What is the difference between String a;
and String a = new String ();
Answer 1, authority 100%
According to @Pavel Parshin , in the first case the variable a
is not initialized (it is not even equal to null
). Its further use is impossible, otherwise a compilation error will occur error: variable a might not have been initialized
. Example .
In the second case, according to en-SO , a new String
object is created with an empty line inside ""
Sting a;
TextUtils.isEmpty (a); // compilation error - the variable is not initialized.
a = new String ();
TextUtils.isEmpty (a); // true
Answer 2, authority 42%
The above are good answers, but if it’s not clear, then String
is the name of the class, String a;
is the creation of a pointer to a class variable String
, it tells us that the variable of this class will be available at this pointer, but so far it is only a pointer that does not point to anything specific. new String ()
is the creation of a specific object in memory, for which space is allocated, and to which the same pointer a
can be used, thus this construction is String a = new String ();
tells us that the pointer a
will point to this particular object in memory new String ()
.
Answer 3, authority 8%
When writing String b
– you just create a variable b
, which is a reference to an object of type string
(but so far it is not does not indicate).
When you write String b = "Hello world"
, you initialize the object immediately, effectively substituting new
. And assign our link b
a link to this object.