Skip to main content

final keyword

Use of final keyword:

A data member of class can be declared as final

  •  final data member should be initialize any of three place
    1.  At a time of declaration
    2. Using respective block.
    3.  Using constructor
  •  We can not re-assign value of final data member

Declaring variable as a final

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package keyword;
 
public class Finalkeyword
{ 
    final int a=10;//initialize at the time of declaration
    final int b;
    final int c;
 
    //non static block
     {
        c=13;//initializing final value in non static block
     }
 
   // Constructor
   Finalkeyword()
      {
         b=12;//initializing in constructor
      }
 
public static void main(String[] args)
{
   System.out.println("*********************");
 
   Finalkeyword f=new Finalkeyword();
 
   // f.a=15;//error because final value can not re-assign
 
   System.out.println("a value : "+f.a);
   System.out.println("b value : "+f.b);
   System.out.println("c value : "+f.c);
 
   System.out.println("*********************");
 
  }
 
}
 
OUTPUT:
*********************
a value : 10
b value : 12
c value : 13
*********************