2

I am just starting out with Java. But I had a big puzzle when I am in the first chapter. It says that we have to "initialize" the handle when we are creating one, like String s = "asdf", and later it says we have create a new object for the string s again, String s = new String("asdf");.

I think the string s already has an object (asdf) in the "initialization", but why we still have to re-create it again(if I am understanding it right)?

Hope someone can explain this more to me, in book it is just skipped.

DontVoteMeDown
  • 21,122
  • 10
  • 69
  • 105

1 Answers1

2
String str1 = "asdf";               //This is a String literal
String str1 = new String("asdf");   //This is a String object

String objects are on the heap, whereas the literals are on the common pool for string literals.

Noe that if you do String s = "asdf"; and then String s = new String("asdf"); you'll get a compilation error for redeclaring s.

See the JLS for further information.

Maroun
  • 94,125
  • 30
  • 188
  • 241
  • Alright. So a String _object_ needs to create a new space of the memory to str1, however a String _literal_ is like quoting (or linking?) an already-established memory space (not sure if I put it in this way right) to it? – user3061156 Dec 04 '13 at 01:27