This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread 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


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: 10426
    
    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: 14194
    
  20

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 8 API documentation
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: 14194
    
  20

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: 12792
    
    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?