my dog learned polymorphism
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why this Output?" Watch "Why this Output?" New topic

Why this Output?

Joe Harry
Ranch Hand

Joined: Sep 26, 2006
Posts: 10033

class A{
int x = 5;
static int x,y;
public static void main(String args){
System.out.println(y++ + x + ++x);//prints 4 instead of 14???
static void doStuff(){

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

Jothi Shankar Kumar. S

SCJP 1.4, SCWCD 1.4 - Hints for you, Certified Scrum Master
Did a rm -R / to find out that I lost my entire Linux installation!
Dave McIntyre

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

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 here for y]
hence the output 4

I agree. Here's the link:
subject: Why this Output?
It's not a secret anymore!