Variable might not have been initialized error

前端 未结 11 1609
孤城傲影
孤城傲影 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<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;
    
    0 讨论(0)
  • 2020-11-21 06:13

    If they were declared as fields of the class then they would be really initialized with 0.

    You're a bit confused because if you write:

    class Clazz {
      int a;
      int b;
    
      Clazz () {
         super ();
         b = 0;
      }
    
      public void printA () {
         sout (a + b);
      }
    
      public static void main (String[] args) {
         new Clazz ().printA ();
      }
    }
    

    Then this code will print "0". It's because a special constructor will be called when you create new instance of Clazz. At first super () will be called, then field a will be initialized implicitly, and then line b = 0 will be executed.

    0 讨论(0)
  • 2020-11-21 06:17

    You declared them, but not initialized.

    int a; // declaration, unknown value
    a = 0; // initialization
    int a = 0; // declaration with initialization
    
    0 讨论(0)
  • 2020-11-21 06:17

    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.

    0 讨论(0)
  • 2020-11-21 06:20

    You declared them, but didn't initialize them with a value. Add something like this :

    int a = 0;
    
    0 讨论(0)
提交回复
热议问题