Can we change the state of an object to which a final reference variable is pointing?

Yes, we change the state of an object to which a final reference variable is pointing but we cannot re-assign a new object to this final reference variable. Example: Change state of the final object

class FinalReferenceTest{
	String name;
	int rollNo;
 
	FinalReferenceTest(String name, int rollNo) {
		this.name = name;
		this.rollNo = rollNo;
	}
 
	void show(){
	    System.out.println("Object State: ");
		System.out.println("Name: " + name);
		System.out.println("Roll No: " + rollNo);
	}
}
public class Main {
	public static void main(String args[]){
		//creating object of FinalReferenceTest Class
		final FinalReferenceTest obj = new FinalReferenceTest("Jai", 6);
		obj.show();
		obj.name = "Sandy";
		obj.show();
	}
}

Output

Object State: 
Name: Jai  
Roll No: 6                   
Object State: 
Name: Sandy
Roll No: 6

Example: re-assign a new object

class FinalReferenceTest{
	String name;
	int rollNo;
 
	FinalReferenceTest(String name, int rollNo) {
		this.name = name;
		this.rollNo = rollNo;
	}
 
}
public class Main {
	public static void main(String args[]){
		//creating object of FinalReferenceTest Class
		final FinalReferenceTest obj = new FinalReferenceTest("Jai", 6);
		obj = new FinalReferenceTest("Sandy", 6);
	}
}

Output

Main.java:16: error: cannot assign a value to final variable obj
		obj = new FinalReferenceTest("Sandy", 6);
		^
1 error

Java interview questions on final keyword

Please follow and like us:
Content Protection by DMCA.com