Variable might not have been initialized error

2018-12-31 01:57发布

When i try to compile this:

public static Rand searchCount (int[] x) 
{
    int a ; 
    int b ; 

    ...   

    for (int l= 0; l<x.length; l++) 
    {
        if (x[l] == 0) 
        a++ ;
        else if (x[l] == 1) 
        b++ ;
    }

    ...   

}

I get these errors:

Rand.java:72: variable a might not have been initialized
                a++ ;
                ^
Rand.java:74: variable b might not have been initialized
                b++ ;
                ^
2 errors

it seems to me that i initialized them at the top of the method. Whats going wrong?

12条回答
高级女魔头
2楼-- · 2018-12-31 02:22

It's a good practice to initialize the local variables inside the method block before using it. Here is a mistake that a beginner may commit.

  public static void main(String[] args){
    int a;
    int[] arr = {1,2,3,4,5};
    for(int i=0; i<arr.length; i++){
        a = arr[i];
    }
    System.out.println(a);
  }

You may expect the console will show '5' but instead the compiler will throw 'variable a might not be initialized' error. Though one may think variable a is 'initialized' inside the for loop, the compiler does not think in that way. What if arr.length is 0? The for loop will not be run at all. Hence, the compiler will give variable a might not have been initialized to point out the potential danger and require you to initialize the variable.

To prevent this kind of error, just initialize the variable when you declare it.

int a = 0;
查看更多
流年柔荑漫光年
3楼-- · 2018-12-31 02:23
int a = 0;
int b = 0;
查看更多
情到深处是孤独
4楼-- · 2018-12-31 02:25

You haven't initialised a and b, only declared them. There is a subtle difference.

int a = 0;
int b = 0;

At least this is for C++, I presume Java is the same concept.

查看更多
泛滥B
5楼-- · 2018-12-31 02:29

You declared them but did not provide them with an intial value - thus, they're unintialized. Try something like:

public static Rand searchCount (int[] x)  
{ 
  int a = 0 ;  
  int b = 0 ; 

and the warnings should go away.

查看更多
不再属于我。
6楼-- · 2018-12-31 02:33

You declared them, but not initialized.

int a; // declaration, unknown value
a = 0; // initialization
int a = 0; // declaration with initialization
查看更多
宁负流年不负卿
7楼-- · 2018-12-31 02:33

Imagine what happens if x[l] is neither 0 nor 1 in the loop. In that case a and b will never be assigned to and have an undefined value. You must initialize them both with some value, for example 0.

查看更多
登录 后发表回答