return value - Passing method argument through ternary operator in java -


code:

public class foo {      static void test(string s){         system.out.println("string called");     }      static void test(int s){         system.out.println("int called");     }      public static void main(string[] args) throws exception {          test(5>8? 5:8);         // line 1         test(5>8? "he":"ha");   // line 2          test(5>8? 5:"ha");      // line 3          system.out.println(5<8? 5:"ha"); //line 4     } } 

when execute code following error @ line 3

foo.java:24: error: no suitable method found test(int#1)                 test(5>8? 5:"ha");              // line 3                 ^ 

using similar type in ternary operator not give error. using different types gives error method call test(5>8? 5:"ha"); works call system.out.println(5<8? 5:"ha");

when add overloaded method static void test(object s){}, //line 3 compiles.

can please explain me scenario?

every expression in java has type. there complicated rules in java language specification, in section on the conditional operator tell how find type of conditional expression such 5 > 8 ? 5 : "ha". in simple terms, specific type both second , third arguments members of.

  • for 5 > 8 ? 5 : 8, both 5 , 8 int, whole expression has type int.
  • for 5 > 8 ? "he" : "ha", both "he" , "ha" string, whole expression has type string.
  • for 5 > 8 ? 5 : "ha", specific type fits both 5 , "ha" object. whole expression has type object.

now since have versions of test accept int , accept string, expressions test ( 5 > 8 ? 5 : 8 ) , test ( 5 > 8 ? "he" : "ha" ) both compile.

but if don't have version of test accepts object, test ( 5 > 8 ? 5 : "ha" ) can't compile.

this over-simplification. rules more complicated i've described, because consider various cases involving null operands, auto-boxing , auto-unboxing.


Comments

Popular posts from this blog

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -