Once you click post assignment, learners in the selected class will immediately be able to see and complete this assignment
Back to Classroom
Constants
Introduction To Java Course
Engineers From These Top Companies and Universities Trust EXLskills
1M+ Professionals | 100+ Institutions
This is the EXLskills free and open-source Introduction To Java Course. It guides learners via explanation, demonstration, and thorough practice, from no more than a basic understanding of Java, to a moderate level of essential coding proficiency.
Is this course FREE?
Yes, this a 100% free course that you can contribute to on GitHub here!
Constants are variables that do not change. Constants include the Java reserved word final, stating that the value will not change in the program. Let's remember that constant variables follow a different naming convention than other variables, using capitals and separating words with an underscore. See the following example of two constants.
ConstantsExample.java
package exlcode;
public class ConstantsExample {
// variable names for constants are capitalized and separated by underscores
public static final int EXAMPLE_VARIABLE_ONE = 1;
public static final double EXAMPLE_VARIABLE_TWO = 3.5;
public static void main(String[] args) {
// EXAMPLE_VARIABLE_1 + 1 will cause an error because
// EXAMPLE_VARIABLE_1 is declared final
System.out.println(EXAMPLE_VARIABLE_ONE);
System.out.println(EXAMPLE_VARIABLE_TWO);
}
}
Since constants cannot be changed, a syntax error or a compile-time error will be thrown if a change is attempted to a variable with the reserved word final.
One advantage of using constants instead of numbers is that the source code would be easier to read and check for debugging. In addition, if a constant needs to change, the change only has to be made in one place, where it is initialized. The programmer does not have to look for every occurrence of the variable and change each one individually. Constants are a great way to keep track of variables you don't want to change in any way while running your code.