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.
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
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";
}