• 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

what is difference between Creating String object using new and Direct assignment ??

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

String s = "Java";
String s = new String("Java");

I read explanation about this in k&b but i did not get it ?

What is the difference between above 2 statement ?
How many objects are created ? and how many references is created ?

Thanks
[ April 25, 2008: Message edited by: Rahul Nair ]
 
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Rahul,

There no difference in initializing the string, either by direct assignment (String a = �Java�) or explicit call to constructor (String a = new String(�Java�)).
The only difference lies on JVM side. In first case, Object String �Java� is created in heap and reference is assigned to variable a.
Second case (String a = new String(�Java�)) just serves as a copy constructor that takes a String as an argument and creates a new instance that represents the same string of characters. Further more first string created (�Java�) is ready for garbage collection on the very next line.

The concept would be more illustrated by following Example:

public class TestString{

public static void main(String[] args){

String a = "Java";
String b = new String(a);
String c = "Java";

System.out.println("String a = " + a);
System.out.println("String b = " + b);
System.out.println("String c = " + c);

System.out.println("Result of a == b : " + (a == b));
System.out.println("Result of a == c : " + (a == c));
}
}

Output
=====

String a = Java
String b = Java
String c = Java
Result of a == b : false
Result of a == c : true

As in case of String b, Explicit Copy constructor is called, new reference is created for Java, while the same reference is allotted to C (Object pooling to enhance performance)

Regards,
Nishant
 
Rahul Nair
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Nishant,

Thanks for replying. Its a Nice explanation for my question,
But I am expecting Something more about STRING CONSTANT POOL. when compiler encounters a String literal, it checks pool for identical value. If exist the new string reference refer to the existing string.

String s = "Java";
String s1 = new String("Java");

In above case,

Is the reference variable s and s1 refer to the SAME OBJECT ??? OR there are 2 different Object one(String s="Java") in Constant Pool and another(String s1 = new String("Java")) in Heap ??

Because in k&b they clearly says that, Because of new keyword Java will create a new String object in normal(heap) memory. and literal "Java" in pool.

Thanks
 
Nishant Hadole
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Rahul,

Please see the result for the example given.

For objects a & c, JVM used String constant pool which is for efficient memory management in java. Unlike other Java Objects, instead of managing String object on heap area, they introduced String constant pool. One of important characteristic of String constant pool is that it doesn�t create same String object if there is already String constant in the pool.

But the story changes a bit for Object b here. The Explicit call to Copy constructor, forces JVM to create a regular object by new keyword on heap area and it will be placed in the String constant pool. Finally it will be assigned to the reference variable b. This process is just by passing from String constant pool management.

Thus a & c share same STRING LITERAL, but b got its own new, which has same text as that of a. That's why, expression a == c return TRUE, but not for a == b.

But wait; there is little twist in tail. Have a look at following case:

public class TestString{
public static void main(String[] args){
String s1 = "abc";
String s2 = "ab";

s2 = s2 + "c";

if (s1 == s2)
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}

What output is you expecting? This is second VARIATION to String Constant Pool. In this case s1 and s2 initially pointed to two different memory locations. As you appended �c� to s2, it seems to be same as s1, but how could Runtime failed to identify that. I guess the runtime behavior will put some light on it.

1. First existing content of s2 is copied to new memory location
2. �c� is appended to it.
3. s2 will now point to newly created String �adc�, and old content is ready to be garbage collected.

Same thing is clearly mentioned in Java Lexical Structures (JLS �3.10.5).
More on : http://java.sun.com/docs/books/jls/third_edition/html/lexical.html#48272

Was this explanation quite useful? Please do revert back to me in case of any concerns.
 
Rahul Nair
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Nishant,

Really it is very nice explanation...But i have some issues regarding this answer.


But the story changes a bit for Object b here. The Explicit call to Copy constructor, forces JVM to create a regular object by new keyword on heap area and it will be placed in the String constant pool. Finally it will be assigned to the reference variable b. This process is just by passing from String constant pool management



1. I agree that due to new keyword it is created in heap, But i never heard or read the process of moving object from heap to Pool ???

2. and If it moved to Pool then it is just like creating new Object(am i wrong ?) then if during moving if there is object with same value exist then it must refer to that existing object ???
So,Instead of displaying True it display false when i try to compare a==b.

Am i wrong ??

Thanks.
 
Nishant Hadole
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Rahul,

I too failed to find any Heap to String Pool movement. But if it is not so, does it mean that String are also created outside the Pool?

Need to Drill down more to find JVM behaviour, thus will need some time. Meanwhile, would like to know any more info, if avilable. I'm not even sure different versions of the VM would have to agree, so maybe at runtime depending on which VM you used you might get different results.

Although is not necessary for us programmer to know about the detail of JVM implementation about String Constant Pool. Some would say �I�m not stupid, I used equals to check equality of Strings. And I don�t really care how JVM in my OS implemented the damn Constant Pool�. But for me knowing this knowledge is something great.

The topic is still open for the discussion.
 
Rahul Nair
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Nishant,

There is nothing to do about how JVM behave but as a Certification Exam Point of View it is necessary to Know what to happened about String with same Valued String and created String Objects using different ways. Because there is too much gotchas(confusion) in String Concept in Java may be due to Efficient String Constant Pool and Heap. But i think(though i don't know whether it is correct or not ?) there nothing like moving objects from heap to pool.

If it moving objects to pool then i think the equal to condition (a==b) should have to display TRUE. But it can't.


If someone know about this pool management then please reply.

Thanks.
 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi!!

Here is a great article about The String Literal Pool.

Strings, Literally

Hope it helps you
 
Rahul Nair
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello Laura,

Thanks for Reply. It is really a Nice Article.

It really covers all doubts about pool management.

Thanks
 
Rahul Nair
Ranch Hand
Posts: 138
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hello,

But still i wondered by tracing output of code given by Nishant in 4th row Reply(Above).

after the statement s2=s1+"c"; why compiler does not check for existing String in String Constant Pool ??

Thanks.
 
Ranch Hand
Posts: 227
Eclipse IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

Some explanations:

* 'new' operator ALWAYS creates an object on heap.

* Programmatically string objects can only be created on heap.

* All methods in String class which return a string (toUpperCase(), toLowerCase(), trim() etc.) create the new object on heap, ONLY if required. If not required (say there are no white-spaces to trim), the same instance is returned.

* StringBuffer and StringBuilder produce string objects on heap on invoking toString().

* s.intern() on a String reference 's' (where s points to an object on heap) returns reference to an object in pool having the same char-sequence. If no such object is there in pool, it is created and its reference is returned. If s already points to an object in pool, the same reference is returned. This is the closest you get to moving object from heap to pool.


String s = "Java";
String s = new String("Java");

What is the difference between above 2 statement ?
How many objects are created ? and how many references is created ?



As explained by Nishant, line # 1 creates 1 object (in pool), whereas line # 2 (alone, not along with line # 1) creates 2 objects (one in pool, one on heap).


Second case (String a = new String(�Java�)) just serves as a copy constructor that takes a String as an argument and creates a new instance that represents the same string of characters. Further more first string created (�Java�) is ready for garbage collection on the very next line.



Please note that a string literal which has been created in pool is NEVER garbage-collected.


The Explicit call to Copy constructor, forces JVM to create a regular object by new keyword on heap area and it will be placed in the String constant pool



The new object created on heap (using the 'new' operator) is NOT placed in pool.


String s1 = "abc";
String s2 = "ab";

s2 = s2 + "c";

...

3. s2 will now point to newly created String �adc�, and old content is ready to be garbage collected.

...

But still i wondered by tracing output of code given by Nishant in 4th row Reply(Above).

after the statement s2=s1+"c"; why compiler does not check for existing String in String Constant Pool ??



JVM uses StringBuffer (for JDK <= v1.4) or StringBuilder (for JDK >= v1.5) to concatenate strings. Hence, at run-time, the last line in the code above changes to:



As stated earlier, toString() will always return string reference pointing to an object on heap. Again, please note that there are 4 objects getting created ("abc", "ab" and "c" in pool and resultant "abc" on heap) and no object is eligible for garbage-collection here.


1. I agree that due to new keyword it is created in heap, But i never heard or read the process of moving object from heap to Pool ???

...

I too failed to find any Heap to String Pool movement. But if it is not so, does it mean that String are also created outside the Pool?

...

But i think(though i don't know whether it is correct or not ?) there nothing like moving objects from heap to pool.



Please see the explanation regarding 'intern' method above.

Best regards,

- Aditya Jha
 
CLUCK LIKE A CHICKEN! Now look at this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic