The type of the expression in the switch inside Java can be a string type __string

Source: Internet
Author: User
Tags case statement

The format is as follows:







When the value of an expression is equal to the value of a case statement, all statements underneath it are run until a break is encountered. If the value of any case statement is not equal to the value of the expression, the statement under optional label default is run.

(a) in the JDK version after Java 1.7, the type of the expression in the switch in Java can be of type string. (The JDK version must be 1.7, 1.5 may only be int or char type!)

The code is as follows:

Package test0428;


Import Java.io.File;
Import Java.util.Scanner;


/*
* Java.io.file representation file (directory)
* The file class is only for directory access and cannot be used for file content access
* */
public class Testfile {
Understanding constructors, alt+/view Help
public static void Main (string[] agrs) {
SYSTEM.OUT.PRINTLN ("Please choose");
String Str=in.next ();
Switch (str) {
Case "ABC":
SYSTEM.OUT.PRINTLN ("abc");
Break
Case "BCD":
System.out.println ("BCD");
Break
Default:
SYSTEM.OUT.PRINTLN ("Default");
Break

}
}
}

The results of the operation are as follows:


Please select
Abc
Abc


(b) The expression in the switch cannot be a Boolean type. If you want to convert to a Boolean type, you can only convert to a string and then use the following code:

Boolean flag1=true;
Switch (flag1+ "") {
Case "true":
System.out.println ("Boolean: true");
Break
Case "Flase":
System.out.println ("Boolean type: Flase");
Break
Default:
SYSTEM.OUT.PRINTLN ("Default");
Break
}


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.