• Post Reply Bookmark Topic Watch Topic
  • New Topic

String Declaration  RSS feed

 
Mayur Mane
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I have doubts in string declaration. As I know we can declare string in two ways:

1. String a=new String("Hello");
2. String b="Hello";

What is exact difference between them? Another thing is when I check (a==b) it retuns me false, but when I check a.equals(b) it returns me with true. Why So?
 
Stephan van Hulst
Saloon Keeper
Posts: 7961
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Mayur, welcome to CodeRanch.

The difference between the two statements is that in the first, you're making a copy of the object, and assigning a reference to the copy to a. In the second statement, you're assigning a reference to the original object to b.

Because Strings are immutable, the first statement is absolutely useless. Never use it. There's only one case that String's copy constructor has a valid use, but it's a rare situation.

As for your second question, please SearchFirst. This question is very common, and there are many threads about it.
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote: . . . There's only one case that String's copy constructor has a valid use, but it's a rare situation. . . .
Even that rare use ceased to apply in Java7.
 
Malatesh Karabisti
Ranch Hand
Posts: 153
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To give some hints, there is memory called 'String constant pool' when you do this object will be created in string pool.
 
ven jovovich
Ranch Hand
Posts: 33
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just to make things a little more interesting, check out what "intern()" does. ;)

Regards,
Ven.
 
Campbell Ritchie
Marshal
Posts: 56518
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The best thing to search for is an old JavaRanch journal article called “Strings, literally” by Corey McGlone.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!