Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Round Up game questioin

 
Tom Johnson
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
In the "round up" game on this site for sample questions for programmer exam, question #73 is as follows

"Member (instance) variables are always assigned a default value if not explicitly initialized?"

The answer is true according to the game :
Answer:true
"Member variables are always given a default value -- numerical primitives get zero, chars get \'u000', and object references get null".

I believe this is incorrect as instance variables that are object references AND final do not get null -> what use would they be then!!

ie



buff DOES NOT get assigned to null!! If it did we couldnt set it to what we want in the constructor or static initializer block!

What do ye think??

Tom
 
peter cooke
Ranch Hand
Posts: 317
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am still fairly junior for all the certs I hold.

Please correct me where I am wrong.
The reason a constructor can set the value of final member is that the constructor is called at a special phase of instance construction.
Since the instance is being constructed the constructor can initialize the member to a new value.

I seem to recollect that constructors are not methods.
 
Tom Johnson
Ranch Hand
Posts: 142
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Peter
The only reason that a constructor can set the value of a final variable is that is has has not been assigned a value upon declaration. Hence if, as like in the test answer, the reference is given null then the constructor would not be able to reassign it
eg


Hence the constructor cannot set it if its already set at declaration.

So what im saying is that


is OK only because buf is actually blank (NOT NULL) after declaration, where as the test answer indicates it is actually initialized to null



The same is true of final primitives


Tom
 
Anupam Sinha
Ranch Hand
Posts: 1090
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think that this has been discussed before. In fact even a final instance variable is assigned a default value and later is assigned a new one.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic