Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

final variables in Java

  • Difficulty Level : Basic
  • Last Updated : 05 Oct, 2021

In Java, we can use final keyword with variables, methods, and classes. When the final keyword is used with a variable of primitive data types such as int, float, etc), the value of the variable cannot be changed. 

Example 1: Usage of final with primitive datatype

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Java




// Java Program to illustrate Use of Final Keyword
// With Primitive Datatypes
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        // Final primitive variable
        final int i = 10;
        i = 30;
 
        // Error will be generated above
    }
}

Output:



Now you must be wondering what if we do use final keyword non-primitive variables, let us explore the same as we did above with the help of an example. 

Note: Non-primitive variables are always references to objects in Java, the members of the referred object can be changed. final for non-primitive variables just means that they cannot be changed to refer to any other object.

Example 2: Usage of final with primitive datatype 

Java




// Java Program to illustrate Use of Final Keyword
// With Primitive Datatypes
 
// Class 1
class Helper {
    int i = 10;
}
 
// Clss 2
// main class
class GFG {
 
    // Main driver method
    public static void main(String args[])
    {
 
        final Helper t1 = new Helper();
        t1.i = 30; // Works
 
        // Print statement for successful execution of
        // Program
        System.out.print("Successfully executed");
    }
}
Output
Successfully executed

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

 




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!