Constants (and enums)

There are various ways of making and using constants. We'll look at different ways of doing them and when each method is appropriate

1. Using variables for state variables

Often you have a program where you need to know what state it is in. For example, in a paint program you might need to know what mode you are painting in.

In the initialization, you might have:

String mode = "line"; //default mode
and then in paintComponent() something like this:
switch (mode) {
case "pencil":
   ...
   break;
case "line":
   ...
   break;
case "erase":
   ...
   break;
}
and in your ActionListener something like this:
if (e.getActionCommand().equals("erase")) {
	mode="erase";
	firstClick = true;
	drawingPanel.repaint();
}

if (e.getActionCommand().equals("pencil")) {
	mode="pencil";
	...

Problems:

Where should you use this approach? Nowhere.

2. Using constants

Constants in Java are written as: static final int AAA = 13;.

— for constant numbers

Example 1:

static final int GRIDSIZE=7;
static final int SCRSIZE = 600;
static final Color BCKCOLOR = new Color(240,240,0);

later on you would use these in your code:

this.setPreferredSize(new Dimension(SCRSIZE, SCRSIZE));
panelTop.setBackground(BCKCOLOUR);
    ...
	
for (int i=0; i<GRIDSIZE; i++) {
	for (int j=0; j<GRIDSIZE; j++) {
		dotsarray[i][j] = (int)(Math.random() * 4 + 1);
	}
}

Advantages: There are some very important reasons for using constants.

 

Problems:

Where should you use this approach? Wherever needed.

The examples above are good. Also see this example, in our robot program, where constants are used for many things.
Note: to import a separate file of constants (final static) in Java, you need to write import static myPackage.RobotMap.*;

— for state variables

Constants can be used for state variables too, as in these examples.

static final int LEFT = 1;
static final int RIGHT = 2;
static final int UP = 3;
static final int DOWN = 4;
  ...
int direction = UP;
  ...
switch (direction) {
case LEFT:
   ...
   break;
case RIGHT:
   ...
   break;
case UP:
   ...
   break; 
case DOWN:
   ...
   break; 
}

Advantages:

 

Problems: There are a couple of serious problems:

Where should you use this way of doing things? for simple programs when ENUMS are too much work