? : behavior question

L

lallous

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)
 
G

Gordon Beaton

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
 
P

Patricia Shanahan

lallous said:
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
 
L

Luc The Perverse

lallous said:
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.
 
T

Tim Ward

lallous said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,266
Messages
2,571,089
Members
48,773
Latest member
Kaybee

Latest Threads

Top