Final Keyword

Ans)The final keyword can be assigned to:

  1. Class level variable
  2. method
  3. class
  4. Objects

If a variable is declared as final, the variable behaves as a constant. It means that value of the variable once set cannot be modified.

final int i = 1;
i = 5; // error
final List names = new ArrayList();
names = new ArrayList(); // error

It is not necessary to initialize final variable at the declaration. If a final variable is not intialized at declaration then the value needs to set in intializer block or constructor.

class Bangalore {
	fianl float latitude;
	final float longitude;
	float area;
	{
		latitude = 78.3;
		longitude = 101.22
	}
	Bangalore(final float latitude, final float longitude) {
		this.latitude = latitude;
		this.longitude  = longitude;

	}

}

But in case of a reference final variable, internal state of the object pointed by that reference variable can be changed. Note that this is not re-assigning. This property of final is called non-transitivity.

class TestFinalVariable {
		final List<String> days = Arrays.asList("Sun", "Mon", "Tues");

		public void testFinal() {
			days.add("Wed");
			days.add("Thur");
			//this will print "Sun" "Mon" "Tues" "Wed" "Thur"
			System.out.prinlnt(days);
			days = new ArrayList(); // this will throw an error
		}
}

If a final is assigned to a method then it cannot be overridden in its child class.

class Parent {
  final void print() {
    System.out.println("Inside");
  }          
}
  
class Child extends Parent {
  public final void print() {
   // error cannot  override final method
    System.out.println("Inside");
  }
} 

If a class is made as final, then no other class can extend it and make it as parent class. E.g. String Class cannot be extended.

Final objects are instantiated only once. i.e

final Map map = new HashMap();
map.put("key";,"value");
map = new HashMap(); // error

Declaring final keyword helps to achieve immutablility and is useful for systems which are multithreaded and acheiving concurrency is critical.


Recommend Reading

  1. How java manages Memory?
  2. Why is it advised to use hashcode and equals together?
  3. Comparable and Comparator in java
  4. How to create Singleton class in Java?
  5. Difference between equals and ==?
  6. When to use abstract class over interface?
  7. Difference between final, finally and finalize
  8. Why is it recommended to use Immutable objects in Java