This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I was just curious why this piece of code prints out x, which is 0 with the System.out.println(x) in the main method when a new object is never initialized, so the variable should never be assigned. Even when I debug, the x variable is not shown, so I can't even tell when the x variable is assigned to 0. Driving me crazy, thanks!
Member variables (whether static or not) are initialised to their default value if you don't initialise them yourself. The default value for an int is zero, so that's what x gets set to.
If you change line 8 to x = 1;, you'll find that x is still zero on line 13.
Joined: Feb 05, 2013
Thank you very much for the quick reply. I actually didn't know integers were automatically initialized to zero. I just assumed there would be a null pointer exception return if it was used before assigned a value.
This automatic initialisation only applies to member variables, though. If it was a local variable then those are not automatically initialised. In that case you'll actually get a compiler error (not an exception) - the compiler won't let you use a variable that might not have been initialised.
One way you could get a NullPointerExceptionis to change line 8 to
This is using the wrapper Integer. That's a reference type, and so it would be initialised to the default value of null. Line 13 would happily print out "null", but you'd hit a problem on line 16. It would try to "unbox" the Integer value, and that will throw a NullPointerExceptionif the value is null.