0

I am unable to find the reason why I am getting:

variable might not have been initialized

Example 1:

class Test {
    public static void main(String[] args) {
        int i = 10;
        int j;
        if (i == 10) {
            j = 20;
        }
        System.out.println(j);
    }
}
Test.java:11: error: variable j might not have been initialized
System.out.println(j);
                   ^
1 error

Example 2:

class Test {
    public static void main(String[] args) {
        int i = 10;
        int j;
        if (i == 10) {
            j = 20;
        } else {
            j = 30;
        }
        System.out.println(j);
    }
}

Output:

20

My doubt is in the second example, how j is initialized?

subbu royal
  • 584
  • 4
  • 12
  • 29

4 Answers4

3

First case, if i != 10 j will not be initialized during

System.out.println(j);

In the second example j will always have a value at (i != 10 j will be 30)

System.out.println(j);

Mind the

**might not** be initialized
Matteo Baldi
  • 5,613
  • 10
  • 39
  • 51
0

Instead of int j; you must have int j = null;.

Eric Reed
  • 377
  • 1
  • 6
  • 21
0

in the second example, how j is initialized?

j is initialized because you have provided paths for all possible cases ...

  • i is equal to 10 (the line if(i == 10) {)
  • i is not equal to 10 (the line } else {)

No matter what, j will be initialized.

In your first solution, this was not the case. If i is not equal to 10, then j will not be initialized and Java does not like that. Java does not care that i is equal to 10 in your logic, it just cares that there is a case where j may not be initialized.

Christien Lomax
  • 105
  • 2
  • 5
0

For local variables JVM won't provide any default values, we have to perform initialization explicitly, before using that variable.

In Example 1: There is no guarantee of initialization of local variable inside logical block at runtime, in your case you have only if statement if it's not true then how the initialization is going to happen , because of that you are getting this error.

In Example 2: You have taken both if ,else statement so if condition is true the variable j will be initialized, if the condition is false then also j will be initialized. (In Example 2 either through if or else variable j will be initialized) because of that you are not getting any error.

kavya
  • 182
  • 3
  • 15