简体   繁体   中英

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

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;
 }

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM