• Post Reply Bookmark Topic Watch Topic
  • New Topic

Help: Passing method argument through ternary operator  RSS feed

 
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Code:



When I execute this code I get the following Error at Line 3


Using similar type in the ternary operator does not give error. But using different types gives error only to the method call but it works for the call

When I add another overloaded method , then the //Line 3 compiles.

Can anyone please explain me this scenario?
 
Ranch Hand
Posts: 100
2
Eclipse IDE Java Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
  
According to JLS
https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.25,
Otherwise, the second and third operands are of types S1 and S2 respectively. Let T1 be the type that results from applying boxing conversion to S1, and let T2 be the type that results from applying boxing conversion to S2.

The type of the conditional expression is the result of applying capture conversion (§5.1.10) to lub(T1, T2) (§15.12.2.7). 


For ternary expression,

condition ? T1:T2

I think informally it should mean that, the result data type is least upper bound (LUB) of two possible result types T1 and T2.

In our case, two possible types are Integer (after autoboxing) and String.

Hence, their lub() should be Object. Object is not argument of any given methods. Hence, compiler error for invocation of test() methods.

But in System.out.println(), we try to form a string of given argument.

Here, we will convert the result of ternary expression to String. Hence, no compiler error.






 
Marshal
Posts: 56600
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Make the second and third arguments of ?: the same type whenever possible. That way you will not have any problems about what type the whole expression returns.
myBoolean ? 1.23 : 456
Is that an int or a double? What sort of variable can you assign that expression to?
myBoolean ? 123 : 456
Easy: it is an int. No risk of confusion. Also remember that ?: has a very low precedence, only one above =, so you may need () around the expression.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!