Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Can new keyword ever return null?

 
Sourabh Bawage
Ranch Hand
Posts: 33
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ....
 
Maneesh Godbole
Saloon Keeper
Posts: 11021
12
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
 
Sourabh Bawage
Ranch Hand
Posts: 33
Eclipse IDE Java Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 15214
36
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13058
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic