default keyword

Syntax

|-default-:-|

Description
The default keyword enables a default action to occur in a switch statement. You can use the default statement at the end of the switch to handle all values that are not explicitly handled by one of the case statements.

No more than one default label may be associated with the same switch statement or a compilation error occurs.

Example
The following is an example of a switch statement that uses a default label:

/*
 * If the test value equals any of the case values, then the 
 * corresponding block of code is executed and the break 
 * statement causes execution of the the switch statement
 * to end.
 */
switch (test){
case 1: 
    System.out.println("Good"); 
    break;
case 2: 
    System.out.println("Very Good"); 
    break;   
default: 
    /*
     * If test doesn't match either of the above cases,
     * we will execute the default code block.  The 
     * break statement at the end of this block is redundant,
     * but it helps prevent errors if another case is 
     * added after the default statement.
     */
    System.out.println("The default code block." );
    break;  // not necessary, but it is good style
}

ngrelr.gif (548 bytes)
Syntax diagrams
case keyword
switch keyword

Source: The Java Language Specification. Copyright (C) 1996 Sun Microsystems, Inc.