aspose file tools*
The moose likes Beginning Java and the fly likes When to Initialize Objects to null or new Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "When to Initialize Objects to null or new" Watch "When to Initialize Objects to null or new" New topic
Author

When to Initialize Objects to null or new

Elle Atechsy
Ranch Hand

Joined: Jan 23, 2004
Posts: 96
Hi Everyone,

Please help me to understand when to initialize objects to null or new. For example, in a class method, I need an ArrayList that will receive some objects as I loop through a recordset. It seems when ever I do the following, it always give me a null pointer acception.

ArrayList sampArrayList = null;

Then when I change it to the following, the error goes away.

ArrayList sampArrayList = new ArrayList();

To prevent running into the same issue over & over, can anyone tell me when should I initialize to null or new, and why?

Much appreciation in advance for any responses.

Lulu

[ September 04, 2005: Message edited by: Lulu Carr ]
[ September 04, 2005: Message edited by: Lulu Carr ]
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
You should initialize your variables at the top of the class or withing a method if it is a method-local variable. You can initialize to null if you expect to have a setter method called to initialize a reference from another class. You can, but IMO you should not do that. Instead, initialize with a non-null value. This is particularly true with collections like ArrayList. Ensuring you have no null references, ever, is an excellent strategy.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

A compelling argument for initializing references at the point of declaration is to ensure that all members are available to the constructor.


"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Never initialise a local to null, and always assign your fields at construction time* or in an initializer. The existence of null is a horrible flaw.

*Passing parameters to constructors is a poor practice, but often times, one must concede due the extreme verbosity of the correct alternative in a Java context.


Tony Morris
Java Q&A (FAQ, Trivia)
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
Originally posted by Tony Morris:
Never initialise a local to null,...


There are never absolutes when it comes to programming, even this one

When I see the words "never" or "always", I typically question these kinds of things. For example, initializing to null allows for lazy initialization (i.e. only initializing when you need it). For local variables, this probably doesn't occur as often as it does for member variables.

Perhaps a more compelling example of when to initialize a local variable to null is if you need to catch an exception that the constructor may throw. For example, I recently found a situation where I had to write code like this:

Because I needed the in variable in the finally clause, I had to declare it outside the try block. I'm sure there are other ways to deal with this problem, but this is what I used.

The moral of the story is "never say never".

Layne


Java API Documentation
The Java Tutorial
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Layne Lund:
... When I see the words "never" or "always", I typically question these kinds of things...

Always question these. Always, always, always...
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
A sign on my wall says "The answer is never always, rarely never, and probably not 1".

Initializing an object via constructor arguments is recommended (in circles that don't include Tony ) because it assures that an object is not created and left in a semi-initialized state. That's in contrast to create with a no argument constructor and a bunch of setField() methods. Forget to set one field and the object may be inconsistent.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Layne]: Because I needed the in variable in the finally clause, I had to declare it outside the try block. I'm sure there are other ways to deal with this problem, but this is what I used.

This is a situation I encounter frequently - here's how I usually handle it:

If the constructor call completes successfully, then you've definitely got an instance (not null), and it must be closed. If something goes wrong, an exception will be thrown, to be handled wherever else in the program is deemed appropriate.


"I'm not back." - Bill Harding, Twister
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Without having to back my other assertions, since the doctrine is prolific and has reached critical mass, this one is easily contested:


Initializing an object via constructor arguments is recommended

If it's not an obvious violation of encapsulation, then I don't know what is, though granted, this is the "beginner" forum. It exposes a construction detail to clients of the contract! Simply provide an "interface" (since you are "interfacing" after all - be nice to your clients) that abstracts that construction detail.

Instead of:
interface I{void m();}
final class X implements I{X(int i){} public void m(){}}

Prefer:
interface IntI{I get(int i);}
final class IntX implements IntI{IntX(){}public I get(int i){return new I(){/* insert X implementation details here */};}}

Now that nasty construction detail is an interface and no poor client is bound to it forever and ever. Clients should only bind to interfaces (since they are interfacing to the service that your provide them right?) and a single point of entry for implementation detail (hence, constructors should always be declared private).

I'm probably reaching the acceptable threshold of unorthodox speech here (this is an internet forum and this is software engineering after all).
When the Catholic Church demands that I recant the universally accepted religious truth beyond all doubt and "fit into that box", I will simply go into exile.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Taking the argument to an extreme, using new with a classname is a wicked form of coupling that should always be avoided. Micah Martin had an interesting blog about the pros & cons of always providing factories. As the simplest possible default, a class could be a factory for itself. At least you could change the factory method to return something new if you ever had to. A factory for anonymous classes generated on the fly can certainly work, too, but defining all my concrete methods this way seems unnecessary.
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
Originally posted by Stan James:
Taking the argument to an extreme, using new with a classname is a wicked form of coupling that should always be avoided. Micah Martin had an interesting blog about the pros & cons of always providing factories. As the simplest possible default, a class could be a factory for itself. At least you could change the factory method to return something new if you ever had to. A factory for anonymous classes generated on the fly can certainly work, too, but defining all my concrete methods this way seems unnecessary.


Though I haven't read that blog, I assume the point is exactly the same one that I refer to when I declare that all constructors should be private (the optimal solution in a Java context, but not optimal ultimately). You are right in that 'new' violates encapsulation, and ultimately, valid software requirements (digression in reasoning steps omitted), but it's unavoidable within the confines of Java, hence declaring constructors private. In fact, a language that I am working on has (the equivalent of) explicit return values from constructors, which, to Java fans, has the benefits of removing all the verbosity that comes with declaring all constructors private. This is not the only advantage though, just one that I foresee will be appealing.

In any case, this thread of conversation seems to exceed 'Java (Beginner)'.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Yes, beginner it ain't but it's pretty interesting. If somebody wants to move it or pick up from here in the OO forum or some place, that would be fine.

I don't worry about constructors violating encapsulation so much as creating dependencies. When you say "x = new ClassName()" it becomes harder to replace instances of ClassName with instances of something else. I often use factories that create instances of classes determined through configuration with Class.forName().newInstance() for command and strategy kinds of things and plug-in components. I don't see any value in private constructors here, just the hassle of getting a static factory method and executing it.
Chris James
Greenhorn

Joined: Sep 07, 2005
Posts: 19


Always... When I see the words "never" or "always", I typically question these kinds of things...


I Always listen to experts but Never take there advice as they Usually are mistaken

Seriously though null is a perfectly valid value particularly in an imperfect world.

I am new to java but like C and C++ testing a object to see if it is valid is important.

In fact as far as I can see the only way to "destroy" an object is to make sure it is no longer referenced by anything therefore one must assign the reference to null

So if null is valid there, then it should be valid where ever it makes sense to do so. such as a class variable that may or may not be used.

Why instantiate it if it is going to be unused. or if you don't know ahead of time what its construction parameters will be?

2p
Chris


In an interesting and related aside...

In the original numbering system invented there was no zero, all numbers started from 1. either you had 1 (or more) rock(s) or it wasn't an issue.
If asked, "do you have any rocks?" the answer was "no" not "I have zero rocks"

BUT it wasn't until zero was 'invented' that mathematics became possible
[ September 07, 2005: Message edited by: Chris Topher ]
Tony Morris
Ranch Hand

Joined: Sep 24, 2003
Posts: 1608
I often chuckle at this fear of "always" and "never".
The fact that it was well established as a sound method of reasoning in the 15th century and that we almost all do it every single day in perhaps an ad hoc manner, even if we inadvertantly take it for granted, the important point is that an axiom must be defined, since the Scientific Method cannot derive ultimate truth, only approach asymptotically. The only way to do this is by making absolute statements, and assuming the context/axiom. If the axiom falls apart, so does the "always/never" (in simple terms). The sky is not blue, it just appears blue.

"Never say "always" or "never" and always make sure you obscure your reasoning in some way so as to stand correct for the most broad set of contexts, then you can never be wrong and always be correct".
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: When to Initialize Objects to null or new
 
Similar Threads
Missing Computer Science Foundation
When to Initialize Objects to null or new
Collection : trouble with order in a TreeSet
plugin-cfg.xml uri name values?
When to use Instance vs Local variables