well!! about the difference i can say is in the first statement String s="hell"; s is a variable of type string which is given value "hell".
But in the second statement String s=new String("hello"); here s is pointing to the reference of class String and it is instantiated using the keyword "new" (on the right hand side). now If you use s with a dot operator ie s.somemethod(); you will get the methods of class String example s.concat("som other string");
i hope it helps you.
Joined: Jul 21, 2006
Hi Dhwani, for String s="hell"; will s.concat("o"); work
Because I feel that String s="hell" would also create a string object
In both the cases what you have is the "String". So little surprisingly you can do all the operations on string literal that you can do on String object.
But note that
will keep the string pointed by s unchanged. The operation will return a new string with the value "hello".
Joined: May 08, 2007
well!! i think the answer given by Pradeep is exactly right when you use String s="hell";
than the method s.concat("o"); later you print the value of s you wil get "hell" no change will be there... instead you have to take another String str; than str=s.concat("o"); this will print "hello".
first, you can always go back and edit a post. at the top/center, you should see several icons. the one that looks like a paper/pencil will let you edit your posts, or even delete it entirely.
The difference between your two examples is subtle. Since Strings are so common, the creators of java gave you a shortcut for creating them. BASICALLY, there is not difference between s = "hello" and s = new String("hello");
That does not mean there is NO difference. You may want to try searching around this forum for "string pool". Once you've read about that a little more, come back here and ask any new questions you may have.
There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Joined: Oct 18, 2004
Since you are keen to know more on String, this may help you to satiate the inquisitor in you