Syntax
switch (expression){
case one:
// code block
break; // terminate the sequence
case two:
// code block
break;
default: // default will execute when none of above case does.
// code block
// default is not at end put break after it
}
→ If break is not used then it will continue with other cases.
→ duplicate cases are not allowed.
Enhanced Syntax
switch(expression){
case one -> // do this;
case two -> // do this;
case three -> // do this;
default -> // do this;
}
x.equals("word") → Here equals only checks value not reference.
x == "word" → here it checks reference
import java.util.Scanner;
public class Switch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String fruit = in.next();
if(fruit.equals("mango")){
System.out.println("king of the fruit");
}
if(fruit.equals("apple")){
System.out.println("red color fruit");
}
if(fruit.equals("grape")){
System.out.println("green color fruit");
}
}
}
This is how we had to do it without switch
import java.util.Scanner;
public class Switch {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String fruit = in.next();
switch (fruit) {
case "mango" -> System.out.println(("King of fruits"));
case "apple" -> System.out.println("red color fruit");
case "grape" -> System.out.println("green color fruit");
default -> System.out.println("what kinda fruit you like");
}
}
}