Is string initialization required in java ...?

class TestMe{ public static void main (String args[]){ String s3; System.out.print(s3); } } 

why the compiler gives an error, the refernce object has a default value of null, why is this not an output ... ??

error: variable s3 might not have been initialized

+4
source share
6 answers

local variables must be initialized before using them, local vars do not get the default values ​​in java, so your string s3 does not get the default value null, since this is a local variable, so a compiler error.

Fom JLS :

If the declarator does not have an initialization expression, then each reference to the variable must be preceded by the execution of the assignment to the variable, or a compilation-time error results in § 16 rules.

+2
source

This is a mistake because JLS says so in §14.4.2. Running local variable declarations:

If the declarator does not have an initialization expression, then each reference to a variable must be preceded by a variable assignment or a compile-time error occurs according to the rules of §16 .

+5
source

The default value of null applies only to non- final fields for a class.

All other cases require initialization before first use.

+1
source

Yes, it is necessary.

 String s3; s3 = "Something...."; System.out.print(s3); // prints "Something..." 

Before using a local variable, you must initialize it.

0
source

what i know about local variables:
Local variables are declared mainly to perform some calculations. Thus, the decision of the programmer to give the value of a variable and should not take default values. If the programmer mistakenly did not initialize the local variable, then it assumes the default value, then the result goes wrong. therefore, local variables will ask the programmer to initialize before using this variable to avoid errors.

0
source

The only scenarios that use defaut values ​​are when the corresponding variables are object fields or even local components of the array. Indeed, ALWAYS arrays initialize their cells with the appropriate default values.

Thus, in your case, your variable does not come from the field (since it is local to the method) and did not participate in the initialization of the array. Therefore, the compiler logically complains.

0
source

All Articles