ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Java Program: How to Use Switch Statement in Java

Updated on November 1, 2013

Get A Website Plus a Free Domain Name in Just 1 Hour!

Bring the new technology in your hands! Share your skills, improve and impress. Get Your Own Website and a Free Domain Name Here!

How to program in Java using Switch Statement with Free Java Source Code given below:

Switch statement in java is another branching mechanism that uses cases. Basically Switch statement requires one variable to represent the choice of the user. So, we as a programmer would provide choices in the program and compare the choice of the user to our predefined choices we write inside the program. For better understanding, we will reprogram again the bird identifier written in the multi if else statement and make it a switch statement instead. Believe me, the code is much cleaner here on the switch statement than on the multi if else statement. See the programming syntax below.

Programming Syntax for Switch statement

switch(ans)
{
Case 1:
{
Your code goes here
}
Case 2:
{
Your code goes here
}
Default:
{
Your code goes here
}
}

Free Java Source Code for Switch Statement

package birds_identifier2;
	
import java.util.Scanner;

public class Main {

   
    public static void main(String[] args) 
    {
        Scanner input = new Scanner(System.in);

        System.out.println("--Select a Choice Below--");
        System.out.println("Press [1]: If your Pet is can fly but cannot talk.");
        System.out.println("Press [2]: If your Pet is cannot fly but can talk.");
        System.out.println("Press [3]: If your Pet is cannot fly but can swim.");
        System.out.println("Press [4]: If your Pet is cannot fly and cannot swim .");
        System.out.println();
        System.out.print("Enter your choice: ");
        int user_answer = input.nextInt();

        switch(user_answer)
        {
            case 1:
            {
                System.out.println("Your Pet is an EAGLE!");
                break;
            }
            case 2:
            {
                System.out.println("Your Pet is a PARROT!");
                break;
            }
            case 3:
            {
                System.out.println("Your Pet is a DUCK!");
                break;
            }
            case 4:
            {
                System.out.println("Your Pet is a CHICKEN!");
                break;
            }
            default:
                System.out.println("Program Error...:D");
        }
    }

}

Sample Output:

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.

    Click to Rate This Article