This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Java in General and the fly likes Difference between String Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Difference between String " Watch "Difference between String " New topic

Difference between String

Rajendra Prakash
Ranch Hand

Joined: Sep 10, 2009
Posts: 293
I need the difference between string s="abc" and string s=new string("abc");
How many objects created for both .
The following i got from google , is it correct.

String s "abc"; is the simple case it will create one string object and one reference variable. "abc" will go into the pool and s will refer to it...

String s new String("abc"); it will create two objects and one reference variable.
java will create a new string object in the nonpool memory s will refer to it. the literal "abc" will be placed in the pool.
Mohamed Sanaulla
Saloon Keeper

Joined: Sep 08, 2007
Posts: 3151

This was discussed recently and many times before. And what you have found is correct.

Mohamed Sanaulla | My Blog
Rajendra Prakash
Ranch Hand

Joined: Sep 10, 2009
Posts: 293
can you say where string pool is located , inside heap memory or some where else
Siddhesh Deodhar
Ranch Hand

Joined: Mar 05, 2009
Posts: 118
If you want to really confirm the answer, you can put statements
string s="abc" and string s=new string("abc"); in main function of say and deassemble the code using command
javap -c Test. It will show you the details.

Good, Better, Best, Don't take rest until, Good becomes Better, and Better becomes Best.
Sidd : (SCJP 6 [90%] )
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15042

This is a frequently asked question - have a look at this post where I listed links to previous discussions of the same question.

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
subject: Difference between String
It's not a secret anymore!