Home > Java > javaTutorial > How to use switch statement in Java and examples

How to use switch statement in Java and examples

PHPz
Release: 2023-04-22 20:46:06
forward
2074 people have browsed it

Explanation

1. In the switch statement, the variable type can be: byte, short, int or char. Since JavaSE7, switch supports the String type, and case labels must be string constants or literals.

2. The switch sentence can have multiple case sentences. Each case is followed by a value and a colon.

3. The switch sentence can contain a default branch, which is usually the last branch of the switch sentence (can be at any position, but usually at the last one). When default is executed, the value of no case statement is equal to the variable value. The default branch does not require a break statement.

Example

Scanner in = new Scanner(System.in);
System.out.println("请输入当前月份");
int month = in.nextInt();
switch (month){
    case 1 :
        System.out.println("一月");break;
    case 2 :
        System.out.println("二月");break;
    case 3 :
        System.out.println("三月");break;
    case 4 :
        System.out.println("四月");break;
    case 5 :
        System.out.println("五月");break;
    case 6 :
        System.out.println("六月");break;
    case 7 :
        System.out.println("七月");break;
    case 8 :
        System.out.println("八月");break;
    case 9 :
        System.out.println("九月");break;
    case 10 :
        System.out.println("十月");break;
    case 11 :
        System.out.println("十一月");break;
    case 12 :
        System.out.println("十二月");break;
    default:
        System.out.println("错误的输入");break;
}
Copy after login

The above is the detailed content of How to use switch statement in Java and examples. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template