Why Are Local Variables Not Initialized in Java

Uninitialized local variable - No error : Java

There's nothing incorrect about that code. You don't actually use those variables so there's no issue. If you did try to use them it would then become a problem. For example,

System.out.println(a2);
System.out.println(x);

would bring about "Variable 'x'/'a2' might not have been intitialized" errors. There will be no default values or ability to run the code. It will be a compile time error and your code won't run. If the variables were class fields they would get default values for certain types or null otherwise.

Why must local variables, including primitives, always be initialized in Java?

Basically, requiring a variable to be assigned a value before you read it is a Good Thing. It means you won't accidentally read something you didn't intend to. Yes, variables could have default values - but isn't it better for the compiler to be able to catch your bug instead, if it can prove that you're trying to read something which might not have been assigned yet? If you want to give a local variable a default value, you can always assign that explicitly.

Now that's fine for local variables - but for instance and static variables, the compiler has no way of knowing the order in which methods will be called. Will a property "setter" be called before the "getter"? It has no way of knowing, so it has no way of alerting you to the danger. That's why default values are used for instance/static variables - at least then you'll get a known value (0, false, null etc) instead of just "whatever happened to be in memory at the time." (It also removes the potential security issue of reading sensitive data which hadn't been explicitly wiped.)

There was a question about this very recently for C#... - read the answers there as well, as it's basically the same thing. You might also find Eric Lippert's recent blog post interesting; it's at least around the same area, even though it has a somewhat different thrust.

java Local variable not initializing outside if-statement

Not only may you have an uninitialized variable, you're guaranteed to.

Look at your control flow: You first ask for a value for define, and then you execute exactly one of the blocks. If define is "boy", you don't initialize agirl; if define is "girl", you don't initialize aboy, and if define doesn't match either, you don't initialize any of your variables at all.

It looks like you are trying to cleverly combine the functions of a boolean and an int by having "magic" values in your ints. This is poor design because it's not clear how the magic works, but you can make your example run by initializing all of your int values to 0:

int aboy = 0, agirl = 0, age = 0;

Why local variable MUST be initialized and why instance variables MUST NOT be initialized before using?

As I know,

  • Instance variable: will be initial at the run time when class initial and default of instance variable is null => instance variable will error at run time.
  • Local variable: Unlike class and instance variables, a local variable is fussy about where you position the declaration for it: You must place the declaration before the first statement that actually uses the variable. => local variable error with syntax error.

    ref: Local variable in java

What happens to a declared, uninitialized variable in Java?

How exactly a JVM does this is entirely up to the JVM and shouldn't matter for a programmer, since the compiler ensures that you do not read uninitialized local variables.

Fields however are different. They need not be assigned before reading them (unless they are final) and the value of a field that has not been assigned is null for reference types or the 0 value of the appropriate primitive type, if the field has a primitive type.

Using s.isEmpty() for a field String s; that has not been assigned results in a NullPointerException.


So as I see now, it makes a big difference if the variable is declared locally or in the Class, though I seem to be unable to understand why when declaring in the class it gives no error, but when declaring in the main it produces the "Not Initialized" error.

In general it's undesirable to work with values that do not have a value. For this reason the language designers had 2 choices:

a) define a default value for variables not yet initialized

b) prevent the programmers from accessing the variable before writing to them.

b) is hard to achieve for fields and therefore option a) was chosen for fields. (There could be multiple methods reading/writing that could be valid or invalid depending on the order of calls, which could only be determined at runtime).

For local variables option b) is viable, since all possible paths of the execution of the method can be checked for assignment statements. This option was chosen during the language design for local variables, since it can help to find many easy mistakes.

Variable might not have been initialized error

You declared them, but you didn't initialize them. Initializing them is setting them equal to a value:

int a;        // This is a declaration
a = 0; // This is an initialization
int b = 1; // This is a declaration and initialization

You get the error because you haven't initialized the variables, but you increment them (e.g., a++) in the for loop.

Java primitives have default values but as one user commented below

Their default value is zero when declared as class members. Local variables don't have default values

Difference between local variable initialize null and not initialize?

The answer depends on what type of variable are you referring.

For class variables, there's no difference, see the JLS - 4.12.5. Initial Values of Variables:

... Every variable in a program must have a value before its value is
used:

For all reference types (§4.3), the default value is null.

Meaning, there is no difference, the later is implicitly set to null.

If the variables are local, they must be assigned before you pass them to a method:

myMethod(x); //will compile :)
myMethod(y) //won't compile :(


Related Topics



Leave a reply



Submit