Hello
I wonder why the output of this:
System.out.println("R=" + ( 4 < 4 ? 1.2 : 2));
Is 2.0 and not 2.
Is Java evaluating the types of both operands and deciding what the returned
type will be?
What is the best place online to read about Java language specifications.
(I come from a C background)
--
Elias
Gordon Beaton - 19 Oct 2006 05:55 GMT
> I wonder why the output of this:
>
> System.out.println("R=" + ( 4 < 4 ? 1.2 : 2));
>
> Is 2.0 and not 2.
Any expression, including one using the conditional operator ?:, can
only have one type that must be determined at compile time. Since one
of the operands is float, the other is promoted to float and it
becomes a float expression.
It's described here, and the rule that's applied is called binary
numeric promotion:
http://java.sun.com/docs/books/jls/second_edition/html/expressions.doc.html#290
293
/gordon

Signature
[ don't email me support questions or followups ]
g o r d o n + n e w s @ b a l d e r 1 3 . s e
Patricia Shanahan - 19 Oct 2006 05:57 GMT
> Hello
>
[quoted text clipped - 6 lines]
> Is Java evaluating the types of both operands and deciding what the returned
> type will be?
Correct. See
http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.25
> What is the best place online to read about Java language specifications.
The Java Language Specification is on-line at
http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html.
Patricia
Luc The Perverse - 19 Oct 2006 09:00 GMT
> Hello
>
[quoted text clipped - 9 lines]
>
> (I come from a C background)
Even in C, though, you can only have one type in the ternary operator for
the two results.
If you had some type which could not be used to define both, then you would
get a compiler error.
--
LTP
:)
Tim Ward - 19 Oct 2006 10:20 GMT
> I wonder why the output of this:
>
[quoted text clipped - 4 lines]
> Is Java evaluating the types of both operands and deciding what the returned
> type will be?
Used to be called "balancing" back in the days when I wrote compilers. All
(typed) languages have to do something like this.

Signature
Tim Ward
Brett Ward Limited - www.brettward.co.uk