Imagine that I have the following Java code:
Object value = -4;
Object result = (value instanceof Integer) ? (-((int)value)) : (-((double)value));
System.out.println(result);
The expectation is that this would print 4. The value variable is clearly an integer, and therefore the first branch of the ternary statement should be taken, resulting in it being cast as an int, and negated.
However, this is not what happens, and instead this results in a value of 4.0; meaning that somehow the false branch of the ternary statement is being taken instead (presumably).
Now, lets take the following Java code:
Object value = -4;
Object result;
if (value instanceof Integer) {
result = -((int)value);
}
else {
result = -((double)value);
}
System.out.println(result);
This should be functionally equivalent to the ternary statement, as it is the same logic, but just expanded into the full if / else format. However, it correctly prints the value as the integer 4.
There are some interesting points to note:
If I change the else branch of the ternary to a different value (e.g. just the string
"A"), then the number is cast as an int correctly. For example:Object result = (value instanceof Integer) ? (-((int)value)) : "A";produces the result of
4.If I print out just the condition, it is always true -- the object
valueis always an integer (and therefore the true path should always run):System.out.println(value instanceof Integer);
My personal suspicion based on the two points above is that the ternary is running correctly, and then somehow the integer value is being cast as a double. However, I have no idea how this could be happening.
Another possible explanation could be that this is some sort of compiler bug -- for this reason I'll mention that this is JavaSE 12.0.2 running in Eclipse on macOS 11 beta 3.