Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

regarding Strings

 
Aman Verma
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I want to know the difference between

String str="abc"; &

String str=new String("abc");

I know that the statement : String str=new String("abc"); will create a new String object and store it on heap but then for the initialization String str="abc"; does java creates new object?
& how n=much objects will be created by following code,

String str="abc";
String str1="abc"
String str2="abc";
String str3=str1;
String str4=str1+str2;
String str5="abc"+str4;

Thanks
-Aman



 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Creates a new reference variable to a String object holding the data "ABC" which resides in the String constant pool.
If there is no such String object in the pool a new one is created.


Creates a new reference to a new String object holding the data "ABC" which resides on the heap.
No checking is done whether another String object with that value already exists elsewhere.


Will usually (not guaranteed though) print true.



Will never print true (unless there's a JVM/compiler which doesn't work correctly and replaces the dynamic string creation calls with calls to Strings in the String constant pool).

Number of objects created in your sample would be 3.
One String "abc", another "abcabc", and yet another "abcabcabc".
6 references to these 3 Strings will exist, 4 of them pointing to the same String "abc".
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic