-3
public class HelloWorld{ //Why is it throwing error here
  final static int i;
     public static void main(String []args){
       int i = call(10);
       System.out.println("Hello World"+i);
     }
     static int call(int y){
         int r= y;
         return r ;
     }
}

For the above program the use of final static int i; throws below error. Can anybody exactly tell me why is it. the same final static int i; works fine when declared inside a method.

Error:

$javac HelloWorld.java 2>&1
HelloWorld.java:1: error: variable i might not have been initialized
public class HelloWorld{
^
1 error
Udo Held
  • 12,314
  • 11
  • 67
  • 93

5 Answers5

4

You are getting the error, because that is how it is supposed to behave.

From JLS - Section 8.3.1.2:

It is a compile-time error if a blank final (§4.12.4) class variable is not definitely assigned (§16.8) by a static initializer (§8.7) of the class in which it is declared.

And from JLS - Section 16.8

Let C be a class, and let V be a blank static final member field of C, declared in C. Then:

  • V is definitely unassigned (and moreover is not definitely assigned) before the leftmost enum constant, static initializer (§8.7), or static variable initializer of C.

Now, since you have neither an static initializer, nor a static variable initializer, your final field is definitely unassigned.

You should assign i some value either at the point of declaration:

final static int i = 0;

or in a static block (not really needed here):

final static int i;
static { i = 0; }
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
2

final variable should be initialized at least to default.

static final variables should be initialized before class loading completes.That is you can initialize them at the time of declaration or in static blocks.

So your final variable should be like

 final static int i=0;//initialization at the time of declaration

or

final static int i;

static{
  i=0;//initialization in static block
}
Prabhaker A
  • 8,317
  • 1
  • 18
  • 24
1

The same goes for non static variables as well. Initialize it with 0 and you are fine.

final static int i= 0;

However you shadow it. You declare a new i and use that one. You your final i won't be used at all.

Udo Held
  • 12,314
  • 11
  • 67
  • 93
0

Assign i some value

final static int i = 0;

You might also be interested in

Why must local variables, including primitives, always be initialized in Java?

Community
  • 1
  • 1
Bhavik Shah
  • 5,125
  • 3
  • 23
  • 40
0

you need to be initialized final static int i; with some int value

Vijay
  • 8,131
  • 11
  • 43
  • 69