Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




Java - Switch with Strings


We have already seen in Java Switch - Case, the example of you being a teacher.


Now, we will look at the same example,


Say, you are a class teacher and there are only 5 students in your class.


And you have marked them with their Roll Numbers and their Names.


Now, say the Principal of the school has asked you to write a Java program, that will show you the roll number of a student once you enter his/her name.


Code with Java Switch - Case


Example :



public class MyApplication
{
    public static void main(String[] args)
    {
        String name = "John";

        switch (name) 
        {
            case "Ronald":
                System.out.println("His roll number is 1");
                break;
            case "John":
                System.out.println("His roll number is 2");
                break;
            case "Murali":
                System.out.println("His roll number is 3");
                break;
            case "Satish":
                System.out.println("His roll number is 4");
                break;
            case "Debasish":
                System.out.println("His roll number is 5");
                break;
            default:
                System.out.println("The student does not exist.");
				break;
        }
    }
}


Output :



  His roll number is 2

This time we are trying to match a String in the Switch - Case statement.


We have taken the name in a String variable name and initialised it with "John".


String name = "John";
Spring_Boot


Then we have taken the name and put it in switch.


switch (name) {
	case "Ronald":
		System.out.println("His roll number is 1");
		break;
	case "John":
		System.out.println("His roll number is 2");
		break;
	case "Murali":
		System.out.println("His roll number is 3");
		break;
	case "Satish":
		System.out.println("His roll number is 4");
		break;
	case "Debasish":
		System.out.println("His roll number is 5");
		break;
	default:
		System.out.println("The student does not exist.");
		break;
	}

And checked which case matches "John".


And found


case "John":
	System.out.println("His roll number is 2");
	break;

So printed John's roll number


His roll number is 2
Spring_Boot