Constants

Constants

• Are similar to variables but, once initialized, their contents may NOT be changed?
• Are declared with the keyword final?
• By convention, have all capital letters in their identifier. This makes them easier to see within the code.

Example 1:
This program defines a number of constants and then displays some of their values.

public class App
{
public static void main(String[] args)
{

final boolean YES = true;
final char DEPOSIT_CODE = ‘D’;
final byte INCHES_PER_FOOT = 12;
final int FEET_PER_MILE = 5280;
final float PI = 3.14F;
final double SALES_TAX_RATE = .06;
final String ADDRESS = “119 South Street”;

// Display some of the values

System.out.println(INCHES_PER_FOOT);
System.out.println(ADDRESS);
}
}
Output

Example 2:
This program will not compile because an attempt is made to change the value of its constant.

public class App1
{
public static void main(String[] args)
{

final double SALES_TAX_RATE = .06;
SALES_TAX_RATE = .04;

// Display the sales tax rate

System.out.println(SALES_TAX_RATE);
}
}
Here the compiler error will occur like this