Java : Strictly type checking fails?

Suppose I have two classes as follows

class A
{
  private Double value;
  ...
  //getters and setters
}

class B
{
  private Double value;
  ...
  //getters and setters
}

Update

public static void main(String[] args)
{
    A a = new A();
    B b = new B();
    a.setValue(b.getValue() != null ? b.getValue() : 0); //works!
    a.setValue(0); //doesn't work
}

And the statement

  1. a.setValue(b.getValue != null ? b.getValue : 0); works fine but

  2. a.setValue(0) doesn't works I need to set the value as 0D to make it work.

why I need not write a D along with 0 in first case?

Jon Skeet
people
quotationmark

I suspect the problem is that you've got

setValue(Double value)

Now the type of your conditional expression (b.getValue() != null ? b.getValue() : 0) is double, following the rules of JLS section 15.25.2:

If one of the operands is of type T, where T is Byte, Short, or Character, and the other operand is a constant expression of type int whose value is representable in the type U which is the result of applying unboxing conversion to T, then the type of the conditional expression is U.

... and that's fine, because you're then calling setValue with a double argument, and that can be boxed to Double.

However, when you try calling setDouble(0) you're trying to call setValue with an int argument, and that can't be boxed to Double... hence the error, and hence the success when you pass 0D instead.

Note that you don't need method calls etc to demonstrate this - here's a simple example:

Double x = 0d;        
Double y = true ? x : 0; // Fine
Double z = 0; // Error

people

See more on this question at Stackoverflow