MOCKSTACKS
EN
Questions And Answers

More Tutorials









Java Switch Case Statements


Switch Case-Control Instruction


  • Switch-Case is used when we have to make a choice between the number of alternatives for a given variable.

  • Var can be an integer, character, or string in Java.

  • Every switch case must contain a default case. The default case is executed when all the other cases are false.

  • Never forget to include the break statement after every switch case otherwise the switch case will not terminate.

  • Syntax:

     Switch(var) {
    	Case C1:
    		//Code;	
    		break;
    	Case C2:
    		//Code;
    		break;	
    	Case C3:
    		//Code
    		break;
    	default:
    		//Code
    
     

  • A switch can occur within another but in practice, this is rarely done.

  • Flow control of switch case in Java :



    Example


    package com.company;
    import java.util.Scanner;
    
    public class cwh_18_elseif {
        public static void main(String[] args) {
            String var = "Saurabh";
    
    
            switch (var) {
                case "Shubham" -> {
                    System.out.println("You are going to become an Adult!");
                    System.out.println("You are going to become an Adult!");
                    System.out.println("You are going to become an Adult!");
                }
                case "Saurabh" -> System.out.println("You are going to join a Job!");
                case "Vishaka" -> System.out.println("You are going to get retired!");
                default -> System.out.println("Enjoy Your life!");
            }
            System.out.println("Thanks for using my Java Code!");
    
        }
    }
    

    Output

    You are going to join a Job!
    Thanks for using my Java Code!


    Conclusion

    In this page (written and validated by ) you learned about Java Switch Case Statements . What's Next? If you are interested in completing Java tutorial, your next topic will be learning about: Java While Loops.



    Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


    Share On:


    Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.