A visible advantage of declaring a java variable as static final is that the compiled java class results in faster performance. Final is a ‘non-access modifier’ which can only be applied to a variable, method or class. It is basically unchangeable, as in , its value once assigned cannot be changed. The final keyword may be used in various different scenarios.
package com.final;
public class final FinalEx {
final int a=10;
final int i=0;
public void JBK()
{
for(i=0;i<5;i++) { //compile time error
//final variable's value can't be change
System.out.println("value of i="+i);
}
}
public static void main(String[] args) {
FinalEx finalEx=new FinalEx();
finalEx.JBK();
}
}
package com.javabykiran.Final;
public class FinalEx1 {
FinalEx1() {
System.out.println("This is a default constructer of FinalEx2");
}
final int a = 100;
final void show() {
System.out.println (a);
}
void welcome() {
System.out.println("Welcome to java by kiran,Pune");
}
}
public class FinalEx1Test extends FinalEx1{
void show(){
//compile time error because method cannot override
System.out.println(“This is method of FinalEx1Test");
}
public static void main(String[] args) {
FinalEx1 finalEx1=new FinalEx1();
finalEx1.show();
}
}
package FinalEx;
final class FinalClass {
void KiranShow(){
System.out.println("BY Kiran’s way final class cannot Be Inherited");
}
}
package FinalEx;
public class FinalClassTest extends FinalClass{
//Here compile time error is shown because the final class
//cannot be extended
public static void main(String[] args) {
FinalClass finalclass=new FinalClass();
finalclass.KiranShow();
}
}
Some more Examples
package com.javabykiran.Final;
public class A {
final B b; //ERROR; as it is not initialised
}
class B {
}
package com.javabykiran.Final;
public class A {
final B b = new B();
void m1() {
b = new B(); // ERROR as we are trying to change the address
}
}
class B {
}
package com.javabykiran.Final;
public class A {
final B b; // NO ERROR as we have done the initialisation in constructor
final int x;
A(){
b =new B();
x=28;
}
}
class B {
}
package com.javabykiran.Final;
public class A {
final int a = 90;
int b = 90;
}
class B {
void m1() {
A a = new A();
a.a=98; //ERROR -even from another class we cannot change
a.b=999; //NO ERROR-variable is not final, therefore we can change
}
}