• Post Reply Bookmark Topic Watch Topic
  • New Topic

PreIncriment and post increment doubt  RSS feed

 
dhanu ubale
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all,
Can any one give me explanation for this program and tell me the internal details.


public class IncDemo
{
public static void main(String args[])
{
int x=1,y=0;
System.out.println(x + y + ++x );
}
}

Why output is 3?

According to me it should be 4.Since ++x has more precedence than it should be evaluated first.
Therefore:
First x+y+2
next 2+0+2=4.
 
bnkiran kumar
Ranch Hand
Posts: 176
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
NO, compiler goes on substituting values from left to right, so

expression is like 1+0+2 which results in 3,

first compiler substitutes value for x then y, then it performs ++x not directly first ++x.

hope you got it.

 
vidya sagar
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi

Check the link for Operator precedence
 
bnkiran kumar
Ranch Hand
Posts: 176
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
vidya sagar
have you cleared ocp 9i, i want some details on it, can you share some details please. i cleared scjp 1.4
 
dhanu ubale
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks kiran got the concept very clearly. But in C language the awnser is 4. Kiran can u share ur SCJP final exam experience ie whether time will be sufficient or not and complexity of questions and which areas to stress on.

-Dhanu
 
swapnil paranjape
Ranch Hand
Posts: 126
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanx kiran
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!