• Skip to main content
  • Skip to primary sidebar
  • Skip to secondary sidebar
  • Skip to footer

Computer Notes

Library
    • Computer Fundamental
    • Computer Memory
    • DBMS Tutorial
    • Operating System
    • Computer Networking
    • C Programming
    • C++ Programming
    • Java Programming
    • C# Programming
    • SQL Tutorial
    • Management Tutorial
    • Computer Graphics
    • Compiler Design
    • Style Sheet
    • JavaScript Tutorial
    • Html Tutorial
    • Wordpress Tutorial
    • Python Tutorial
    • PHP Tutorial
    • JSP Tutorial
    • AngularJS Tutorial
    • Data Structures
    • E Commerce Tutorial
    • Visual Basic
    • Structs2 Tutorial
    • Digital Electronics
    • Internet Terms
    • Servlet Tutorial
    • Software Engineering
    • Interviews Questions
    • Basic Terms
    • Troubleshooting
Menu

Header Right

Home » Java » Structures » Switch Statement in Java Example
Next →
← Prev

Switch Statement in Java Example

By Dinesh Thakur

When there is requirement of several branching i.e. if we need several if statements, it is better to use switch statement. In other words, switch is a variation of if statement which performs multiway branching.

Syntax:

 

switch (expression)

{

case value:

                      statement(s) ;

                      break;

case value:

                     statement(s);

                     break;

default:

                     statement(s);

                      break;

}

The keyword switch begins the switch construct. The parentheses contain expression which may be a byte, a char, a short, or an int. Next is a required {, followed by any number of constructs that begin with the keyword case and end with break, with any number of statements in between. Then, there is an optional keyword called default which ends with break. Finally, a required} completes the case statement.

The case statement works by evaluating the expression and then scanning down the case statements until a match is found. When the match is found, the corresponding group of statements between the case and break will be executed. break statement is for exiting from switch construct. If no matches are found and a default is present, the group of statements associated with default will be executed. If no default is present and no match is found control jumps to the statements following switch command.

Note: When the statement of any case is executed and we forget to place break, then control will go into following case construct and executes its statements also. It keeps on executing all the statements of each case construct one after the other until a break is encountered or switch gets over.

 

Example:

 

switch(k)

{

case ‘a’ :        System.out.println(“Apple “);

                     break;

case ‘b’ :       System.out.println(“Bat”) ;

                     break;

default :       System.out.println(“Please enter a character”);

}

 

In above example, the control will jump to respective statement depending on the value of the variable k. If the value of k is ‘a’, then Apple will be printed on the screen. break after System.out.println takes the control out of the switch statement. If break is not included, control will also execute the case statement following it i.e. it will also print Bat, even though the value of k is ‘a’. This means that when case is true, then its statements are executed followed by other case statements until control encounters break statement.

If the value of k is neither ‘a’ nor ‘b’, then control will execute default statement displaying “Please enter a character” on the screen.

Look at the following example: Here, we have removed all break statements

 

switch(k)

{

case ‘a’ : System.out.println(“Apple”);

case ‘b’ : System.out.println(“Bat”);

case ‘c’ : System.out.println(“Cat”);

default: System.out.println(“Please enter a character”);

}

 

In above example, if the value of k is ‘a’, it will print:

Apple

Bat

Cat

Please enter a character

This is because after p~inting Apple, control will continue executing another case

statement in absence of break statement

If value of k is ‘b’, it will print

Bat

Cat

Please enter a character

If value of k is ‘c’, it will print

Cat

Please enter a character

Features of the switch statement:

1. The switch differs from the if statements in the sense that switch can only test for equality, whereas if can evaluate any type of logical expression. That is, the switch looks only for a match between the value of the expression and one of its case constants.

2. No two case constants in the same switch can have identical values.

3. A switch statement is more efficient than a set of nested if statements.

When it compiles a switch statement, the Java compiler will inspect each of the case constants and create a “jump table” that it will use for selecting the path of execution depending on the value of the expression. It is for this reason that switches statement runs much faster than the sequence of if else.

To demonstrate the circumstances where switch performs better then the series of if statements, lets look at the following two programs. First program is written with the help of if statement and the same program is then written with switch statement

 

/* Enter a value between 1 and 4 and print it in words */

import java.io.*;

class SwitchExample

{

            public static void main(String args[] )

                throws IOException

            {

                        BufferedReader k=new BufferedReader(new InputStreamReader

                                    (System.in));

                        String h;

                        int n;

                        System.out.println(“Enter a value between 1 and 4 “);

                        h=k.readLine( );

                        n=Integer.parseInt(h);

                        if(n==1)

                        {

                                    System.out.println(“One”);

                        }

                        if(n==2)

                        {

                                    System.out.println(“Two”);

                        }

                        if(n==3)

                        {

                                    System.out.println(“Three”);

                        }

                        if(n==4)

                        {

                                    System.out.println(“Four”);

                        }

            }

}

Now, the same above program is also done with switch statement for comparison

 

/* Enter a value between 1 & 4 and print it in words using switch command.  */

import java.io.*;

class SwitchExample

{

            public static void main(String args[] ) 

            throws IOException

            {

                        BufferedReader k=new BufferedReader(new InputStreamReader

                                    (System.in));

                        String h;

                        int n;

                        System.out.println(“Enter a value between 1 and 4 “);

                        h=k.readLine( );

                        n=Integer.parseInt(h);

                        switch(n)

                        {

                                    case 1:

                                                System.out.println(“One”);

                                                break;

                                    case 2:

                                                System.out.println(“Two”);

                                                break;

                                    case 3:

                                                System.out.println(“Three”);

                                                break;

                                    case 4:

                                                System.out.println(“Four”);

                                                break;

                                    default :

                                                System.out.println(“The value is above Four”);

                        }

            }

}

From above two programs, we can easily see that using switch statement is more handy and readable as compared to using series of if statements

You’ll also like:

  1. JavaScript Switch Statement
  2. What are the limitations with switch statement
  3. Switch ….Case Statement
  4. is a default case necessary in a switch statement
  5. When is a switch statement better than multiple if statements
Next →
← Prev
Like/Subscribe us for latest updates     

About Dinesh Thakur
Dinesh ThakurDinesh Thakur holds an B.C.A, MCDBA, MCSD certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps.

Dinesh Thakur is a Freelance Writer who helps different clients from all over the globe. Dinesh has written over 500+ blogs, 30+ eBooks, and 10000+ Posts for all types of clients.


For any type of query or something that you think is missing, please feel free to Contact us.


Primary Sidebar

Java Tutorials

Java Tutorials

  • Java - Home
  • Java - IDE
  • Java - Features
  • Java - History
  • Java - this Keyword
  • Java - Tokens
  • Java - Jump Statements
  • Java - Control Statements
  • Java - Literals
  • Java - Data Types
  • Java - Type Casting
  • Java - Constant
  • Java - Differences
  • Java - Keyword
  • Java - Static Keyword
  • Java - Variable Scope
  • Java - Identifiers
  • Java - Nested For Loop
  • Java - Vector
  • Java - Type Conversion Vs Casting
  • Java - Access Protection
  • Java - Implicit Type Conversion
  • Java - Type Casting
  • Java - Call by Value Vs Reference
  • Java - Collections
  • Java - Garbage Collection
  • Java - Scanner Class
  • Java - this Keyword
  • Java - Final Keyword
  • Java - Access Modifiers
  • Java - Design Patterns in Java

OOPS Concepts

  • Java - OOPS Concepts
  • Java - Characteristics of OOP
  • Java - OOPS Benefits
  • Java - Procedural Vs OOP's
  • Java - Polymorphism
  • Java - Encapsulation
  • Java - Multithreading
  • Java - Serialization

Java Operator & Types

  • Java - Operator
  • Java - Logical Operators
  • Java - Conditional Operator
  • Java - Assignment Operator
  • Java - Shift Operators
  • Java - Bitwise Complement Operator

Java Constructor & Types

  • Java - Constructor
  • Java - Copy Constructor
  • Java - String Constructors
  • Java - Parameterized Constructor

Java Array

  • Java - Array
  • Java - Accessing Array Elements
  • Java - ArrayList
  • Java - Passing Arrays to Methods
  • Java - Wrapper Class
  • Java - Singleton Class
  • Java - Access Specifiers
  • Java - Substring

Java Inheritance & Interfaces

  • Java - Inheritance
  • Java - Multilevel Inheritance
  • Java - Single Inheritance
  • Java - Abstract Class
  • Java - Abstraction
  • Java - Interfaces
  • Java - Extending Interfaces
  • Java - Method Overriding
  • Java - Method Overloading
  • Java - Super Keyword
  • Java - Multiple Inheritance

Exception Handling Tutorials

  • Java - Exception Handling
  • Java - Exception-Handling Advantages
  • Java - Final, Finally and Finalize

Data Structures

  • Java - Data Structures
  • Java - Bubble Sort

Advance Java

  • Java - Applet Life Cycle
  • Java - Applet Explaination
  • Java - Thread Model
  • Java - RMI Architecture
  • Java - Applet
  • Java - Swing Features
  • Java - Choice and list Control
  • Java - JFrame with Multiple JPanels
  • Java - Java Adapter Classes
  • Java - AWT Vs Swing
  • Java - Checkbox
  • Java - Byte Stream Classes
  • Java - Character Stream Classes
  • Java - Change Color of Applet
  • Java - Passing Parameters
  • Java - Html Applet Tag
  • Java - JComboBox
  • Java - CardLayout
  • Java - Keyboard Events
  • Java - Applet Run From CLI
  • Java - Applet Update Method
  • Java - Applet Display Methods
  • Java - Event Handling
  • Java - Scrollbar
  • Java - JFrame ContentPane Layout
  • Java - Class Rectangle
  • Java - Event Handling Model

Java programs

  • Java - Armstrong Number
  • Java - Program Structure
  • Java - Java Programs Types
  • Java - Font Class
  • Java - repaint()
  • Java - Thread Priority
  • Java - 1D Array
  • Java - 3x3 Matrix
  • Java - drawline()
  • Java - Prime Number Program
  • Java - Copy Data
  • Java - Calculate Area of Rectangle
  • Java - Strong Number Program
  • Java - Swap Elements of an Array
  • Java - Parameterized Constructor
  • Java - ActionListener
  • Java - Print Number
  • Java - Find Average Program
  • Java - Simple and Compound Interest
  • Java - Area of Rectangle
  • Java - Default Constructor Program
  • Java - Single Inheritance Program
  • Java - Array of Objects
  • Java - Passing 2D Array
  • Java - Compute the Bill
  • Java - BufferedReader Example
  • Java - Sum of First N Number
  • Java - Check Number
  • Java - Sum of Two 3x3 Matrices
  • Java - Calculate Circumference
  • Java - Perfect Number Program
  • Java - Factorial Program
  • Java - Reverse a String

Other Links

  • Java - PDF Version

Footer

Basic Course

  • Computer Fundamental
  • Computer Networking
  • Operating System
  • Database System
  • Computer Graphics
  • Management System
  • Software Engineering
  • Digital Electronics
  • Electronic Commerce
  • Compiler Design
  • Troubleshooting

Programming

  • Java Programming
  • Structured Query (SQL)
  • C Programming
  • C++ Programming
  • Visual Basic
  • Data Structures
  • Struts 2
  • Java Servlet
  • C# Programming
  • Basic Terms
  • Interviews

World Wide Web

  • Internet
  • Java Script
  • HTML Language
  • Cascading Style Sheet
  • Java Server Pages
  • Wordpress
  • PHP
  • Python Tutorial
  • AngularJS
  • Troubleshooting

 About Us |  Contact Us |  FAQ

Dinesh Thakur is a Technology Columinist and founder of Computer Notes.

Copyright © 2025. All Rights Reserved.

APPLY FOR ONLINE JOB IN BIGGEST CRYPTO COMPANIES
APPLY NOW