Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ternary operator

 
challa
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Ternary

{

public static void main(String args[])

{

int a = 5;

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

}

}


I thought the output is
value is - 9

but the output is
value is -9.0

why? can anyone please explain?
 
vidya sagar
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi purnima

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

Whenever u do ternary operation, then values should be in the same data type, if not compiler automatically promotes to the larger data type.If compiler cannot do so it simply throws error.

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

In this case Error
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic