printing problem

G

gk

int a = 5;

System.out.println("Value is - " + ((a < 5) ? 9.9 : 9));

output: 9.0

where from 9.0 came from ? there is 9 but NOT 9.0

see, the condition a<5 is false.....so this should print 9

but output is 9.0
 
G

Gordon Beaton

int a = 5;

System.out.println("Value is - " + ((a < 5) ? 9.9 : 9));

output: 9.0

where from 9.0 came from ? there is 9 but NOT 9.0

see, the condition a<5 is false.....so this should print 9

but output is 9.0

An expression 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#290293

/gordon
 
P

Patricia Shanahan

Gordon said:
An expression 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#290293

/gordon

If this is specifically for printing, could you use strings rather than
numbers?

System.out.println("Value is - " + ((a < 5) ? "9.9" : "9"));

Patricia
 

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,078
Members
48,772
Latest member
Backspace Studios

Latest Threads

Top