Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why this Output?

 
Joe Harry
Ranch Hand
Posts: 10124
3
Eclipse IDE Mac PPC Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
class A{
static{
int x = 5;
}
static int x,y;
public static void main(String args){
doStuff();
System.out.println(y++ + x + ++x);//prints 4 instead of 14???
}
static void doStuff(){
x++;
++y;
}
}

Why the above code prints 4. Shoudn't the value of x be taken as 5 instead of 0? Please anyone.

Regards,
Jothi Shankar Kumar. S
 
Dave McIntyre
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

There are two different variables x declared. The first goes out of scope at the end of the tiny block in which it is declared. So the x that is still alive when you you call main() is the second one, which just gets initialised with its default value of 0
 
Prameela Nair
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The x in the static initializer block ends with the block itself.
the static vars x & y are then initialized to 0 and are incremented in the function doStuff(). so x = y = 1; [Note: here post/pre increments dont make an impact]

In the System.out the incremented values are used for adding up as follows :-
System.out.println((1)++ + (1)+ (2)); [Note: incase of post increment the value is fist utilized and then incremented...as here for y]
hence the output 4

HTH,
Prameela
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic