aspose file tools*
The moose likes Beginning Java and the fly likes Constructor in Same Class as main method 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 » Java » Beginning Java
Bookmark "Constructor in Same Class as main method" Watch "Constructor in Same Class as main method" New topic
Author

Constructor in Same Class as main method

Dan Hughes
Greenhorn

Joined: Feb 05, 2013
Posts: 2
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

Joined: Apr 06, 2010
Posts: 4246
    
    7

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

Joined: Feb 05, 2013
Posts: 2
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

Joined: Apr 06, 2010
Posts: 4246
    
    7

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.
 
wood burning stoves
 
subject: Constructor in Same Class as main method
 
Similar Threads
final instance variable
Increment Operator and Assignment Operator
Instance variables
Objective 2.1
AOOB exception in my CODE-PLEASE HELP!