To what value is a variable of the String type automatically initialized?
null
Unless it's inside a method (local variable), in which case it's not declared to anything.
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.
If the variable is a class variable, instance variable, or array component, it is initialized to null
(since the default value for a reference type is null
)
If the variable is a local variable, then it must be given a value explicitly (i.e. it has no default value in this case).
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
String
is a local variable, it will not be initialized. - If the
String
is 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).
It's null
unless it's local, in which case it is technically uninitialized, but in fact you can't use it, for that reason, so the language is still type-safe. You can't deref a garbage pointer.