Constants
Constants are like variables that don't change. They are declared in the same places as the global variables, only the keywords static and final are added to their declaration.
You use them to replace "magic numbers". A magic number is a number that appears in code without any explanation. For example, if someone was trying to calculate the provincial sales tax of something, they might type price*0.08 + price *0.07. It is hard to understand what 0.08 and 0.07 are, if they were named PST and GST, it would be easier to follow the code. Further suppose that the provincial and federal governments lowered the sales tax. The programmer would have to go all through their code changing each instance of the GST and PST. If they had used a constant, they would only need to change it in one spot.
An example program:
import java.io.*;
public class test
{
public static final int sizex = 20;
public static final int sizey = 3;
public static final double PST = 0.08;
public static final double GST = 0.07;
public static final String filename = "input.txt";
public static void main (String args [])
{System.out.println ("" + sizex);//Prints: 20
double price = 9;
double tax = price*PST + price*GST;
double total = price + tax;
System.out.println(""+total);//Prints: 10.35}
}
Great places to use constants: