Nb179
Nb179

Reputation: 67

Are && statements and nested conditionals of the following code equivalent?

If x and y are int variables. Are the following two segments of Java code behaviourally equivalent for all values of x and y? Explain why, or why not.

Version 1:

if (x > 10)
  {
  if (y < 20)
  {System.out.print("hi");
  }
}

Version 2:

if (x > 10 && y < 20)
{
System.out.print("hi");
}

I think it is equivalent but I just want to make sure I'm not missing anything. I don't see how they cannot be equivalent. Thanks.

Upvotes: 1

Views: 44

Answers (4)

Andreas
Andreas

Reputation: 159114

Yes, they are equivalent, but the second one is shorter, and you can add a single else clause, which you cannot do in the first, because you'd have to write two independent else clauses there.

Whether one or two else clauses should be used depends on what your logic requires, so both forms may be appropriate.

I would generally recommend the second one, but if you don't need a single else clause, and the expressions are large, the first one may end up being more readable.

Upvotes: 1

Gianfranco Pesce
Gianfranco Pesce

Reputation: 21

Yes they are equivalent also from the semantic point of view.

Upvotes: 0

Frank Puffer
Frank Puffer

Reputation: 8215

Yes, they are.

The important point which might not be so obvious is that in both versions the second comparison is only evaluated if the first one results in 'true'.

Upvotes: 1

KarelPeeters
KarelPeeters

Reputation: 1465

Yes, they are completely equivalent. In situations like these it comes down to picking the one you think is clearest.

Upvotes: 1

Related Questions