• Post Reply Bookmark Topic Watch Topic
  • New Topic

ternary operator returning different types  RSS feed

 
John Ali
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi, quick question...
Can a ternary operator return to different types, String or an int for example?
Quick ex.

public void test (int a, int b) {
int d = 0;
String e = "0"
System.out.println(a > b ? d : e);
}
 
Paul Clapham
Sheriff
Posts: 22828
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. In your example, d and e have to be compatible types. I don't want to go into exactly what that means (mostly because I can't give a precise explanation myself) but String and int definitely aren't compatible.

The reason is (again, roughly speaking) that every expression has to have a type assigned to it, and it wouldn't be possible to assign a type to your example "a > b ? d : e".
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Actually the example will work fine in 5.0 or later due to autoboxing. The type will be Object and an Integer or a String will be passed to System.out.println(Object).
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!