mps88
mps88

Reputation: 33

Java switch case statement is returning different type of values(different data-type) and is assigned to same variable of type var

Following is my code snippet:

Scanner sc = new Scanner(System.in);
int input = sc.nextInt();

var output = switch (input){
  case 1 -> "one";
  case 2 -> '2';
  case 3 -> 3.14;
  default -> 10;
};

System.out.println(output);

Now if I enter 1 as input, it prints "one", for 2 it prints '2', for 3 it prints 3.14 and for the rest it prints 10.

Does this mean datatype of output is decided at runtime according to the return type?

Upvotes: 0

Views: 1254

Answers (3)

Bohemian
Bohemian

Reputation: 425168

The type of output is determined at compile time as something that is Serializable, Comparable and Constable, because that's the closest common ancestor to all of the result.

The object assigned to the variable is determined at runtime is one of String, Character, Double or Integer.


The actual compile type is Serializable & Comparable<? extends Serializable & Comparable<?> & Constable> & Constable (My IDE told me that!).

Upvotes: 0

Michael
Michael

Reputation: 44200

output is inferred to the closest common superclass of all of those types, which is the intersection of Comparable & Serializable. That's slightly more specific than Object, but probably not in a meaningful way in most cases.

Luckily System.out.println accepts any old Object, since it can toString() any possible arguments.

'2' is autoboxed to Character, 3.14 to Double and 10 to Integer.

So output.getClass() would return one of four distinct things.

Upvotes: 1

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

No, the output variable is always determined at compile time as explained here:

With var, the Java compiler infers the type of the variable at compile time, using type information obtained from the variable’s initializer. The inferred type is then used as the static type of the variable.

In this particular case, it is a class implementing Serializable, Comparable, and Constable as you can see editing it in a modern ide

enter image description here

Note that this is not a generic Object. Infact you can't reassign the output variable to a generic Object like an ArrayList.

output = new ArrayList<String>());    // It doesn't compile

while you can reassign to any Comparable Constable and Serializable, for example to a Long

output = 10L;    // It compiles!

Upvotes: 1

Related Questions