I don't understand why you create a String object as follows:
String stringObj = "";
I think, it should be:
String obj = new String();
I don't understand why you create a String object as follows:
String stringObj = "";
I think, it should be:
String obj = new String();
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.
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).