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
a.setValue(b.getValue != null ? b.getValue : 0);
works fine but
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?
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
, whereT
isByte
,Short
, orCharacter
, and the other operand is a constant expression of type int whose value is representable in the typeU
which is the result of applying unboxing conversion toT
, then the type of the conditional expression isU
.
... 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
See more on this question at Stackoverflow