This week's book giveaways are in the Java EE and JavaScript forums.
We're giving away four copies each of The Java EE 7 Tutorial Volume 1 or Volume 2(winners choice) and jQuery UI in Action and have the authors on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes Can new keyword ever return null? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Can new keyword ever return null?" Watch "Can new keyword ever return null?" New topic
Author

Can new keyword ever return null?

Sourabh Bawage
Ranch Hand

Joined: Sep 03, 2013
Posts: 33

I am quite sure that



can never return null.....

I just wanted to make sure...because in my company i see previous code which checks for null when an ArrayList is returned ....


SCJP
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10268
    
    8

Welcome to the Ranch.
i see previous code which checks for null when an ArrayList is returned ....

Returned from where? If it is from a method then it can indeed be null.


[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14114
    
  16

When you create an object using the new operator then you will indeed never get null.

It makes no sense to check for null after using new:


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Sourabh Bawage
Ranch Hand

Joined: Sep 03, 2013
Posts: 33


Returned from where? If it is from a method then it can indeed be null.



ya when returned from a method....

for example...



i think as new keyword is used here aswell...it can't return null....
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14114
    
  16

If somewhere in the "more code" (line 8 in your example), dataList is set to null, then the getData() method will return null. But the new operator itself never returns null, so there's no need to check for that.
William Brogden
Author and all-around good cowpoke
Rancher

Joined: Mar 22, 2000
Posts: 12769
    
    5
However - note that if the constructor throws an exception which you ignore, then the reference will indeed be null and result in a nasty surprise later.

Bill
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Can new keyword ever return null?