×

Java Switch string

A multi-way branch statement is the switch statement. It offers a simple method for allocating execution to various code sections according to the expression's value. Primitive data types, including bytes, shorts, chars, and ints, can all be used in the word. It now functions with the String class, Wrapper classes, and enumerated types (Enums in Java). Together with multi-exception catch blocks and automatic resource management, this was one of the most well-liked JDK 7 release features. String objects may be used in the switch statement expression in Java 7 code.

An advantage over using an equivalent series of if/else reports is to use a string-based switch. Now, user merely declare a string to be an object of the String class, as shown below:

Example:

String hello = "Hello World"; // Valid from JDK7 and onwards
Object hello = "Hello World"; // Invalid from JDK7 and onwards

While switch statements are convenient, they also have some important drawbacks that should be kept in mind. For this reason, we should go through the following characteristics:

  1. The StringString shouldn't be NULL: When working with lines, the User should ensure that the expression in switch statements is not null to avoid a NullPointerException being thrown at run-time.
  2. Expensive operation: Strings can be more costly to switch on than primitive data types in terms of execution cost. Therefore, it is recommended to only activate strings in situations when the governing data is already in string form.
  3. Better than an if-else statement: Switch statements that use String objects are often more efficient bytecode generators for Java than chained if-then-else expressions.
  4. Case Sensitive Comparison: The comparison of String objects in switch statements is case-sensitive because the equals() function of the String class is utilised by the switch statement to compare the String object in its expression with the expressions linked to each case label.

Example to demonstrate the use of string

Animalss.java

// Java Program to Demonstrate use of String to
// Control a Switch Statement
// Main class
public class Animals {
// 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("cat");
// break keyword terminates the
// code execution here itself
break;


// Case 2
case "two":
// Print statement corresponding case
System.out.println("dog");
break;


// Case 3
case "three":
// Print statement corresponding case
System.out.println("rabbit");
break;


// Case 4
// Default case
default:
// Print statement corresponding case
System.out.println("no match");
}
}
}

Output:

Java Switch string

Equals() and hashCode() methods can be used to implement strings in switches, but I was more interested in Java 7's implementation of lines in controls.

This straightforward test programme's primary method and switch block operate on the String variable. This program runs using a String argument, which is then accessed from the String array argument of the primary method.

This application can be launched in Active, Passive, or Safe modes. While it's preferable to use an Enum to express these kinds of well-known unchanging values if you decide to use a String, be sure to put it in capital letters to avoid case-sensitive problems with lower case and camel case.

StringInSwitchCase.java

public class StringInSwitchCase{


public static void main(String[] args) {
String mode = args[0];


switch (mode) {
case "PASSIVE":
System.out.println("Application is running on Passive mode");
break;
case "ACTIVE":
System.out.println("Application is running on Active mode");
break;
case "SAFE":
System.out.println("Application is running on Safe mode");
}
}
}

Output:

Java Switch string

For this code to be compiled and run, JDK 1.7 must be installed. Any JDK 7 version can be done.

The decompiled version of the class mentioned above was created using the jdk1.7.0 40 version.

Can a switch have a string in it?

A string is the only type other than an integer that can be used in a switch statement.

What is a switch purpose in Java?

Java switch case allows the User to choose one of several statements to execute. It resembles an if-else-if ladder expression as a result. It supports numerous data types. The switch statement is employed to compare a variable's values to a number of those given in the test cases.


Related Topics

Difference Between in Java and C++

FeatureC++JavaDefinitionC++ is a general programming language created by Bjarne Stroustrup as an extension of c language    Java is class-based, object-based, and designed to have as few implementation dependencies as...

4 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

Java Math exp() Method

The exp() method of Math class returns Euler’s number(e) raised to the power of a double value. Syntax: public static double exp(double a) Parameters: The parameter ‘a’ represents the exponent e. Return Value: The exp ()...

2 minutes read.

Convert List to String in Java

We occasionally need to create a string from a list of characters. Since a string is only a collection of characters, a character array can be converted into a string....

6 minutes read.

Graph Problems in Java

A graph is a special type of data structure used in programming that is made up of edges connecting each set of finitely many nodes, or vertices, to each other....

14 minutes read.

Java Generics Questions

Introduction We'll walk through a few real-world examples of interview questions and responses for Java generics in this article. Java 5 saw the debut of the fundamental idea of generics. Due to...

9 minutes read.

Java Integer remainder Unsigned() method

The remainderUnsigned() method of Java Integer class returns the unsigned remainder by dividing the first and second argument. Syntax public static int remainderUnsigned(int dividend, int divisor)  Parameters The ‘dividend’ and ‘divisor’ represents the value...

1 minute read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Types of Logical Operators in Java

In this tutorial, we are going to study logical operators. A logical operator is an operator that accomplishes a logical operation that is to connect two or more operations. These...

5 minutes read.

Rehashing in Java

The most crucial idea mostly in the data structure is hashing, which is utilized to change a particular key into some other value. The hash function can be used to...

7 minutes read.

Buffer reader to read string in Java

The Buffered Reader class of Java is used to read the stream of characters from the input stream. Program to read string using Buffer reader import java.io.*; class  Demo {   public static void main(String...

3 minutes read.

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.

Java String join() method

Java String join() method returns a joined String with given delimiter Syntax: public static String join(CharSequence delimeter,charSequence...elements) public static String join(CharSequence delimeter,Iterable<?extens charSequence>elements) Parameters: delimiter: char value to be added with each element elements: char value...

1 minute read.

Java String intern() method

Java String intern() method returns canonical representation for the String Object. syntax: public String intern() Return: It returns a interned String that to be a pool of unique String. Java String intern() Example 1 public class...

2 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Java LinkedList vs ArrayList

LinkedList In LinkedList, each element is a distinct entity containing an information portion and an address component, and the elements are not kept in consecutive locations. Pointers & addresses are used...

3 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

Coin change problem in dynamic programming

In this tutorial, we will understand a popular problem called the coin changeproblem through dynamic programming. This problem checks the logical and critical thinking ability of the person. Dynamic Programming...

5 minutes read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.