Please confirm that your displayed name bears some similarity to your real name; Hyderabad is a city, but I know there are some people who have names like "London" and "Lancaster" and "York(e)."
new String("swapna") involves two String objects.
1: new String("swapna")
2: new String("swapna")
There is the "swapna" which you have written in the code as a String literal. If you have used "swapna" anywhere else, the JVM will use the same object in the String pool for both. The new String bit, however, will create a second object, whose value is (would you believe) "swapna".
This is called a copy constructor, and is probably in the String class more for completeness' sake than because people need it all the time, as you find out if you read the API.
Joined: Nov 20, 2008
string pool is containing the literals: swapna,abc,campbell.....
I hav ecreated the string
inthis scenario also it creates two strings?..means the string poll is already having "abc" literal..
Consider the normal way an object is created with the new operator:
new <classname>(<args>) ;
So when you write:
what is the type of the argument to the String constructor?... That's right, its a String. So if you already have a String, you have to have one to pass to the String constructor, why do you need the extra characters to create another String. The answer is you usually don't. I can say with some degree of certainty that you will never need to use the new String(String) constructor when the argument is a String literal. There are some rare cases when you will have to do this when the argument is not a literal String, but rather a String created by some other method. But the takeaway from all this is that there are indeed two String objects created, the String object created by the String literal, and the String object that is created as a result of calling the String constructor. [ December 01, 2008: Message edited by: Garrett Rowe ]
Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter