1

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?

5
  • It has "special" support from the language itself. Otherwise, you won't be able to do it. Commented May 14, 2013 at 11:43
  • 8
    The Java Language Specifications, section 3.10.5 states: A string literal is always of type String. That's why this works. Commented May 14, 2013 at 11:45
  • @zellus: The duplicate does not really answer this question that well, IMO. It doesn't really ask for the difference between them, but why we can do it. Commented May 14, 2013 at 11:47
  • @jlordo: Do you minds expanding that into an answer? I'll remove my community answer if you do. Commented May 14, 2013 at 11:51
  • 1
    @nhahtdh: Edited your answer :P Was too lazy too start over :D Commented May 14, 2013 at 11:56

2 Answers 2

6

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";
Sign up to request clarification or add additional context in comments.

Comments

5

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.