Return to lecture notes index
15-100 Lecture 16 (Monday February 23, 2005)
Static and final

Here's the code we wrote in class for the Menu class:


import java.io.*;
class Menu {
  private String menuString;
  private int numberOfOptions;
  private BufferedReader br;
	
  //the static final makes these variables immutable.  You won't 
  //be able to change which string these variables refer to.
  private static final String MENU_HEADER = "------Menu--------";
  private static final String PROMPT_STRING = "Your choice> ";	
	
  public Menu(String menuString, int numberOfOptions){
    br = new BufferedReader(new InputStreamReader(System.in));
    this.menuString = menuString;
    this.numberOfOptions = numberOfOptions;
  }
	
  public void display() {
    System.out.println(MENU_HEADER);
    System.out.println(menuString);
  }
	
  public int getChoice()throws NumberFormatException, IOException{
    System.out.println(PROMPT_STRING);
		
    String choice = br.readLine();
		
    return Integer.parseInt(choice);
  }
}

So in the instance variable declaration you noticed two words that we haven't used in that context before static and final. Final is a reserved word that tells Java once the variable has been set to hold a reference or primitive the variable's stored value my not be changed. What does this mean? It would be illegal to write MENU_HEADER = "Header"; The compiler would complain because this final variable has already been initialized. Notice, stylistically, that because this variable is final we write its name in all capitals and use an underscore (_) to signify a space between words (as opposed to the camel case that we write most variable names in).

So what does static mean? You have seen it used before in main()'s signature (public static void main(String[] args)). Static means that for every instance of the class (in this case Menu) that is made they will all have the same state (aka for all instances of Menu, MENU_HEADER will always be the same). If you were to change MENU_HEADER in one instance of Menu (which for this variable can't happen because its final...but this is hypothetical) all of the MENU_HEADERs will be set to this (ie == will return true when applied to MENU_HEADER of two different Menu's).

While loops

Here is a class (NameGame) that uses the menu class. The purpose of this class will be to allow a user to select a choice (enter a name, print out different parts of the name, or quit). The user should be presented with these choices until the user decides to quit.

Now how do we do this? We have no way of knowing how many games the user will want to play, so how do we know how many times to run the "game" code? Fortunately, java has a structure called loops that will solve this problem. The simplest loop is the while(statement that evaluates to a boolean) loop. This loop will execute reach it's end then go back to the top of the loop and continue to execute as long as the continuation condition is true (shown here in italics) or until the loop is broken from (the reserved word "break" will allow a program to exit from the inner most loop that is being executed).


import java.io.*;
class NameGame{
  private String firstName;
  private String middleName;
  private String lastName;
	
  public NameGame(String firstName, String middleName, String lastName){
    this.firstName =firstName;
    this.middleName = middleName;
    this.lastName = lastName;
  }
	
  public void printFirstName(){
    System.out.println(firstName);
  }
	
  public void printMiddleName(){
    System.out.println(middleName);
  }
	
  public void printLastName(){
    System.out.println(lastName);
  }
	
  public static void main(String[] args) throws Exception{
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		
    String menuString = "1) Create NameGame \n" +
			"2) Print first name \n" +
			"3) Print middle name \n" +
			"4) Print last name \n" +
			"5) Quit \n" ;
		
    int numberOfChoices = 5;
		
    Menu nameMenu = new Menu(menuString, numberOfChoices);
		
    //this continuation condition will always be true (it is an infinite loop)
    while (true) {
      nameMenu.display();
      int choice = nameMenu.getChoice();
      NameGame game = null;
			
      if (choice == 1){
        System.out.println("First> ");
        String firstName = br.readLine();
				
        System.out.println("Middle> ");
        String middleName = br.readLine();
				
        System.out.println("Last> ");
        String lastName = br.readLine();
				
        game = new NameGame(firstName, middleName, lastName);
      }
			
      if (choice == 2){
        game.printFirstName();
      }
			
      if (choice == 3){
	game.printMiddleName();
      }
		
      if (choice == 4){
	game.printLastName();
      }
		
      if (choice == 5){
	return;
      }//end of ifs
    }// end while
  }//end main(...)
}//end class NameGame
Notice that while the code compiles it isn't the best solution to the problem. We will modify this code next class so that it catches IOException and NumberFormatException instead of throwing them.