File APIs for Java Developers Manipulate DOC, XLS, PPT, PDF and many others from your application. http://aspose.com/file-tools
Big Moose Saloon
 Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies Register / Login Win a copy of REST with Spring (video course) this week in the Spring forum!

# Strange IF condition

Duran Harris
Ranch Hand

Joined: Nov 09, 2008
Posts: 606

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

===>SCJP 1.5(72%)<===
==>SCWCD1.5(76%)<===
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
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

SCJP 6
Duran Harris
Ranch Hand

Joined: Nov 09, 2008
Posts: 606

I thought the for loop included the System.out.println()!
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
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

Joined: Jan 02, 2008
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 ]

SCJP 5.0<br />Preparing SCWCD
Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
Ya it is just typing mistake.

subject: Strange IF condition