Final is a keyword which finalize or fix particular thing. Suppose we use final keyword with variable then that variable cannot contain another value. Means it fixes the value which cannot be change in the same program.
For example: using final keyword with variable
class A{
final int i=10;
i=20; //20 will not be value of i because i is already final with 10.
System.out.println(i);
}
Output: 10
final keyword with array: When we use it with array, the size of array will be finalized. We can modify the value present in array but cannot modify the size of array.
For Example:
class A{
public static void main(){
final int[] a=new int[3];
a[0]=10;
a[0]=20;
System.out.println(a[0]);}
Output: 20 // we can modify value in array but cannot modify size.
final keyword with class: We can use final keyword in class to avoid inheritance. once we put final keyword with class that class cannot be inherited. we cannot use the variable or method of class class in other class.
final class A{
int i=10; }
class B extend A{
public static void main(){
B b=new b();
System.out.println(b.i);} }
Output: Error // as inheritance is not possible
*Note: We cannot inherit class with final keyword but we can inherit class in class with final keyword.
For Example:
class A{
int i=10; }
final class B extend A{
public static void main(){
B b=new b();
System.out.println(b.i);} }
Output:10 // as we inherited in class with final keyword