To what value is a variable of the String type automatically initialized?
10 Answers
Here's a summary of the answers posted by Martin v. Löwis and silky.
We can say the following about the initialization of a String object:
- If the
Stringis a local variable, it will not be initialized. - If the
Stringis a class variable, instance variable, or an array component, then it will be initialized tonull.
The reasoning is as follows:
As a variable with the type of String is a reference type, according to The Java Language Specification, Third Edition, Section 4.12.5: Initial Values of Variables says the following:
Every variable in a program must have a value before its value is used
It goes on to say the following about the initialization of reference types:
- Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10):
- [removed information on irrelevant information]
- For all reference types (§4.3), the default value is
null.
And finally, the follow about local variables:
- A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified by the compiler using the rules for definite assignment (§16).
Comments
A variable of type String is a reference variable. As an instance variable, it gets initialized to null, see the specification for the discussion of other cases.
Comments
- Any variable that is declared within a class is automatically initialized.
- Any variable that is declared within a method must be initialized otherwise it will generate an error.
- Strings are initialized to null,ints to 0 and so on..
Check this page for more information...