• Register
0 votes
17 views
Explain with an Example?
680 points

Please log in or register to answer this question.

1 Answer

0 votes

Solution :

Firstly, we have seen in most of the cases of using the switch case specially in constant or any literal types but not  string type.Now we are going to discuss about the switch case use and inserting a string to check each case in the example program. 

Switch case :

It’s a multi-way branching statement.which means we have a constant or literal of any type like integer and character or even enumerations can be checked against all the cases with the statement provided next to the switch case.If there is a match then that assoicated block of code will be executed.We have alot of advantages with using a string in switch case, Firstly instead of using multiple elif statements or the if/else statements we can switch with string if neccesary. It’s a case senstive and make sure the string should not be a null. 
 
Now, in the following example we are going to use the switch case with a string. 

Code :

import java.util.Scanner; 
public class S{  
    public static void main(String[] args) {  
Scanner sc=new Scanner(System.in);
System.out.println("enter a fruit name");
String fruit=sc.nextLine();
        switch(fruit){  
        case "apple":  
            System.out.println("Take the apples");  
            break;  
        case "pineapple":  
            System.out.println("Take the pineapples");  
            break;  
        case "guave":  
            System.out.println("Take the guave fruit");  
        }  
    }  
}

Output :

enter a fruit name : pineapple
Take the pineapples
 
Hope, your clear with my answer
 
 
 
 
 
1.3k points