Java-Final Variables

Final Variables

If you make any variable as final, that the variable cannot be modified by the methods in the class. You can provide an initial value for a final field when you declare it. For example :

There is a final variable data2, we are going to change the value of this variable, but It can’t be changed because final variable once assigned a value can never be changed.

Program

1

Program Source

class Data {
    
    int data1 = 20;
    final int data2 = 40;
    
    void changeData1(int da)
    {
        data1+=da;
    }
    
    void changeData2(int da)
    {
        data2+=da;
    }
}

public class Javaapp {

    public static void main(String[] args) {
        
        Data obj = new Data();
        obj.changeData1(20);
        System.out.println("data1 = "+obj.data1);
        obj.changeData2(40);
        System.out.println("data2 = "+obj.data2);
    }
}

Leave a Comment