Java Constants

In this tutorial you will learn about the Java Constants and its application with practical example.

Java Constants

Constants refers to immutable values. Constants are basically literals whose values cannot be modified or changed during the execution of program. Java doesn’t provide built-in support for constants, but it possible to create a constant using static and final modifiers. Constant can be used to make program more readable and understood by others. In addition, a constant is cached by the JVM as well as your application, so using a constant can improve performance.

Static Modifier

The static modifier allows a class variable to be used without creating an instance of that class. A static class members are associated with the class itself, rather than an individual object. All of the instances of a class share the same copy of a static variable.

Example:-

here, class classOne contains a static variable days_in_week, thus we are allowed to use it in classTwo without explicitly creating a classOne object.

Final Modifier

The final modifier makes a variable’s value immutable. Once the value is assigned, it cannot be changed later in program. The final modifier is used in conjunction with Primitive data types (i.e., int, short, long, byte, char, float, double, boolean) to make a variable immutable.

Example:-

Note:- By convention constant names are always preferred to be in uppercase.
Recommended:-  Java Comments
In this tutorial we have learn about the Java Constants and its application with practical example. I hope you will like this tutorial.