java - How does the ternary operator evaluate the resulting datatype? -


given piece of code

public class main {      public static void main(string[] args) {         foo(1);         foo("1");         foo(true?1:"1");         foo(false?1:"1");     }      static void foo(int i){system.out.println("int");}     static void foo(string s){system.out.println("string");}     static void foo(object o){system.out.println("object");} } 

this output get:

 int string object object 

i can't understand why in last 2 cases foo(object o) invoked, instead of foo(int i) , foo(string s). isn't return type ternary expression evaluated @ runtime?

edit:

what confusing me assertion that

system.out.println((y>5) ? 21 : "zebra"); 

compiles because (oca study guide - sybex):

the system.out.println() not care statements differnt types, because can convert both string

while point println overloaded accept object types input. quite misleading, imho.

isn't return type ternary expression evaluated @ runtime?

no, absolutely not. contrary way java works, overload resolution etc performed @ compile-time. expect happen if hadn't passed result method, tried assign variable? sort of variable have declared?

the expression's type governed rules of jls 15.25. in both cases, third operand of type string, leading being reference conditional expression, table 15.25-e applied, result of lub(integer,object). lub part refers jls 4.10.4, confusing - type here isn't exactly same object, in cases can considered way.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -