-2

In my opinion, the default value for the int variable is 0. However, in my this demo, the variable num3 does not have the initialized value.

class Solution
{
    static int num1;
    int num2;
    public static void main(String[] args){
        int num3;
        int[] nums = new int[5];
        System.out.println("num1: " + num1);
        Solution sol = new Solution();    
        System.out.println("num2: " + sol.num2);
        System.out.println("num3: " + num3);
        System.out.print("nums:");
        for(int item : nums)
            System.out.print(" " + item);
        System.out.println("");
    }
}

I ran my demo on Ubuntu16.04. The error I got is as follows:

Solution.java:12: error: variable num3 might not have been initialized
        System.out.println(num3);
                           ^
1 error

If I remove this line System.out.println("num3: " + num3);, the results I have are as follows:

num1: 0
num2: 0
nums: 0 0 0 0 0

If anyone knows why, please let me know. Thanks.

tqjustc
  • 3,624
  • 6
  • 27
  • 42

1 Answers1

0

From https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html (my emphasis):

Default Values

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.

...

Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

Community
  • 1
  • 1
user94559
  • 59,196
  • 6
  • 103
  • 103
  • 2
    "Relying on such default values, however, is generally considered bad programming style."---outdated advice. IntelliJ actually has a warning "redundant initializer, 0 is the default value". – Marko Topolnik Sep 27 '16 at 19:34
  • @smarx I think we also can treat the array `nums` as the local variable. However, it seems that it has the default values. – tqjustc Sep 27 '16 at 23:30
  • @tqjustc The *array* doesn't have a default value. It has the value you assigned (`new int[5]`). – user94559 Sep 27 '16 at 23:53