Win a copy of OCP Java SE 8 Programmer II Exam Study Guide this week in the OCP forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

String Declaration  RSS feed

 
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?
 
Saloon Keeper
Posts: 8580
161
  • 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.
 
Marshal
Posts: 58321
178
  • 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.
 
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.
 
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: 58321
178
  • 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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!