문제

In the following code I have two identical conditional assignment operations, one returns an object of type Double, and the second returns the String "Integer".

double d = 24.0;

Number o = (d % 1 == 0) ? new Double(d).intValue() : new Double(d).doubleValue();
String result = (d % 1 == 0) ? "Integer" : "Double";

System.out.println(o.getClass()); // prints "class java.lang.Double"
System.out.println(result); // Integer

Why are the exact same expressions returning two different things?

도움이 되었습니까?

해결책

Well, that is because of the JLS specs for the conditional operator:

Otherwise, if the second and third operands have types that are convertible (§5.1.8) to numeric types, then there are several cases:

  • ...
  • Otherwise, binary numeric promotion (§5.6.2) is applied to the operand types, and the type of the conditional expression is the promoted type of the second and third operands.

Numeric promotion is defined here in §5.6.2. It says:

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

  • If either operand is of type double, the other is converted to double.
  • ...

다른 팁

Well 0.0 is still == to 0

System.out.println(0 == 0.0); // equals true

http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top