aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why this Output? 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 "Why this Output?" Watch "Why this Output?" New topic
Author

Why this Output?

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 9243
    
    1

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


SCJP 1.4, SCWCD 1.4 - Hints for you, SCBCD Hints - Demnachst, SCDJWS - Auch Demnachst
Did a rm -R / to find out that I lost my entire Linux installation!
Dave McIntyre
Greenhorn

Joined: Oct 22, 2006
Posts: 8

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

Joined: Oct 24, 2006
Posts: 12
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why this Output?
 
Similar Threads
abstract class instantiation
Method overloading
code explanation needed
static variables
DOUBT from scjp book