Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

ternary operator  RSS feed

 
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
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!