Print Page Print Page

Ch5 – Flag Variables and Return Statement

  1. Create a new project in Eclipse names Flags and create a class named Flag. Be certain you create a main method.
  2. Add the following code to main.
boolean evenFlag = (Integer.parseInt(args[0]) %2 == 0);
if(evenFlag) {
  System.out.println("arg[0] was even");
}
else {
  System.out.println("arg[0] was odd");
}

The completed class appears as follows.

public class Flag {
  public static void main(String[] args) {
    boolean evenFlag = (Integer.parseInt(args[0]) %2 == 0);
    if(evenFlag) {
      System.out.println("arg[0] was even");
    }
    else {
      System.out.println("arg[0] was odd");
    }
  }
}
  1. Click the run button and note the error that occurs.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
	at Flag.main(Flag.java:5)
  1. The error is due to no parameter having been passed to the program. To pass a parameter in Eclipse you must do the following. First, from the Run menu, select Run Configurations.chapter_5_run_config_menu
  2. Click the Arguments tab and enter three into the program arguments text area.chapter_5_run_config_dialog
  3. Click the Run button and you should see the following results in the Console tab.chapter_5_run_config_console
  4. You can modify the value passed to the program by returning to the saved run configuration. Note that here the configuration was named Flag.chapter_5_run_config_flag
  5. Change the Program arguments to six, click Run, and note the printed results change.
arg[0] was even