• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static enum variable, works without initialisation?

 
Vince Tan
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Hi there, based on the above code I can't seem to figure out why static enum field does not require initialisation (uncomment line A) before using them. However, a local enum (uncomment line B) will require initialisation?

I understand that local primitive variables must be initialised compared to a instance primitive variable but this does not apply to objects.

Would appreciate it if someone could explain to me the reason behind that. Thanks in advance!

 
Roel De Nijs
Sheriff
Posts: 10666
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static class variables and instance variables get a default value if you don't initialize them explicitly. Local variables don't. You must initialize a local variable before using it. If you don't use the local variable, you don't need to initialize it. All the previous is illustrated in this code snippet:

Hope it helps!
Kind regards,
Roel
 
Vince Tan
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So when you say a default value (for objects or enum) in this case you're referring to null? And local variable (objects or enum) don't even get a null value assigned? Is that right?
 
Roel De Nijs
Sheriff
Posts: 10666
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Vince Tan wrote:So when you say a default value (for objects or enum) in this case you're referring to null? And local variable (objects or enum) don't even get a null value assigned? Is that right?

Yes!

For class and instance variables: default values for everyone! A reference variable (no matter which type) will get null as default value; a primitive variable will get an appropriate default value depending on the primitive type (e.g. false for boolean, 0 for int,...).
For local variables: default values for no one! (that is: no default values at all)
 
Vince Tan
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That clarifies it. Thanks again!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic