Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on String
  • Practice String
  • MCQs on String
  • Tutorial on String
  • String Operations
  • Sort String
  • Substring & Subsequence
  • Iterate String
  • Reverse String
  • Rotate String
  • String Concatenation
  • Compare Strings
  • KMP Algorithm
  • Boyer-Moore Algorithm
  • Rabin-Karp Algorithm
  • Z Algorithm
  • String Guide for CP
Open In App
Next Article:
String in Switch Case in Java
Next article icon

String in Switch Case in Java

Last Updated : 11 Jul, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

The switch statement is a multi-way branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression. Basically, the expression can be a byte, short, char, and int primitive data types. Beginning with JDK7, it also works with enumerated types ( Enums in java), the String class, and Wrapper classes.

Hence the concept of string in switch statement arises into play in JDK 7 as we can use a string literal or constant to control a switch statement, which is not possible in C/C++. Using a string-based switch is an improvement over using the equivalent sequence of if/else statements. We now declare a string as a String class object only as depicted below:

Illustration:

String geeks = "GeeksforGeeks" ; // Valid from JDK7 and onwards  Object geeks = "GeeksforGeeks" ; // Invalid from JDK7 and onwards 

There are certain key points that are needed to be remembered while using switch statement as it does provide convenience but at the same time acts as a double sword, hence we better go through traits as listed: 

1. Expensive operation: Switching on strings can be more expensive in terms of execution than switching on primitive data types. Therefore, it is best to switch on strings only in cases in which the controlling data is already in string form.

2. String should not be NULL: Ensure that the expression in any switch statement is not null while working with strings to prevent a NullPointerException from being thrown at run-time.

3. Case Sensitive Comparison: The switch statement compares the String object in its expression with the expressions associated with each case label as if it were using the equals() method of String class consequently, the comparison of String objects in switch statements is case sensitive.

4. Better than if-else: The Java compiler generates generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

Example 1:

Java
// Java Program to Demonstrate use of String to // Control a Switch Statement  // Main class public class GFG {      // Main driver method     public static void main(String[] args)     {          // Custom input string         String str = "two";          // Switch statement over above string         switch (str) {          // Case 1         case "one":              // Print statement corresponding case             System.out.println("one");              // break keyword terminates the             // code execution here itself             break;          // Case 2         case "two":              // Print statement corresponding case             System.out.println("two");             break;          // Case 3         case "three":              // Print statement corresponding case             System.out.println("three");             break;          // Case 4         // Default case         default:              // Print statement corresponding case             System.out.println("no match");         }     } } 

Output
two 

Example 2:

Java
// Java Program to Demonstrate use of String to // Control a Switch Statement  // Main class public class GFG {      // Main driver method     public static void main(String[] args)     {          // Custom input string         // Null string is passed         String str = "";          // Switch statement over above string         switch (str) {          // Case 1         case "one":              // Print statement corresponding case             System.out.println("one");              // break keyword terminates the             // code execution here itself             break;          // Case 2         case "two":              // Print statement corresponding case             System.out.println("two");             break;          // Case 3         case "three":              // Print statement corresponding case             System.out.println("three");             break;          // Case 4         // Default case         default:              // Print statement corresponding case             System.out.println("no match");         }     } } 

Output
no match 


Next Article
String in Switch Case in Java

K

kartik
Improve
Article Tags :
  • Strings
  • Java
  • Computer Science Fundamentals
  • DSA
Practice Tags :
  • Java
  • Strings

Similar Reads

    Compare two Strings in Java
    String in Java are immutable sequences of characters. Comparing strings is the most common task in different scenarios such as input validation or searching algorithms. In this article, we will learn multiple ways to compare two strings in Java with simple examples.Example:To compare two strings in
    4 min read
    Switch Statements in Java
    The switch statement in Java is a multi-way branch statement. In simple words, the Java switch statement executes one statement from multiple conditions.It is an alternative to an if-else-if ladder statement. It provides an easy way to dispatch execution to different parts of the code based on the v
    9 min read
    Swapping Pairs of Characters in a String in Java
    Given string str, the task is to write a Java program to swap the pairs of characters of a string. If the string contains an odd number of characters then the last character remains as it is. Examples: Input: str = “Java”Output: aJav Explanation: The given string contains even number of characters.
    3 min read
    Swapping Characters of a String in Java
    As we know that Object of String in Java are immutable (i.e. we cannot perform any changes once its created). To do modifications on string stored in a String object, we copy it to a character array, StringBuffer, etc and do modifications on the copy object.In this article we would go through some m
    3 min read
    Nested switch case
    Switch-case statements:These are a substitute for long if statements that compare a variable to several integral values The switch statement is a multiway branch statement. It provides an easy way to dispatch execution to different parts of code based on the value of the expression.Switch is a contr
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences