Java Constants

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

Java Constants

Constants refer to immutable values. Constants are basically literals whose values cannot be modified or changed during the execution of the program. Java doesn’t provide built-in support for constants, but it is possible to create a constant using static and final modifiers. A constant can be used to make the 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.

Table Of Contents

Static Modifier

The static modifier allows a class variable to be used without creating an instance of that class. 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 class one object.

Final Modifier

The final modifier makes a variable’s value immutable. Once the value is assigned, it cannot be changed later in the 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.

In this tutorial we have learn about the Java Constants and its application with practical example. I hope you will like this tutorial.