Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!

# operator

anita dhar
Ranch Hand
Posts: 69
hi , can any one explain this program , this program is from K&B from chapter 4 of self test

class Foozit
{
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);
}
}

o/p 8 2

Praveen Seluka
Ranch Hand
Posts: 95
Hi

First of all

Integer x=0;
x++;//this is possible as java 5 does autoboxing

here

1.z=0
preincrement on x(++x),so it increments x and y before checking >2
it will be (1>2) || (1>2)
since if condition is false,it wont execute x++;

now x=1 and y=1

2.z=1

it will be (2>2)||(2>2)
condition false

now x=2 y=2
3.z=2
Its important now.
if || is used ,then if the first condition is true,then it wont even look at the second one (++y>2)
so it preincrements x which will be 3
If condition satisfied.
x++;
Now x=4 y=2

4.z=3
Same thing happens as z=2
At the end x=6 y=2

5.z=4
Same thing happens as z=2
At the end x=8 y=2

gets out of the loop and prints 8 2

Thanks
Praveen SP

anita dhar
Ranch Hand
Posts: 69
i am coinfused with pre and post incremant can any one exaplain me

x= 2;
Integer y = 7 ;

++x , ++y,x++,y++;

Praveen Seluka
Ranch Hand
Posts: 95
Integer i=2;

now if ((i++)==2) then it will assign i=2 and will make the increment only after when it goes to the next line.

output : 3

Now if preincrement operator is used

output : 3

Praveen SP

anita dhar
Ranch Hand
Posts: 69
Thanka praveen no i got it