Values that should never change
Some values must stay the same for the whole program, like the number of days in a week. Put final in front, and Java won't let anyone change it:
public class Main {
public static void main(String[] args) {
final int DAYS_IN_WEEK = 7;
final double GST_RATE = 0.18;
System.out.println("A week has " + DAYS_IN_WEEK + " days");
System.out.println("Tax on 100 is " + (100 * GST_RATE));
}
}Output
A week has 7 days Tax on 100 is 18.0
Constants are written in UPPER_CASE with underscores between words, so they stand out.
Trying to change a constant
public class Main {
public static void main(String[] args) {
final int DAYS_IN_WEEK = 7;
DAYS_IN_WEEK = 8;
}
}Output (the program does not compile)
Main.java:4: error: cannot assign a value to final variable DAYS_IN_WEEK
DAYS_IN_WEEK = 8;
^Tip: Use a constant instead of typing the same number in many places. If it ever needs to change, you change it in one place only.