Published: Sunday, December 17, 2023, Updated: Sunday, December 17, 2023

Differences Between Final Variable and Static Variable in Java with Example

In Java, final and static are two different modifiers that can be applied to variables, and they serve distinct purposes.

Final Variable

  • When a variable is declared as final, it means that its value cannot be changed after it has been assigned a value.
  • Once a final variable is assigned a value, attempting to reassign a new value to it will result in a compilation error.
  • final variables are often used to create constants or to ensure that a variable retains a constant value throughout its lifetime. public class Example { final int constantValue = 10; public void changeValue() { // Compilation error: cannot assign a value to a final variable // constantValue = 20; } }

Static Variable

  • When a variable is declared as static, it means that the variable is associated with the class rather than with instances of the class (objects).
  • There is only one copy of a static variable, regardless of how many instances of the class are created.
  • static variables are often used to represent class-wide information or shared data among instances of the class. public class Example { static int staticVariable = 5; public static void main(String[] args) { // Accessing a static variable System.out.println(Example.staticVariable); // Modifying a static variable Example.staticVariable = 10; } }

Combining final and static:

  • It is possible to use both final and static modifiers together for a variable. In this case, the variable becomes a constant that is associated with the class and cannot be changed.
   public class Example {
       static final int CONSTANT_VALUE = 42;

       public static void main(String[] args) {
           // Accessing a final static variable
           System.out.println(Example.CONSTANT_VALUE);

           // Compilation error: cannot assign a value to a final variable
           // Example.CONSTANT_VALUE = 10;
       }
   }

In summary, a final variable is one whose value cannot be changed once assigned, and a static variable is associated with the class rather than instances of the class.

They can be used independently or together, depending on the requirements of the program.

Elliyas Ahmed
Elliyas Ahmed
Elliyas Ahmed, founder of COMPROMATH, is a Computer Science and Engineering graduate who excels in Blogging, Website Development, and SEO. He offers freelancing services to help clients succeed online. Learn more about Elliyas Ahmed.