3

I don't understand why you create a String object as follows:

String stringObj = "";

I think, it should be:

String obj = new String();
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
ThiepLV
  • 1,219
  • 3
  • 10
  • 21
  • It should be noted that there is no need to initialize your "stringObj" reference variable when you declare it. So long as a value is eventually assigned to it before you use it somewhere, you can simply say `String stringObj;`. When a new value is assigned to "stringObj", it is a reference to a different object -- it's not modifying the String that the variable may have previously referenced. – Hot Licks Jul 06 '13 at 02:37
  • @WilliamMorrison, compare?! – RiaD Jul 06 '13 at 03:21
  • Covers the same subjects. Am I wrong in this? Perhaps it is not truly duplicate, I will remove flag. – William Morrison Jul 06 '13 at 03:22
  • @WilliamMorrison, Oh I see, both have common with string interning. Excuse me – RiaD Jul 06 '13 at 03:24
  • I will leave it be. This question may appear on some searches the other would not. – William Morrison Jul 06 '13 at 03:33

2 Answers2

5
String stringObj = "";

Is called as String literals. They are interned.

What that means is, let us say if you have

String stringObj = "";
String stringObj2 = "";
String stringObj3 = "";

All 3 references (stringObj, stringObj2, stringObj3) points to same memory location.

String obj = new String();

This syntax creates new String object on every invocation.

What that means is, let us say if you have:

String stringObj = new String();
String stringObj2 = new String();
String stringObj3 = new String();

Three new (separate) String objects will be created and point to different memory locations.

FThompson
  • 28,352
  • 13
  • 60
  • 93
kosa
  • 65,990
  • 13
  • 130
  • 167
  • you can explain more detail for me? – ThiepLV Jul 06 '13 at 02:04
  • As an aside, I wouldn't worry about whether or not two String objects point to the same memory location (since you can't modify them anyway). Thus, don't use == to compare strings. Use `s1.equals(s2)`. – ajb Jul 06 '13 at 04:31
4

Java compiler has special syntax for creating string objects from string literals. When you write

String stringObj = "";

Java creates a new String object, ans assigns it to stringObj.

Note that this is not directly equivalent to new String(), because strings instantiated from string literals are interned. This means that strings created from the same literal are not only object-equal, but also reference-equal (i.e. reference the same object).

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523