Meaningless Drivel is fun!*
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 Android Security Essentials Live Lessons this week in the Android 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: 10172
    
    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: 14074
    
  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: 14074
    
  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: 12761
    
    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?
 
Similar Threads
return
Question on using return value and not.
help needed in copying an Array
JUnit - Testing someone elses code
Method Local Inner Class Pg 671 Kathy Sierra and Bates SCJP 6