Paul Odero
Paul Odero

Reputation: 49

Why does Java allow to assign a string literal to a String object?

String is a class in java. While declaring and assigning string, it is correct to say String name = "Paul" though to instantiate an object from a java class we do String name = new String(); Taking name as an object, I'm wondering why we can assign a series of characters "Paul" to the object. Under what concept does this one works and how does it?

Upvotes: 1

Views: 1627

Answers (2)

nhahtdh
nhahtdh

Reputation: 56809

In Java code

"Paul"

is a String literal and

String name

a variable of type String with the name name.

The Java Language Specifications, section 3.10.5 states:

A string literal is always of type String

As 123 is an int literal and int number is a variable of type int with the name number, following both statements are legal, because the type on the left- and righthand side of the assignments match:

int number = 123;
String name = "Paul";

Upvotes: 6

Michal Borek
Michal Borek

Reputation: 4624

That's because implicitly Strings - "..." are treated as objects as well.

Under the cover JVM looks for similar "objects" in so called String pool and then if it finds it there it returns that object (instead of creating new one) otherwise creates new object and puts it to String pool.

This is for memory efficiency, and "Paul" so new String("Paul") is not the same.

This is possible because as we know, strings are immutable in Java.

You can read more about this behavior search for keyword "string pool".

Upvotes: 5

Related Questions