• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Difference between String s = "Marcus"; vs String s2 = new String("Marcus");

 
Ranch Hand
Posts: 224
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi please tell me difference between
String s = "Marcus";
String s2 = new String("Marcus");
What happens in heap?
 
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Amol

In this case a seprate new object gets create in heap having ref as s2
 
Ranch Hand
Posts: 961
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The only difference is that two object are created.




But in this case, they are different objects




If you would like to use the same object, then use the itern() method of String.



3.10.5 See String Literals in the JLS for further information.
 
Ranch Hand
Posts: 102
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1- String objects pool issue

String object is immutable; thats mean when you say

String s = "Mohammed";
s += "El-Adawi";

on runtime this means that a new String "Mohammed El-adawi" is created
and assigned to reference s
and String "Mohammed" now is eligable for gc

why sun have to do that ?, because String literals
(any thing between " " is reccognized by compiler as String literal)
are put by compiler in String pool, then if compilar found the same literal again for example

String s = "abc";
String m = "abc"; // compiler now found the same String literal

compiler will have one copy of "abc" and will assign both s,m to the same String literal, (at run time one object constructed and asigned to s,m)

if m change the String, s will point to the wrong thing, thats why String is immutable.

2- answer to your question

String s = "Marcus"; // One String object is built and assigned to s.

String s2 = new String("Marcus");
/* now compiler found "Marcus" in the pool
so it will not create a new object
new operator creates new object contains
Marcus at runtime
*/


String s3 = new String("Mohammed Not Marcus");
// compiler adds "Mohammed Not Marcus" to String pool but with no
// reference assignment, and String object created and assigned to S3 // at runtime

3- Another thing

String s1 = "abc";
String s2 = "abc";
System.out.println(s1 == s2); // true

but

String s1 = "abc";
String s2 = new String ("abc");
System.out.println(s1 == s2); // false

I hope that is helpfull
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
String s = "Marcus";
It is a string literal.
String s2 = new String("Marcus");
A new instance is created as you have created the string with the new operator.

But again if you have created a new string like
String s1 = "Marcus"

First it searches if the string "Marcus" is there in the string pool,(in this case,as it is already there),now it just reassigns the same to s1.
 
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
"sriya",
Welcome to the JavaRanch.

We're a friendly group, but we do require members to have valid display names.

Display names must be two words: your first name, a space, then your last name. Fictitious names are not allowed.

Please edit your profile and correct your display name since accounts with display names get deleted, often without warning

This is your third and final warning.

thanks,
Dave
 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
class StringTest{
public static void main(String args[]){
String s1="rajeev";
System.out.println(s1);
System.out.println(s1.hashCode());
String name=new String("rajeev");
System.out.println(name);
System.out.println(name.hashCode());

}
}

the out put is :
rajeev
-938404389
rajeev
-938404389

So according to our disscussion it is wrong please let me know the exact meaning whats going here
thanks in advance

 
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Vineela Kom has given a correct explanation.The hashCode method is overridden in String, so it returns the same value from two Strings which would return true from their equals() method. What you want to do is something like thisStrings not created with the new operator, which are compile-time constants: all the same object. Strings created with new operator: different object. String entered at runtime cannot be predicted by the compiler or JVM, so you can see whether they are the same object.

campbell@computer:~/java$ java StringEqualsDemo Campbell
s = Campbell, hash = fb83cb24, s1 = Campbell, . . .

And work the rest out for yourselves.>
 
Rajeev Kumarjamshedpur
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Campbell Ritchie

My confusion is according to the discussion when we create
String s1="rajeev";
the jvm ist of all checks whether the same object is already available in the string constant pool .if it is available then it create another reference to it if the same object is not there .then it create anothere object with the constant "rajeev" and store in to string constant pool
System.out.println(s1);
System.out.println(s1.hashCode());
String name=new String("rajeev");

but here the the new operator is used to create the string object . In this case JVM always create a new object without looking in string constant pool
so i am confusion is here why i have the same memory address if jvm create the new object without looking in string constant pool if possible please guide me


System.out.println(name);
System.out.println(name.hashCode());


Thanks in advance
 
Campbell Ritchie
Marshal
Posts: 79153
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The String hash code has nothing to do with the memory address.
 
Greenhorn
Posts: 17
Eclipse IDE Java ME Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Rajeev,

hashCode() method is overridden in String class, so it will give same result whenever equlas() method returns true for two objects.
 
Jd Sierra
Greenhorn
Posts: 17
Eclipse IDE Java ME Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Campbell Ritchie for such a nice explanation..
But still I have one doubt regarding to this which I want to make clear..

How many new objects will be created after following statement?


What I am assuming answer is..
1) Two objects will be created if "abc" is not referred from String Literal Pool
2) One object will be created if "abc" is already referred from String Literal Pool

so what I am thinking is..
if is already written somewhere previously in code, then will create only one new object, otherwise (if String s1="abc"; is not wriiten,then ) two new objects will be created.

Please tell me whether I am right or wrong? If wrong then why?
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jd Sierra wrote:


This is not valid Java syntax. Did you mean:
 
Greenhorn
Posts: 11
Postgres Database Java Ubuntu
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Sierra, don't get confused between "String pools" and "HEAP" as String Object in Java is treated bit differently.

1. lets take a scenario where you would have used new String() post String literal created in a POOL:

String myString = "fun" ; // this shall create an entry in the String pools (seperate memory location other than heap). [OBJECT CREATED]

and now if you do

String myString2 = "fun"; // this is mere a reference to the same String Object "fun" present in the Pool as created above [NO OBJECT CREATED]

and now if you do

String myString3 = new String("fun"); // this shall create a New Object in HEAP but not in POOL . [OBJECT CREATED] hence creating only single Object that is in HEAP

2. Now lets take a scenario where you would have used new String() pre String literal created in a POOL

String myString = new String("fun"); // this shall create a New Object in HEAP but not in POOL . [OBJECT CREATED] hence creating only single Object that is in HEAP

and then if you do

String myString2 = foo ; // this shall create an Object in the POOL . [OBJECT CREATED]

3. Now let's use intern() function of String to make the String Objects created using new operator available in the POOL

String myString = new String("fun").intern() // this shall create a New Object in HEAP and also place it in the POOL . [OBJECT CREATED]

and then if you do

String myString2 = foo ; // this shall make a reference to "fun" object in the POOL as 'intern()' method has done the job above . [NO OBJECT CREATED]


I hope this shall clear your doubt ...

Cheers!!!





 
Jd Sierra
Greenhorn
Posts: 17
Eclipse IDE Java ME Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jesper de Jong wrote:

Jd Sierra wrote:


This is not valid Java syntax. Did you mean:



ya, I am sorry. You are right Jesper. I meant

Jesper, I would like to have some words from you regarding to my doubt.
 
Jd Sierra
Greenhorn
Posts: 17
Eclipse IDE Java ME Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Ankur Kapoor wrote:

2. Now lets take a scenario where you would have used new String() pre String literal created in a POOL

String myString = new String("fun"); // this shall create a New Object in HEAP but not in POOL . [OBJECT CREATED] hence creating only single Object that is in HEAP

3. Now let's use intern() function of String to make the String Objects created using new operator available in the POOL

String myString = new String("fun").intern() // this shall create a New Object in HEAP and also place it in the POOL . [OBJECT CREATED]



I am not getting above statements because it contradicats with article of Strings in this forum as well as Book by Kathy Sierra. OR may be the reason is I am misunderstood somewhere and not getting the actual thing. So, here I am clearing all things and tell me where I am wrong with valid reason.

I would like to start with statements of Kathy Sierra's Book on page no. 434.

Kathy Sierra wrote:

In this case, because we used the new keyword, Java will create a new String object in normal (nonpool) memory, and s will refer to it. In addition, literal "abc" will be placed in the pool.



Now, I am concluding following things. Tell me where I am wrong.
Consider each and every of the following scenarios is independent and has no relationship with previous scenario.

1)

Only one object of String literal "abc" will be created here and it will be referred from String Literal Pool Table as well as it will be referred by Reference variable s.


2)

Here due to new keyword, one String object will be created in heap. Now we are passing String literal "def" to the String constructor. So, again one object of String literal "def" will be created and it will be referred from Strin Literal Pool Table just like in previous case but as we used new operator here, one extra object is created containg same literal "def" but it will not be reference from String Literal Pool and will be eligible for Garabage Collection. So, on the whole two objects are created in this case.

3)

now I want to know is how many object will be created in this case just and only because of line no.2?
After the end of first line, one object will be created as I mentioned in case 1.
Because of 2nd line, definately one object will be created containing String literal "ghi" due to new keyword which will not be referred from Strin Literal Pool Table. But I think here unlike in case 2, one more object containg String literal "ghi" will not be created which we are passing in String constructor because it's alreday available after line 1.
So, answer is only one new object is created just and only because of line no.2

4)
anybody can argue after reading my above statements that what is the use of intern() method when String is definately going to be referred from String Literal Table whether we use new keyword or not. I have following reasons for this:

i> If we have passed String literal while creating String using new operator, then there will be two objects in Heap containg same strings.One will be referred by reference variable and one will be referred from String Literal Pool. Now, if we apply intern() method on reference variable, then reference variable will also refer to the object which is being referred from String Literal Pool Table and another object will be eligible for garbage collection

ii> Another case where intern() method can be really helpful is when we do not pass String literal in String constructor and make String using array of characters or using any other valid arguments. At this time, as we have not passed String literal in an argument, only one object will be created which will not be permanent but after intern() method, it will be permanent as now it will be referred from String literal Pool.

Please tell me whereever I am wrong in any of above statements.
Regards
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Jd Sierra wrote:
3)

now I want to know is how many object will be created in this case just and only because of line no.2?
After the end of first line, one object will be created as I mentioned in case 1.
Because of 2nd line, definately one object will be created containing String literal "ghi" due to new keyword which will not be referred from Strin Literal Pool Table. But I think here unlike in case 2, one more object containg String literal "ghi" will not be created which we are passing in String constructor because it's alreday available after line 1.
So, answer is only one new object is created just and only because of line no.2


Maybe I am being too literal...but when you say "Just and only because of line no.2", to me, that means "ignore everything else - including line 1". then you say "at the end of the first line"...which you just told me to ignore.

I think the simplest way to think of it is this way

1) ANY and EVERY time you see the word "new", an object is created on the heap.
2) ANY and EVERY time the compiler sees a String literal for the first time, a String is created in the String pool.

So, if we look at these two lines of code...On line 1, we encounter a String literal of "ghi". If we assume we have not encountered it before, then a String object is created in the String Pool. The reference variable 's' is set to refer to that object.

On line 2, we encounter the String literal "ghi". This time, we HAVE encountered it before, so we do NOT need to create it in the String Pool. The 'new' operator then causes us to create a new object in the heap. It turns out we will create a String there, and create it with the value of "ghi".

s is then re-assigned to point to this newly created object on the heap. The old String object in the pool with a value of "ghi" is still there, and it is NOT eligible for gc, regardless of what else may or may not be referring to it.

 
Jd Sierra
Greenhorn
Posts: 17
Eclipse IDE Java ME Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Fred, nice explanation.

So,
after following statements,


total FOUR objects will be created. One after line 1, One more after line 2 and Two more after line 3. am I?
 
Ranch Hand
Posts: 45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Fred,

Thanks a lot your explanation which cleared all my doubts(which were pending for a long time) .
how many objects are created exactly with and with out new operator etc..
And when exactly is string created in pool and heap.
Even I read Kathy Siera and was quite confused with the explanation, but your two simple ways of thinking really helped


 
Ranch Hand
Posts: 679
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

fred rosenberger wrote:2) ANY and EVERY time the compiler sees a String literal for the first time, a String is created in the String pool.


Actually it's when a class loader sees a String literal for the first time that a String is created in the String pool. The compiler never creates objects.
 
Greenhorn
Posts: 1
Eclipse IDE Oracle Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hey Fred,

Many Thanks for your explanation which cleared my doubts [which were pending for a long time]
 
reply
    Bookmark Topic Watch Topic
  • New Topic