Final Reference v/s Primitive Variable

Primitive Variable

Consider the code,

final int i = 12;
i = 15; //ERROR
i++; //ERROR
  • The content of the primitive variable is the actual value.
  • The value of the primitive variable cannot be changed once initialized.

Reference Variable

  • The content of the reference variable is reference to the object in the memory, i.e.) the way to get to the object in the memory.
  • Reference variable cannot be reassigned to refer to a different object in the memory.
class Person
{
	String name;
	int age;

	public static void main(String[] args) {
		final Person p1 = new Person();
		p1 = new Person(); //ERROR

		Person p2 = new Person();
		p1 = p2; //ERROR
		p1 = null; //ERROR
	}
}
  • But the data (properties) within the object can be changed.
  • Final reference allows you to modify the state of the object but you cannot modify the reference variable to point to a different object in the memory.
class Person
{
	String name;
	int age;
      
       public static void main(String[] args) {
              final Person p1 = new Person();
              p1.age = 12;
              p1.name = "John";
              //This is legal. You can modify the state of final reference.
             p1.age = 30; 
             p1.name = "Peter";
       }
}

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.