? : behavior question

  • Follow


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 


0
Reply lallous (276) 10/17/2006 9:32:25 PM

On Wed, 18 Oct 2006 00:32:25 +0300, lallous wrote:
> 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

-- 
[ 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 
0
Reply n.o.t (478) 10/19/2006 4:55:19 AM


lallous wrote:
> 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?

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
0
Reply pats (3215) 10/19/2006 4:57:26 AM

"lallous" <lallous@lgwm.org> wrote in message 
news:4poeglFjmbbeU1@individual.net...
> 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)

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

:) 


0
Reply sll_noSpamlicious_z_XXX_m (653) 10/19/2006 8:00:14 AM

"lallous" <lallous@lgwm.org> wrote in message
news:4poeglFjmbbeU1@individual.net...
>
> 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?

Used to be called "balancing" back in the days when I wrote compilers. All
(typed) languages have to do something like this.

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


0
Reply tw22 (185) 10/19/2006 9:20:46 AM

4 Replies
31 Views

(page loaded in 0.088 seconds)


Reply: