Skip to main content

(How) can I improve the If conditional code

Pl review the code below.  Can this be improved or is there an alternate way to write this code:

String s = "1";

if( s.equals("1"))
    System.out.println("One");
else if (s.equals("2"))
    System.out.println("two");
else
    System.out.println("some number");


Highlight the lines below for the answer:
With Java 7 and later, one can switch/case on String objects
switch(s) {
    case "1":
        System.out.println("One");
        break;
    case "2":
        System.out.println("two");
        break;
    default:
        System.out.println("some number");

}

Comments