Difference between constants and final variables in Java?

JavaObject Oriented ProgrammingProgramming

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 in C language constants are not supported in Java(directly). But, you can still create a constant by declaring a variable static and final.

  • 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.

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

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

Final variable in Java

Once you declare a variable final you cannot change its value. If you try to do so a compile time error will be generated.

Example

 Live Demo

public class FinalExample {
   public static void main(String args[]) {
      final int num = 200;
      num = 2544;
   }
}

Output

FinalExample.java:4: error: cannot assign a value to final variable num
   num = 2544;
   ^
1 error

The main difference between final variable and a constant (static and final) is that 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. Where a constant is un-modifiable and have only one copy through out the program. For example, consider the following Java program,

Example

 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.

raja
Published on 15-Oct-2019 06:51:23
Advertisements