difference between string literal and string object

3195 단어 Java
new String("text");  explicitly creates a new and referentially distinct instance of a  String  object;  String s = "text";  may reuse an instance from the string constant pool if one is available.
You very rarely would ever want to use the  new String(anotherString)  constructor. 
From the API: String(String original)  : Initializes a newly created  String  object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string. Unless an explicit copy of original is needed, use of this constructor is unnecessary since strings are immutable.
Whenever you call  new  in JAVA it create an object in heap and obviously it will call the constructor also.
String literals will go into  String Constant Pool .
It might help you to understand it visually to remember it for longer time.
Whenever you call  new  in JAVA it create an object in heap and obviously it will call the constructor also.
String literals will go into  String Constant Pool .
It might help you to understand it visually to remember it for longer time.
Object creation line by line: String str1 = new String("java5");
Using string literal "java5"in the constructor, an new string value is stored in string constant pool
Using new operator a new string object is created in the heap with "java5"as value
String str2 = "java5
Reference  str2  is pointed to already stored value in string constant pool
String str3 = new String(str2);
A new string object is created in the heap with the same value as reference by  str2
String str4 = "java5";
Reference  str4  is pointed to already stored value in string constant pool

Total objects: Heap [더미] - 2, Constant Pool [상수 탱크] - 1
Whenever you call  new  in JAVA it create an object in heap and obviously it will call the constructor also.
String literals will go into  String Constant Pool .
It might help you to understand it visually to remember it for longer time.
Object creation line by line: String str1 = new String("java5");
Using string literal "java5"in the constructor, an new string value is stored in string constant pool
Using new operator a new string object is created in the heap with "java5"as value
String str2 = "java5
Reference  str2  is pointed to already stored value in string constant pool
String str3 = new String(str2);
A new string object is created in the heap with the same value as reference by  str2
String str4 = "java5";
Reference  str4  is pointed to already stored value in string constant pool

Total objects : Heap - 2, Pool - 1

좋은 웹페이지 즐겨찾기