This week's book giveaway is in the Testing forum.We're giving away four copies of The Way of the Web Tester: A Beginner's Guide to Automating Tests and have Jonathan Rasmusson on-line!See this thread for details.
Win a copy of The Way of the Web Tester: A Beginner's Guide to Automating Tests this week in the Testing forum!

# Strange IF condition

Duran Harris
Ranch Hand
Posts: 608
Hi:

class Floozit{
public static void main(String[] args)
{
Integer x = 0;
Integer y = 0;
for(Short z= 0;z<5;z++)
if((++x>2)>||(++y)>2)
x++;
System.out.println(x+" "+y);

}
}

The possible output are all 3-4 digits in length though!
At the very least I would think that it prints:
1 1 2 2 4 3 5 4

Punit Singh
Ranch Hand
Posts: 952
for(Short z= 0;z<5;z++)
if((++x>2)>||(++y)>2)
x++;

for loop boundary is upto x++, not after that.

so output will be 8 2. why?
first x=0, y=0

1. z=0,
++x(x=1) > 2 false || ++y(y=1) false
x++ not executed here as both are false.

2. z=1
++x(x=2) > 2 false || ++y(y=2) false
x++ not executed here as both are false.

3. z=2
++x(x=3) > 2 true here y++ will not executed as || is short circuit operator
x++ executed so (x=4)

3. z=3
++x(x=5) > 2 true here y++ will not executed as || is short circuit operator
x++ executed so (x=6)

4. z=4
++x(x=7) > 2 true here y++ will not executed as || is short circuit operator
x++ executed so (x=8)

and finally
System.out.println(x+" "+y);// 8 2

Duran Harris
Ranch Hand
Posts: 608
I thought the for loop included the System.out.println()!

Punit Singh
Ranch Hand
Posts: 952
no no

for(Short z= 0;z<5;z++)
if((++x>2)>||(++y)>2)
x++;

for loop is not using {} braces, so it is just including if() conditional statement, and this if() statement is including x++ statement as if(){} is also not using {} so it can contain only one statement after it.

Alejandro Galvan
Ranch Hand
Posts: 48
Hi:

Originally posted by Duran Harris:
if((++x>2)>||(++y)>2)

In the (++x>2)> expression, is the last greater-than symbol correct? Cause, if it is in your code, it won't compile, if it is not in your code, the output is as said by Punit.

Regards,
[ January 02, 2009: Message edited by: Alejandro Galvan ]

Punit Singh
Ranch Hand
Posts: 952
Ya it is just typing mistake.

 Don't get me started about those stupid light bulbs.