Ternary operator with different types of expressions

Lemonov :

I was playing with ternary operator and noticed something odd. I have code below:

class Main {

  static void foo(int a){
    System.out.println("int");
  }

  static void foo(String a){
    System.out.println("String");
  }

  static void foo(Object a){
    System.out.println("object");
  }

  public static void main(String[] args) {
    foo(2==3 ? 0xF00:"bar");
    System.out.println((2==3 ? 0xF00:"bar").getClass().getName());
  }
}

Which results in

object

java.lang.String

First line of result shows that this instruction passed to foo method with object parameter.

Second line that the instruction itself results in String.

Question:

  1. Why if result is String compiler decides to go with Object?

  2. Is this because of the type ambiguity?

  3. If yes then why getting class name returned java.lang.String?

Leo Aso :

In Java, you have compile time type information and you have run time type information. Compile time type information is what the compiler can deduce about the type of a value or expression just by looking at it, but without executing it. When the compiler sees the expression

2 == 3 ? 0xF00 : "bar"

It does not know whether 2 == 3 will be true or false, because it does not execute code. So all it knows is that the result can be an Integer, or a String. So when the time comes to pick which foo method to call, it picks the one that accepts Object, since that is the only one that it knows will work in both scenarios.

However, when the code is actually running, 2 == 3 will be false, and the result will be a String, whose getClass() method will return String.class. And that is what you need to note: getClass() does not return the type that the variable had at compile time, but it returns the actual type of the object that the variable holds at run time. i.e.

Object o = "Hello!";
System.out.println(o.getClass());

will print java.lang.String, because even though to the compiler it is an Object, at run time it is actually a String.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=444608&siteId=1