Java switch Statement

πŸ”„ Java switch Statement

The switch statement is used to select one of many code blocks to execute based on a variable’s value.
It is an alternative to long chains of if...else if.


βœ… Syntax of switch

switch (expression) {
case value1:
// Code block
break;
case value2:
// Code block
break;
...
default:
// Default code block
}

πŸ“Œ Important Notes:

  • The break keyword stops the execution after a matching case.

  • If break is omitted, execution continues into the next case (fall-through).

  • default runs if no case matches (optional but recommended).


πŸ“˜ Example 1: Basic switch

public class Main {
public static void main(String[] args) {
int day = 3;

switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
}
}

πŸ“Œ Output:

Wednesday

πŸ“˜ Example 2: Without break (Fall-Through)

public class Main {
public static void main(String[] args) {
int number = 2;

switch (number) {
case 1:
System.out.println("One");
case 2:
System.out.println("Two");
case 3:
System.out.println("Three");
default:
System.out.println("Done");
}
}
}

πŸ“Œ Output:

Two
Three
Done

πŸ“˜ Example 3: switch with String

public class Main {
public static void main(String[] args) {
String role = "Admin";

switch (role) {
case "Admin":
System.out.println("Welcome Admin");
break;
case "User":
System.out.println("Welcome User");
break;
default:
System.out.println("Unknown Role");
}
}
}

πŸ“Œ Output:

Welcome Admin

πŸš€ Example 4: Multiple Case Labels

public class Main {
public static void main(String[] args) {
char grade = 'B';

switch (grade) {
case 'A':
case 'B':
System.out.println("Excellent");
break;
case 'C':
System.out.println("Good");
break;
default:
System.out.println("Try Again");
}
}
}

πŸ“Œ Output:

Excellent

🧠 When to Use switch?

Use switch when:

βœ”οΈ Expression has many fixed values
βœ”οΈ Values are int, byte, short, char, enum, or String

CodeCapsule

Sanjit Sinha β€” Web Developer | PHP β€’ Laravel β€’ CodeIgniter β€’ MySQL β€’ Bootstrap Founder, CodeCapsule β€” Student projects & practical coding guides. Email: info@codecapsule.in β€’ Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *