Pages

Wednesday, November 27, 2013

Java 7 Tutorial - Strings in switch statement

In Java 7 you can use String in switch statement which was not possible before.

For example before SE 7 you have to use if, else if statements to compare the string values but now you can use Switch statements.

package com.ravi.java7learning;

public class Java7Feature {

public static void main(String[] a)
{
Java7Feature feature = new Java7Feature();
feature.switchDemo("No 1");
feature.switchDemoBeforeSE7("No 1");
}

private void switchDemoBeforeSE7(String input)
{
if(input.equals("No 1"))
{
System.out.println("You have entered :"+input);
} else if(input.equals("No 2")) {
System.out.println("You have entered :"+input);
} else if(input.equals("No 3")) {
System.out.println("You have entered :"+input);
} else if(input.equals("No 4")) {
System.out.println("You have entered :"+input);
} else if(input.equals("No 5")) {
System.out.println("You have entered :"+input);
} else {
System.out.println("You have entered something different :"+input);
}
}

private void switchDemo(String input)
{
switch(input)
{
case "No 1":
System.out.println("You have entered :"+input);
break;
case "No 2":
System.out.println("You have entered :"+input);
break;
case "No 3":
System.out.println("You have entered :"+input);
break;
case "No 4":
System.out.println("You have entered :"+input);
break;
case "No 5":
System.out.println("You have entered :"+input);
break;
default:
System.out.println("You have entered something different :"+input);
}
}

}



No comments:

Post a Comment

 
Blogger Templates