Since Java 7, programmers can use String in the switch-case statement. This simple feature had been waiting for a long time before becoming available in Java 1.7. Imagine we would have to use the following code to test a String variable against a list of values before Java 1.7:

String country = getCountry();	// get country from somewhere

if (country.equals("USA")) {

	// invite American

} else if (country.equals("UK")) {

	// invite British

} else if (country.equals("Japan")) {

	// invite Japanese

} else if (country.equals("China")) {

	// invite Chinese

} else if (country.equals("France")) {

	// invite French
}

Now with Java 1.7 we can replace the above if-else statements by this much simpler and cleaner switch-case statement:

String country = getCountry();

switch (country) {
	case "USA":
		// invite American
		break;

	case "UK":
		// invite British
		break;

	case "Japan":
		// invite Japanese
		break;

	case "China":
		// invite Chinese
		break;

	case "France":
		// invite French
		break;

	default:
		// unsupported country
}

In this switch statement, the String variable country is compared with the String literals in the case clause by the equals() method of the String class. 

It’s recommended to declare String constants to be used in the case clause like this:

// declare String constants in class level
static final String USA 	= "USA";
static final String UK	 	= "UK";
static final String JAPAN 	= "Japan";
static final String CHINA 	= "China";
static final String FRANCE	= "France";

// get country from somewhere
String country = getCountry();

// using Strings in switch-case statement
switch (country) {
	case USA:
		// invite American
		break;

	case UK:
		// invite British
		break;

	case JAPAN:
		// invite Japanese
		break;

	case CHINA:
		// invite Chinese
		break;

	case FRANCE:
		// invite French
		break;

	default:
		// unsupported country
}

So remember to use this new, handy language feature since Java 1.7.

 

Related Topics:

Other Recommended Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Add comment