Variable might not have been initialized error

前端 未结 11 1585
孤城傲影
孤城傲影 2020-11-21 05:50

When i try to compile this:

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

    ...   

    for (int l= 0; l

        
11条回答
  •  名媛妹妹
    2020-11-21 06:12

    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

    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;
    

提交回复
热议问题