Java switch case String


Today we will investigate Java Switch Case String Example. Being a java software engineer, I know the significance of String and how frequently it's utilized for restrictive stream. Regardless of whether you have a straightforward strategy that carries on diversely for various info String or a Servlet controller class to check the approaching activity and procedure it likewise, we use String and contrast it with decide the flow.

Java Switch Case

java switch case, java switch string

Java switch case is a flawless method to code for contingent stream, much the same as if-else conditions. Prior to Java 7, the main way to accomplish string based restrictive stream was utilizing if-else conditions. However, Java 7 has improved the change case to help String also.

Java switch case String Example

Here I am giving a java program that demonstrates the utilization of String in java switch case articulations. For correlation, I am likewise giving another strategy which does likewise contingent stream utilizing if-else conditions.

SwitchStringExample.java


package com.journaldev.util;

public class SwitchStringExample {

	public static void main(String[] args) {
		printColorUsingSwitch("red");
		printColorUsingIf("red");
		// switch case string is case sensitive
		printColorUsingSwitch("RED");
		printColorUsingSwitch(null);
	}

	private static void printColorUsingIf(String color) {
		if (color.equals("blue")) {
			System.out.println("BLUE");
		} else if (color.equals("red")) {
			System.out.println("RED");
		} else {
			System.out.println("INVALID COLOR CODE");
		}
	}

	private static void printColorUsingSwitch(String color) {
		switch (color) {
		case "blue":
			System.out.println("BLUE");
			break;
		case "red":
			System.out.println("RED");
			break;
		default:
			System.out.println("INVALID COLOR CODE");
		}
	}

}

Here is the output of the above program.


RED
RED
INVALID COLOR CODE
Exception in thread "main"java.lang.NullPointerException
	at com.journaldev.util.SwitchStringExample.printColorUsingSwitch(SwitchStringExample.java:24)
	at com.journaldev.util.SwitchStringExample.main(SwitchStringExample.java:10)

Keys focuses to know for java switch case String are:

  1. Java switch case String make code increasingly lucid by expelling the numerous if-else-whenever tied conditions.
  2. Java switch case String is case touchy, the yield of model affirms it.
  3. Java Switch case utilizes String.equals() technique to contrast the passed esteem and case esteems, so make a point to add a NULL check to stay away from NullPointerException.
  4. According to Java 7 documentation for Strings in Switch, java compiler creates progressively productive byte code for String in Switch proclamation than affixed if-else-if statements.
  5. Make beyond any doubt to utilize java switch case String just when you realize that it will be utilized with Java 7 else it will toss Exception.





© Journaldev Python 3 tutorial spring tutorial