Computer Applications

Explain with the help of an example, the purpose of default in a switch statement.

Java Conditional Stmts

ICSE 2005

66 Likes

Answer

When none of the case values are equal to the expression of switch statement then default case is executed. In the example below, value of number is 4 so case 0, case 1 and case 2 are not equal to number. Hence sopln of default case will get executed printing "Value of number is greater than two" to the console.

int number = 4;
    
switch(number) {
    
    case 0:
        System.out.println("Value of number is zero");
        break;
        
    case 1:
        System.out.println("Value of number is one");
        break;
        
    case 2:
        System.out.println("Value of number is two");
        break;
        
    default:
        System.out.println("Value of number is greater than two");
        break;
        
}

Answered By

32 Likes


Related Questions