'Why there is no compilation error when I am using different data types for switch expression and case value in this case
public class Conditionsif {
public static void main(String[] args) {
// TODO Auto-generated method stub
int day=1;
switch(day){
case '1':
System.out.println("Monday");
break;
}
}
}
There is no compilation error in above though switch expression is integer data type and case value is character
Solution 1:[1]
Its because of implicit casting ascii value of a is 97
switch(97){
case 'a': System.out.println("a"); break;
case 'b': System.out.println("b"); break;
case 'c': System.out.println("c"); break;
}
Solution 2:[2]
When you use ' ', this means you use char data type. char data type accept one character only , for example : char x = 'h';
And also accept the Ascii code for the character for example : char x = 104;
So case '1' mean compare variable day with value equal to value 1.
if you modify code as following , this code will print Monaday.
int day=97;
switch(day){
case 'a':
System.out.println("Monday");
break;
}
Best Regards.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Abhishek Bansal |
| Solution 2 | Osama Soliman |
