Eugene
Eugene

Reputation: 60184

If a new object is instantiating here (if obj == "")

I'm wondering if a new object is creating here:

String obj;
if(obj == "") {
}

and here:

if(obj.equals("")){}

I mean is the object like new String("") instantiating for those both cases?

Upvotes: 1

Views: 106

Answers (5)

aioobe
aioobe

Reputation: 421030

No. There will be no object created for obj. Prehaps you're mixing up with C++ where the default constructor would have been called?

In

String obj;
if(obj == "") {
}

the check obj == "" will fail (since obj will equal null and "" will not).

In

if(obj.equals("")){}

you'll get a NullPointerException, since obj is null, which cannot be dispatched on.


If the question is whether or not an empty string is created for the purpose of comparing, the answer is: Not at runtime, but at compile time. Compare it with the question, "Is i == 5 creating an integer of value 5 here?" Well, not really.

Upvotes: 1

gfelisberto
gfelisberto

Reputation: 1723

That code does not even build. And the compiler tells you why:

"The local variable obj may not have been initialized"

Upvotes: 1

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43098

It depends. If string pool already contains the string "", then no new object will be constructed. Otherwise of course a new String object is constructed and put to the string pool.

Upvotes: 1

Andrzej Doyle
Andrzej Doyle

Reputation: 103797

Kind of.

You're right that the program will actually reference a full String object, containing the value "". However, this isn't strictly created at the point the method is invoked. The Strings for (compile-time constant) string literals are created in a JVM-wide constant pool when the class is loaded into the VM, and identical constants share the same strings.

Since there's almost certainly a class in the JVM itself that references the empty string literal, the string pool will already contain the object corresponding to "" and so your class won't actually cause a new object to be created.

Upvotes: 6

Pops
Pops

Reputation: 30828

No, obj is just a reference to nowhere in those cases. You'll get an error saying that obj hasn't been initialized in either case.

Upvotes: 1

Related Questions