Calling a Variable Arity Method – Declarations

Calling a Variable Arity Method

Example 3.15 illustrates various aspects of calling a variable arity method. The method flexiPrint() in the VarargsDemo class has a variable arity parameter:

Click here to view code image

public static void flexiPrint(Object… data) { // Object[]
  //…
}

The variable arity method prints the name of the Class object representing the actual array that is passed at runtime. It prints the number of elements in this array as well as the text representation of each element in the array.

The method flexiPrint() is called in the main() method. First it is called with the values of primitive types and Strings ((1) to (8)), and then it is called with the program arguments (p. 141) supplied on the command line ((9) to (11)).

Compiling the program results in a warning at (9), which we ignore for the time being. The program can still be run, as shown in Example 3.15. The numbers at the end of the lines in the output relate to numbers in the code, and are not printed by the program.

Example 3.15 Calling a Variable Arity Method

Click here to view code image

public class VarargsDemo {
  public static void flexiPrint(Object… data) { // Object[]
    // Print the name of the Class object for the varargs parameter.
    System.out.print(“Type: ” + data.getClass().getName());
    System.out.println(”  No. of elements: ” + data.length);
    System.out.print(“Element values: “);
    for(Object element : data)
      System.out.print(element + ” “);
    System.out.println();
  }
  public static void main(String… args) {
    int    day       = 13;
    String monthName = “August”;
    int    year      = 2009;
    // Passing primitives and non-array types:
    flexiPrint();                      // (1) new Object[] {}
    flexiPrint(day);                   // (2) new Object[] {Integer.valueOf(day)}
    flexiPrint(day, monthName);        // (3) new Object[] {Integer.valueOf(day),
                                       //                   monthName}
    flexiPrint(day, monthName, year);  // (4) new Object[] {Integer.valueOf(day),
                                       //                   monthName,
                                       //                   Integer.valueOf(year)}
    System.out.println();
    // Passing an array type:
    Object[] dateInfo = {day,          // (5) new Object[] {Integer.valueOf(day),
                         monthName,    //                   monthName,
                         year};        //                   Integer.valueOf(year)}
    flexiPrint(dateInfo);              // (6) Non-varargs call
    flexiPrint((Object) dateInfo);     // (7) new Object[] {(Object) dateInfo}
    flexiPrint(new Object[]{dateInfo});// (8) Non-varargs call
    System.out.println();
    // Explicit varargs or non-varargs call:
    flexiPrint(args);                  // (9) Warning!
    flexiPrint((Object) args);         // (10) Explicit varargs call
    flexiPrint((Object[]) args);       // (11) Explicit non-varargs call
  }
}

Compiling the program:

Click here to view code image

>
javac VarargsDemo.java
VarargsDemo.java:41: warning: non-varargs call of varargs method with inexact
argument type for last parameter;
    flexiPrint(args);                  // (9) Warning!
               ^
  cast to Object for a varargs call
  cast to Object[] for a non-varargs call and to suppress this warning
1 warning

Running the program:

Click here to view code image

>
java VarargsDemo To arg or not to arg

Type: [Ljava.lang.Object;  No. of elements: 0                (1)
Element values:
Type: [Ljava.lang.Object;  No. of elements: 1                (2)
Element values: 13
Type: [Ljava.lang.Object;  No. of elements: 2                (3)
Element values: 13 August
Type: [Ljava.lang.Object;  No. of elements: 3                (4)
Element values: 13 August 2009
Type: [Ljava.lang.Object;  No. of elements: 3                (6)
Element values: 13 August 2009
Type: [Ljava.lang.Object;  No. of elements: 1                (7)
Element values: [Ljava.lang.Object;@1eed786
Type: [Ljava.lang.Object;  No. of elements: 1                (8)
Element values: [Ljava.lang.Object;@1eed786
Type: [Ljava.lang.String;  No. of elements: 6                (9)
Element values: To arg or not to arg
Type: [Ljava.lang.Object;  No. of elements: 1                (10)
Element values: [Ljava.lang.String;@187aeca
Type: [Ljava.lang.String;  No. of elements: 6                (11)
Element values: To arg or not to arg

The if-else Statement 2 – Control Flow

Example 4.1 Fall-Through in a switch Statement with the Colon Notation

Click here to view code image

public class Advice {
  private static final int LITTLE_ADVICE = 0;
  private static final int MORE_ADVICE = 1;
  private static final int LOTS_OF_ADVICE = 2;
  public static void main(String[] args) {
    dispenseAdvice(LOTS_OF_ADVICE);
  }
  public static void dispenseAdvice(int howMuchAdvice) {
    switch (howMuchAdvice) {                                     // (1)
      case LOTS_OF_ADVICE: System.out.println(“See no evil.”);   // (2)
      case MORE_ADVICE:    System.out.println(“Speak no evil.”); // (3)
      case LITTLE_ADVICE:  System.out.println(“Hear no evil.”);  // (4)
                           break;                                // (5)
      default:             System.out.println(“No advice.”);     // (6)
    }
  }
}

Output from the program:

See no evil.
Speak no evil.
Hear no evil.

Several case labels can prefix the same group of statements. This is the equivalent of specifying the same case constants in a single case label. The latter syntax is preferable as it is more concise than the former. Such case constants will result in the associated group of statements being executed. This behavior is illustrated in Example 4.2 for the switch statement at (1).

At (2) in Example 4.2, three case labels are defined that are associated with the same action. At (3), (4), and (5), a list of case constants is defined for some of the case labels. Note also the use of the break statement to stop fall-through in the switch block after the statements associated with a case label are executed.

The first statement in the switch block must always have a case or default label; otherwise, it will be unreachable. This statement will never be executed because control can never be transferred to it. The compiler will flag this case (no pun intended) as an error. An empty switch block is perfectly legal, but not of much use.

Since each group of statements associated with a case label can be any arbitrary statement, it can also be another switch statement. In other words, switch statements can be nested. Since a switch statement defines its own local block, the case labels in an inner block do not conflict with any case labels in an outer block. Labels can be redefined in nested blocks; in contrast, variables cannot be redeclared in nested blocks (ยง6.6, p. 354). In Example 4.2, an inner switch statement is defined at (6), which allows further refinement of the action to take on the value of the selector expression in cases where multiple case labels are used in the outer switch statement. A break statement terminates the innermost switch statement in which it is executed.

The print statement at (7) is always executed for the case constants 9, 10, and 11.

Note that the break statement is the last statement in the group of statements associated with each case label. It is easy to think that the break statement is a part of the switch statement syntax, but technically it is not.

Example 4.2 Nested switch Statements with the Colon Notation

Click here to view code image

public class Seasons {
  public static void main(String[] args) {
    int monthNumber = 11;
    switch(monthNumber) {                                     // (1) Outer
      case 12: case 1: case 2:                                // (2)
        System.out.println(“Snow in the winter.”);
        break;
      case 3, 4: case 5:                                      // (3)
        System.out.println(“Green grass in the spring.”);
        break;
      case 6, 7, 8:                                           // (4)
        System.out.println(“Sunshine in the summer.”);
        break;
      case 9, 10, 11:                                         // (5)
        switch(monthNumber) { // Nested switch                   (6) Inner
          case 10:
            System.out.println(“Halloween.”);
            break;
          case 11:
            System.out.println(“Thanksgiving.”);
            break;
        } // End nested switch
        // Always printed for case constant 9, 10, 11
        System.out.println(“Yellow leaves in the fall.”);     // (7)
        break;
      default:
        System.out.println(monthNumber + ” is not a valid month.”);
    }
  }
}

Output from the program:

Click here to view code image

Thanksgiving.
Yellow leaves in the fall.