Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

is it ok to assign the the local object reference variable to null ?

 
mike zhang
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
local variables have to initialized. is it ok to assign them to null always ? for example, is the code below ok ?

[ May 28, 2002: Message edited by: Dirk Schreckmann ]
 
Jason Kretzer
Ranch Hand
Posts: 280
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
IMHO, it is perfectly fine to do so. I use this code all the time---particularly with initializing private data members in a class' constructor.
HTH,
 
Rob Ross
Bartender
Posts: 2205
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, you have to initialize your local variables at some point, so this is fine. In fact, it's a pretty good idea to initialize object references to null, since this is what happens for member variables when a new class is constructed.
 
Michael Matola
whippersnapper
Ranch Hand
Posts: 1820
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's possible that I don't 100% understand the question or the intent of the code.
But anyhow, for what it's worth, here's how I'd write that code:

(1) If all you're doing is returning an instance of MyClass and not doing anything else with that instance within this method, then why bother declaring the identifier "myClass" at all, let alone worrying about whether to set it to null?
(2) "return myClass = new MyClass();" -- Sure it's valid syntax, but is anyone really advocating this as good style?
(3) I reversed the condition because it makes it clearer to me that throwing the exception is the exceptional behavior and returning the new instance of MyClass is the standard behavior. (Others might object that testing for a negative is a bad thing...)
 
Marilyn de Queiroz
Sheriff
Posts: 9066
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Looks much cleaner to me, Mike. Testing for the negative is fine IMO because you don't have an else block that way.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic