The “final” Keyword in JAVA

Why we use it and what’s the function ?

Shivansh Kumar
2 min readFeb 8, 2023

Key Concept behind using “final” keyword is to prevent the content to be modified

Declaring Variable or Reference as a final

  • When we declare variable as “final”, we are making it a constant. Means in the whole program the value will be the same as initialized(in it’s scope).
  • Final variable must be initialized while declaring. It’s bit logical, coz final itself saying I am final, I don't want to change, so there must be any value it is holding. Hence, we have to assign the value to it.
  • It provide immutability to variable of primitives type only not to the object.(to understand what does it mean go through below code snippets)
  • For references to objects, final ensures that the reference will never change, meaning that it will always refer to the same object. It makes no guarantees whatsoever about the values inside the object being referred to staying the same. (to understand what does it mean go through below code snippets)
/* Variabel as final */

final int TeamMember = 3; // This can't be modified coz of final keyword

TeamMember = 5; // we can't do like this because of final
// It will throw an error

/* object as a final */

final Student ram = new Student(89,"yuu"); //here the roll for object ram is 89

ram.roll=90; // But here we have reassing the roll with value 90,

--

--