How to implement constants in java?


A constant variable is the one whose value is fixed and only one copy of it exists in the program. Once you declare a constant variable and assign value to it, you cannot change its value again throughout the program.

You can create a constant in c language using the constant keyword (one way to create it) as −

const int intererConstant = 100;
or,
const float floatConstant = 16.254;
….. etc

Constants in java

Unlike in C language constants are not supported in Java(directly). But, you can still create a constant by declaring a variable static and final.

Static − Once you declare a variable static they will be loaded in to the memory at the compile time i.e. only one copy of them is available.

Final − once you declare a variable final you cannot modify its value again.

Therefore, you can create a constant in Java by declaring the instance variable static and final.

Example

In the following Java example, we have 5 constants (static and final variables) in a class (named Data) and, accessing them from the main method of another class.

class Data{
   static final int integerConstant = 20;
   static final String stringConstant = "hello";
   static final float floatConstant = 1654.22f;
   static final char characterConstant = 'C';
}
public class ConstantsExample {
   public static void main(String args[]) {
      System.out.println("value of integerConstant: "+Data.integerConstant);
      System.out.println("value of stringConstant: "+Data.stringConstant);
      System.out.println("value of floatConstant: "+Data.floatConstant);
      System.out.println("value of characterConstant: "+Data.characterConstant);
   }
}

Output

value of integerConstant: 20
value of stringConstant: hello
value of floatConstant: 1654.22
value of characterConstant: C

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements