File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes regarding Strings Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "regarding Strings" Watch "regarding Strings" New topic
Author

regarding Strings

Aman Verma
Greenhorn

Joined: May 10, 2005
Posts: 15
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

Joined: Oct 12, 2000
Posts: 5093

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".


42
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: regarding Strings
 
Similar Threads
equals() and ==, doubt
comparing Strings
Is Kathy&Bert book wrong? Or my understanding wrong?
Can anyone explain what is == and equal( ) ?
equals versus ==