Can a final keyword alone be used to define a constant 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.

Unlike other languages java does not support constants 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 into 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

 Live Demo

class Data {
   static final int integerConstant = 20;
}
public class ConstantsExample {
   public static void main(String args[]) {
      System.out.println("value of integerConstant: "+Data.integerConstant);
   }
}

Output

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

Constants without static keyword

If you create a final variable without static keyword, though its value is un-modifiable, a separate copy of the variable is created each time you create a new object.

Example

For example, consider the following Java program,

 Live Demo

class Data {
   final int integerConstant = 20;
}
public class ConstantExample {
   public static void main(String args[]) {
      Data obj1 = new Data();
      System.out.println("value of integerConstant: "+obj1.integerConstant);
      Data obj2 = new Data();
      System.out.println("value of integerConstant: "+obj2.integerConstant);
   }
}

Output

value of integerConstant: 20
value of integerConstant: 20

Here we have created a final variable and trying to print its value using two objects, thought value of the variable is same at both instances, since we have used a different object for each they are the copies of the actual variable.

According to the definition of the constant you need to have a single copy of the variable throughout the program (class).

Therefore, to create constant as pert definition, you need to declare it both static and final.

Updated on: 15-Oct-2019

268 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements