Suppose you wanted to write a program which prints the current month of the year. You could define a constant for each month, then assign one of the constants to a variable. You could also define an array of string references containing the name of each month.
Listing 1 - MonthsDriver.java (version 1)
public class MonthsDriver
{
public final static byte JANUARY = 0;
public final static byte FEBRUARY = 1;
public final static byte MARCH = 2;
public final static byte APRIL = 3;
public final static byte MAY = 4;
public final static byte JUNE = 5;
public final static byte JULY = 6;
public final static byte AUGUST = 7;
public final static byte SEPTEMBER = 8;
public final static byte OCTOBER = 9;
public final static byte NOVEMBER = 10;
public final static byte DECEMBER = 11;
public final static byte NUMBER_OF_MONTHS = 12;
public final static String[] months =
{
"JANUARY","FEBRUARY","MARCH","APRIL","MAY","JUNE",
"JULY","AUGUST","SEPTEMBER","OCTOBER","NOVEMBER","DECEMBER"
};
public static void main(String[] args)
{
byte month = MAY;
System.out.println(months[month]); // Prints MAY
}
}
The program in Listing 1 works, but what if you had initialized the variable month as follows?
byte month = 20;
Copyright ©2017 by Ralph Lecessi Incorporated. All rights reserved.