Java Error “variable might not have been initialized” – Java错误 “变量可能没有被初始化&#8221。

最后修改: 2022年 4月 6日

1. Overview

1.概述

In this article, we are going to address the “variable might not have been initialized” error in Java programs. This error occurs when we declare a variable without initializing it. Therefore, we will discuss the error with an example and offer some solutions to solve it.

在这篇文章中,我们要解决Java程序中的 “变量可能没有被初始化 “的错误。当我们声明一个变量而不对其进行初始化时就会出现这个错误。因此,我们将通过一个例子来讨论这个错误,并提供一些解决方案来解决它。

2. Java Error: “variable might not have been initialized”

2.Java错误。“变量可能没有被初始化”

Should we declare a local variable without an initial value, we get an error. This error occurs only for local variables since Java automatically initializes the instance variables at compile time (it sets 0 for integers, false for boolean, etc.). However, local variables need a default value because the Java compiler doesn’t allow the use of uninitialized variables.

如果我们声明一个没有初始值的局部变量,我们会得到一个错误。这个错误只发生在局部变量上,因为Java在编译时自动初始化了实例变量(它为整数设置0,为布尔值设置false,等等)。然而,局部变量需要一个默认值,因为Java编译器不允许使用未初始化的变量。

Let’s write a simple code having an uninitialized variable:

让我们写一段简单的代码,有一个未初始化的变量。

public class VariableMightNotHaveBeenInitializedError {
    public static void main(String[] args) {
        int sum;
        int[] list = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
        for (int i = 0; i < list.length; i++) {
            sum += list[i];
        }
        System.out.println("sum is: " + sum);
    }
}

In this code, we calculate the sum of a list of integer numbers. Then, we put it in the variable sum. The following error appears at compile time:

在这段代码中,我们计算了一个整数列表的总和。然后,我们把它放在变量sum.中,在编译时出现以下错误。

Screenshot-2022-03-30-at-12.45.37

3. Solutions

3.解决方案

To solve the error, we should simply assign a value to the variable when creating it:

为了解决这个错误,我们应该在创建该变量时简单地给它赋值

public class VariableMightNotHaveBeenInitializedError {
    public static void main(String[] args) {
        int sum = 0;
        int[] list = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9};
        for (int i = 0; i < list.length; i++) {
            sum += list[i];
        }
        System.out.println("sum is: " + sum);
    }
}

Finally, by running the code, we get results without any errors:

最后,通过运行代码,我们得到的结果没有任何错误。

Screenshot-2022-04-04-at-13.58.25

4. Conclusion

4.总结

In this tutorial, we discussed how uninitialized variables in Java cause getting errors. Then, we wrote a simple Java code and declared a local variable to hold the result of an operation without any error.

在本教程中,我们讨论了Java中未初始化的变量是如何导致获得错误的。然后,我们写了一段简单的Java代码,并声明了一个局部变量来保存一个操作的结果,没有任何错误。