Wednesday 1 February 2017

Final Keyword In Java

Final Keyword

The final keyword in java is used to restrict the user. The java final keyword can be use with :
    - Variable
    - Method
    - Class

Final variable ( Stop value change ) :
If you make any variable as final, you cannot change the value of final variable(It will be constant).
Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed.

class Bike
{
    final int speedlimit=90; //final variable
    void run()
    {
        speedlimit=400;
    }
    public static void main(String args[])
    {
        Bike obj=new  Bike();
        obj.run();
    }
}

Output: Compile time error
mukesh@ubuntu:~/Desktop/javaPrograms$ javac Test.java
Test.java:6: error: cannot assign a value to final variable speedlimit
        speedlimit=400;
        ^
1 error

  
Final method   ( Stop method overriding ):
Example of final method

class Bike
{
    final void run()
    {
        System.out.println("Bike running");
    }
}
class Hero extends Bike
{
    void run()
    {
        System.out.println("Bike running safely with 100kmph");
    }
    public static void main(String args[])
    {
        Hero obj= new Hero();
        obj.run();
    }
}

Output: Compile time error
mukesh@ubuntu:~/Desktop/javaPrograms$ javac Test.java
Test.java:10: error: run() in Hero cannot override run() in Bike
    void run()
         ^
  overridden method is final
1 error

  
Final class  ( Stop inheritance ) :
If you make any class as final, you cannot extend it.
Example of final class

final class Bike
{
  
}
class Hero extends Bike
{
    void run()
    {
        System.out.println("running safely with 100kmph");
    }
    public static void main(String args[])
    {
        Hero obj= new Hero();
        obj.run();
    }
}

Output: Compile time error
mukesh@ubuntu:~/Desktop/javaPrograms$ javac Test.java
Test.java:5: error: cannot inherit from final Bike
class Hero extends Bike
                   ^
1 error

Point to be remember regarding Final.
- Final is almost opposite to the polymorphism.
- Final value can't be re-assigned.
- A final keyword can we used with 1)Variable 2)method & 3)class
- final method can be inherited but cannot overridden.
- A final variable that is not initialized at the time of declaration is known as blank final variable.
- We can not declare a cunstructor final, because constructor is never inherited.


Programs for Practice on Final Keyword

Program # 1
class A
{
    public static void main(String[] args)
    {
      int i=0;
      final int j=1;
      System.out.println(i);
      System.out.println(j);
      i=10;
      //j=1;
      System.out.println(i);
      System.out.println(j);

    }
}

Output:
i value can be modify anytime but j cant cause of final
0
1
10
1

Program # 2
class B
{
    public static void main(String[] args)
    {
      final int i=10;
      i++;
      System.out.println(i);
    }
}

Output:
compilation error:
B.java:6: cannot assign a value to final variable i
i++;
^
1 error

Program # 3
Note :Here array x is final ,we are modifying x[0],x[1] ie index value ,not array x hence no error.
class C
{
    public static void main(String[] args)
    {
      final int[]x=new int[2];
      x[0]=10;
      x[1]=20;
      System.out.println(x[0]);
      System.out.println(x[1]);
    }
}

Output:
10
20


Program # 4
Note : Here reassigning a final array hence error
class D
{
    public static void main(String[] args)
    {
      final int[]x=new int[3];
      x=new int[3];
      System.out.println("done");
    }
}

Output:
D.java:7: cannot assign a value to final variable x
x=new int[3];


Program # 5
Note : In this program we are modifying the i value not e1,Hence it is valid
class E
{
    int i;
    public static void main(String[] args)
    {
      final E e1=new E();
      e1.i=20;
      System.out.println("done");
    }
}

Output:
done

Program # 6
Note : In this program reference variable f1 can not re-initialize because of final.
class F
{
    int i;
    public static void main(String[] args)
    {
      final F f1=new F();
      //f1=new F(); --here trying to re-initialize a final ref var
      //f1=null;    --here trying to re-initialize a final ref var
      System.out.println("done");
    }
}

Output:
done

Program # 7
Note : A global final variable sud be initilize.
class F
{
    final int i=0;
    public static void main(String[] args)
    {
      F f1=new F();
      //f1.i=20;  --cannot re-initilize final variable
      //System.out.println(f1.i);
    }
}

Output:


Program # 8
Note : final argument in main method can not be re-assigned
class G
{
    public static void main(final String[] args)
    {
      System.out.println("Hello world");
      args=null;
    }
}

Output:
compiler error

Program # 9
class H
{
    final int i=10;
}
class Manager
{
    public static void main(final String[] args)
    {
      H obj=new H();
      System.out.println(obj.i);
      obj.i=10;//error :can't re-assign a final value.
      System.out.println(obj.i);
    }
}

Output:
error :can't assign a final value.

Program # 10
Note : Eventhough not calling test() ,final x can't be reassigned in test().
class I
{
    final int x=10;
    void test()
    {
        x=11;
    }
}
Output:
I.java:7: cannot assign a value to final variable x
  x=10;


Program # 11
Note:
1.Global final variable must be initilized at any cost.
    By the time of object creation global final variable can't survive with its default value
2.Not only at the place of declaration ,it can be initilize in constructor or in the IIB.

class J
{
    final int i;
}
class Manager1
{
    public static void main(String[] args)
    {
      J obj=new J();
      System.out.println(obj.i);
    }
}

Output:
J.java:2: variable i might not have been initialized
class J


Program # 12
class J
{
    final int i;
}

Output:
J.java:2: variable i might not have been initialized
class J


Program # 13
Note : A global final variable can be initialize inside constructor.
class L
{
    final int i;
    L()
    {
        i=10;
    }
}

Output:
compile successfull


Program # 14
class M
{
    final int i=10;
    M()
    {
        i=10;
    }
}

Output:
J.java:7: cannot assign a value to final variable i
i=10;

Program # 15
Note : If multiple constructor final value should be initilizing in each constructor.
class N
{
    final int i;
    N()
    {
        i=10;
    }
    N(int j)
    {
        i=10;
    }
    N(int k,double l)
    {
        i=10;
    }
}

Output:
successful compile

Program # 16
Note : Non-static final global works on object wise.create object N() nad N(int i) and analyse.

class N
{
    final int i;
    N()
    {
        i=5;
    }
    N(int i)
    {
        this.i=i;
    }
    N(int i,double d)
    {
        this.i=i;
    }
}
public class Demo
{
    public static void main(String[] args)
    {
        N obj1=new N();
        N obj2=new N(10);
        N obj3=new N(15,800);
        System.out.println(obj1.i);
        System.out.println(obj2.i);
        System.out.println(obj3.i);
    }
}

Output:
5
10
15

Program # 17
Note : In every constructor final variable should be initialize , this() is used to initialize the final in the second constructor. if removing this() then it will give compiler error

class Q
{
    final int i;
    Q()
    {
        i=10;
    }
    Q(String s1)
    {
        this();
    }
}

Output:
compile success

Program # 18
Note :IIB executing on object creation,hence through IIB we can initilize the final global variable

class R
{
    final int i;
    {
        i=0;
    }
}

Output:
compile sucess


Program # 19
Note : While crating obj first IIB will execute and i will get initilized,then constructor will execute and try to re-initilize the final value hence error

class S
{
    final int i;
    S()
    {
        i=0;
    }
    {
        i=0;
    }
}

Output:
J.java:7: variable i might already have been assigned
i=0;

Program # 20
Note : we can keep multiple IIB in a class.
class S
{
    final int i;
    {
        i=0;
    }
    {
        i=0;
    }
}

Output:
J.java:7: variable i might already have been assigned
i=0;

Program # 21
Note :
    Arguments of constructors and Method can be declare as a final,if argument declare as final then that should not be re-initilized.
    Argument is also a local variable,if lacal variable is final then that should not be re-initilized.
    while creating object we have to supply value to i,j.
    j is final here so j should not re-initilized here

class U
{
    U(int i,final int j)
    {
      i=20;
      j=20;
    }
}

Output:
J.java:7: final parameter j may not be assigned
j=20;

Program # 22
Note :
Static final global variable : means it acts as a perfect constant,static means only single copy on one execution Hence it can't be re-initilized

class V
{
    static final int i=10;
    public static void main(final String[] args)
    {
      System.out.println(i);
      i=20;
      System.out.println(i);
    }
}

Output:
J.java:7: final parameter j may not be assigned
j=20;

Program # 23
Note: global final variable can't survive with its default value,no matter it static or non-static.
class W
{
 final static int i;
}

Output:
J.java:2: variable i might not have been initialized

Program # 24
Note :gloabal final variable can be initilize in static block.
class W
{
    static final int i;
    static
    {
        i=0;
    }
}

Output:
compile success

Program # 25
class W
{
    static final int i=0;
    static
    {
        i=0;
    }
}

Output:
J.java:7: cannot assign a value to final variable i
i=0;

Program # 26
class Z
{
    static final int i;
    static
    {
        i=0;
    }
    static
    {
        i=0;
    }
}

Output:
J.java:11: variable i might already have been assigned
i=0;

Program # 27
Note :final keyword can be use with method also, so a final method can not be override in the subclass.
class C
{
     void test1()
     {
     }
     final void test2()
     {
     }
}
class D extends C
{
     void test1()
     {
     }
     void test2()
     {
     }
}

Output:
K.java:16: test2() in D cannot override test2() in C; overridden method is final
void test2(

Program # 28
Note : class can be also declare final. final class can not have a sub class

final class F
{
 //some member
}
class G extends F
{
}

Output:


Program # 29
Note: Abstract method means that method should be get implement in sub-class,so we can not use a final keyword with an abstract method.

abstract class E
{
    final abstract void test();
}

Output:
J.java:4: illegal combination of modifiers: abstract and final
final abstract void test();

Program # 30
abstract final class E
{
 //
}

Output:
J.java:2: illegal combination of modifiers: abstract and final
abstract final class E

Program # 31
Note : Compile success but can't create an object of abstract class
abstract class I
{
    public static void main(String[] args)
    {
        System.out.println("Hello World!");
    }
}

Output:
Hello World!

Program # 32
Note:
static method is not inheriting in sub-class ,hence the combination of :
[static & abstract] and [final & abstract] are not possible for method

abstract class J
{
 static abstract void test1();
}

Output:
K.java:4: illegal combination of modifiers: abstract and static

Program # 33
Note:
Every interface attributes are public static and final so in interface all attributes must be initilized at place of declaration.
we can't put SIB in interface

interface A
{
  int i;
}

Output:
A.java:3: = expected
int i;
^
1 error*/

Program # 34
interface B
{
 String s1=null;
 int j=0;
}

Output:
compile success

Program # 35
Note: a1.j--> compiler will modify reference variable to class name.
class A
{
 int i;
 static int j;
 public static void main(final String[] args)
 {
  System.out.println(j);
  System.out.println(A.j);
  A a1=new A();
  System.out.println(a1.i);
  System.out.println(a1.j);
 }
}

Output:
0
0
0
0

Program # 36
1.In every non-static definition block there is a default reference variable that is 'this'.
2.'this' is available in all non-static definition block,constructor,IIB and non-static methods
3.In main method this is not available ,so here we have to use reference variable to access.
4.Non-static member should be access with refernce variable.compiler will incorporate this inside the non-static block to access non-static member

class B
{
 int i;
 void test1()
 {
  System.out.println("test1:"+i);
  System.out.println("test1 by using this keyword:"+this.i);
  i=10;
  test2();
 }
 void test2()
 {
  System.out.println("test2:"+i);
  System.out.println("test1 by using this keyword:"+this.i);
  i=20;
  test3();
 }
 void test3()
 {
  System.out.println("test3:"+i);
  System.out.println("test1 by using this keyword:"+this.i);
  i=30;
 }
 public static void main(final String[] args)
 {
  B b1=new B();
  System.out.println("main1:"+b1.i);
  b1.i=5;
  b1.test1();
  System.out.println("main2:"+b1.i);
 }
}

Output:
main1:0
test1:5
test1 by using this keyword:5
test2:10
test1 by using this keyword:10
test3:20
test1 by using this keyword:20
main2:30

Program # 37
class G
{
 int i;
 G obj;
 public static void main(final String[] args)
 {
  G g1=new G();
  System.out.println(g1.i);
  System.out.println(g1.obj);
  g1.obj=new G();
  g1.obj.i=10;
  g1.i=20;
  System.out.println(g1.i);
  System.out.println(g1.obj.i);
 }
}

Output:
0
null
20
10

Program # 38
class C
{
 int i;
}
class D
{
 C c1;
 public static void main(final String[] args)
 {
  D d1=new D();
  System.out.println(d1.c1);
 }
}
class E
{
 C c1=new C();
 public static void main(final String[] args)
 {
  E e1=new E();
  System.out.println(e1.c1);
  System.out.println(e1.c1.i);
 }
}
class F
{
 C c1=null;
 public static void main(final String[] args)
 {
  F f1=new F();
  f1.c1=new C();
  System.out.println(f1.c1);
  System.out.println(f1.c1.i);
 }

}

Output:
D:
null
--------------
E:
C@3e25a5
0
--------------
F:
C@3e25a5
0

Program # 39
class P
{
 int i=1;
}
class Q extends P
{
 int i=2;
}
class R extends Q
{
 int i=3;
}
class Manager1
{
 public static void main(final String[] args)
 {
  P p1=new P();
  System.out.println(p1.i);

  P p2=new Q();
  System.out.println(p2.i);

  Q q1=new Q();
  System.out.println(q1.i);

  R r1=new R();
  System.out.println(r1.i);

  P p3=r1;
  System.out.println(p3.i);
  System.out.println(((Q)p3).i);
 }
}

Output:
1
1
2
3
1
2

Program # 40
class A
{
    void test1()
    {
      System.out.println("test1:"+this);
      test2();//this.test2();
    }
    void test2()
    {
      System.out.println("test2:"+this);
      test3();//this.test3();
    }
    void test3()
    {
        System.out.println("test3:"+this);
    }
    public static void main(final String[] args)
    {
      A a1=new A();
      System.out.println("Main:"+a1);
      a1.test1();
    }
}

Output:
Main:A@1a46e30
test1:A@1a46e30
test2:A@1a46e30
test3:A@1a46e30

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...