1

Given this code

final Double price = new Double(someString);
if(price != null <...>) {

Am I correct in assuming that price can NEVER be null here?

Anders Johansen
  • 10,165
  • 7
  • 35
  • 52
  • 5
    Yes it is never null. – Thomas Jung May 15 '13 at 07:42
  • If you separate the declaration from the assignment and have a try catch around the assignment then price might be null if `someString` is not a number (depending on what you do with the exception) – blank May 15 '13 at 07:47

4 Answers4

6

It can thrown NumberFormatException but it can never be null, because you are using the new keyword.

Habib
  • 219,104
  • 29
  • 407
  • 436
4

Read the specifications: section 15.9.4 of the JLS:

The value of a class instance creation expression is a reference to the newly created object of the specified class. Every time the expression is evaluated, a fresh object is created.

A constructor therefore can never return null. However, an java.lang.OutOfMemoryError may occur.

Erich Schubert
  • 8,575
  • 2
  • 26
  • 42
1

new never results in null, yes.

Sean Owen
  • 66,182
  • 23
  • 141
  • 173
1

Yes, it can never be null. why do you doubt?

vishal_aim
  • 7,636
  • 1
  • 20
  • 23
  • I doubted because the code explicitly checked for it, and I couldn't find that part of the spec where it was explicitly stated this was a useless check. – Anders Johansen May 15 '13 at 08:06