File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Constructor in Same Class as main method

 
Dan Hughes
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Everyone,
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!

 
Matthew Brown
Bartender
Posts: 4549
8
Java Netbeans IDE Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dan. Welcome to the Ranch!

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.
 
Dan Hughes
Greenhorn
Posts: 2
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thanks again!
 
Matthew Brown
Bartender
Posts: 4549
8
Java Netbeans IDE Scala
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You'd never get a NullPointerException, because int is a primitive type, and these can't be null.

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 NullPointerException is 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 NullPointerException if the value is null.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic