aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes operator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "operator " Watch "operator " New topic
Author

operator

anita dhar
Ranch Hand

Joined: Jul 14, 2007
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


please tell me properly about pre and post increment
thanks in advance
Praveen Seluka
Ranch Hand

Joined: Jul 17, 2007
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

Joined: Jul 14, 2007
Posts: 69
i am coinfused with pre and post incremant can any one exaplain me

x= 2;
Integer y = 7 ;

++x , ++y,x++,y++;
thnaks in advance
Praveen Seluka
Ranch Hand

Joined: Jul 17, 2007
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

Joined: Jul 14, 2007
Posts: 69
Thanka praveen no i got it
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: operator
 
Similar Threads
Doubt in K&B concerning topic :Operators
output
Increment operator
Strange IF condition
increment doubt