-3

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.

Ssiro
  • 127
  • 1
  • 5
  • 18
  • No. "I've seen a lot of questions like this but none of them had Strings that weren't initiated yet." – Ssiro Mar 02 '17 at 13:18
  • 3
    Just one, in the `String a` it is only declaring a variable `a` of type String. – Dazak Mar 02 '17 at 13:19
  • 2
    @Ssiro is asking whether declaring a variable creates any `Object`, the answer is obviously no, it is only a reference without any target – buræquete Mar 02 '17 at 13:19
  • Awesome, thanks. That's all I needed to know. Can one of you "Answer" the question so I can declare it solved ? – Ssiro Mar 02 '17 at 13:20

3 Answers3

1

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

buræquete
  • 14,226
  • 4
  • 44
  • 89
  • to be exact: `b` is not an object, it is a reference referencing a `new String()`. – piet.t Mar 02 '17 at 13:33
  • yes, but after the execution, you can call it object `b`, my wording might be confusing though – buræquete Mar 02 '17 at 13:34
  • 1
    Calling `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. – piet.t Mar 02 '17 at 13:36
  • Yeah, that I agree, sorry for the confusion, though that object will probably be shredded alive by gc – buræquete Mar 02 '17 at 13:37
1

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.

peterremec
  • 488
  • 1
  • 15
  • 46
1

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";
}
Dazak
  • 1,011
  • 2
  • 9
  • 17