Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The type of output is determined at compile time as Serializable, because that’s the closest common ancestor to all of the results.

This compiles:

Serializable x = output;

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading