The title says it all
String a;
String b = new String("Hello");
I've seen a lot of questions like this but none of them had Strings that weren't initiated yet.
Can someone help me on this ?
Thank you.
You are creating a single object that is referenced by variable b
, a
is a declared variable without any data assigned to it, that is not an object in a Java sense
b
is not an object, it is a reference referencing a new String()
.
b
, my wording might be confusing though
Mar 2, 2017 at 13:34
b
an object is going to end up in all sorts of confusion. Does b = null;
delete an object? No, it doesn't it clears a reference - the object might still be alive and well.
First row only declares a string variable, but doesn't create object. In the second row, a string object is created with a new
keyword.
So there's only one object created.
Here is an explanation took from OCA Java SE 7 Programmer I Certification Guide: Prepare for the 1ZO-803 exam:
An object comes into the picture when you use the keyword operator new. You can initialize a reference variable with this object. Note the difference between declaring a variable and initializing it. The following is an example of a class Person and another class ObjectLifeCycle:
class Person {}
class ObjectLifeCycle {
Person person;
}
In the previous code, no objects of class Person are created in the class ObjectLife-Cycle; it declares only a variable of type Person. An object is created when a reference variable is initialized:
class ObjectLifeCycle2 {
Person person = new Person();
}
Syntactically, an object comes into being by using the new operator. Because Strings can also be initialized using the = operator, the following code is a valid example of String objects being created
class ObjectLifeCycle3 {
String obj1 = new String("eJava");
String obj2 = "Guru";
}
String a
it is only declaring a variablea
of type String.Object
, the answer is obviously no, it is only a reference without any target