Initialization of int datatype: Array vs Regular

class returntest { public static void main(String...args) { int a; System.out.println(a); //Line 1 int b[] = new int[10]; System.out.println(b[1]); //Line 2 } } 

I get a compiler error (obviously) on line 1, stating that the variable may not be initialized.

I know that all elements of an int array are initialized by default to 0 (so that line 2 compiles successfully), but my question is why the compiler can not apply the same logic (from 0 to all ints) to a regular (not an array) int variables.

Is there any restriction that prevents the compiler from doing this?

+4
source share
4 answers

Local variables defined in the statement block must always be initialized before use.

But member variables defined directly in the body of the class are automatically initialized to 0. When the object is created.

Useful thread here .

+4
source

From here: -

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, be sure to assign a value to it before attempting to use it. Access to an uninitialized local variable will result in a compile-time error.

+2
source

When the scope variable is local, you must initialize the local variable.

When you declare any local / block variable , they did not get the default value. They must assign some value before accessing it; another wise compiler will throw an error.

As you see in your code

 int a; //Gives error because not assigned any value 

When allocating resources for a local variable, Java does not write the value to memory. The reason you get the error message is because Java ensures that you give it a value before you use it. Sun realized that this could be a difficult problem to diagnose in C code, because you did not get help from the compiler, so they decided to check it at compile time.

Send link

0
source

It was a solution for language design.

Having a default initialization for local variables can hide errors. Using a local variable implies that you want to set it first. Simple cases of forgetting to install it or install it only in if will then be fixed.

0
source

Source: https://habr.com/ru/post/1499901/


All Articles