Can a new object be stored in the previous object - java

String s1=new String("Java"); /* 1st object created */
String s2="Tech"; /* 2nd Object */
s1+=s2;
I'm confusing here whether new object created or result stored in the previous object.
How many Objects created

str1 += str2
is equivalent to doing the following:
str1 = new StringBuilder().append(str1).append(str2).toString();
Final call to toString will create a new object and the reference will be hold by variable str1 here in 3rd line of code. The earlier object in heap String("Java") will become ready for garbage collection.
Java is not similar to c in case of strings it creates a new object instead of modifying the existing objects. This is cause strings in java are immutable.

String s1=new String("Java"); /* 2 objects created as 'new' is used - s1 (holds reference to new String) and string literal "Java" */
String s2="Tech"; /* 3rd Object - "Tech", s2 just holds reference to it */
s1+=s2; /* 4th Object created, which is concatenation of s1 and s2. s1 holds reference to it.
So total 4 objects created.

Related

String intern() method usage confusion

We use intern() method for the Strings which are created through new String() so that they will create an entry in String Pool and return the newly created String from the String Pool so that this created string is eligible for use with == operator (as per my understanding).
Then what is the use of creating a new String through constructor?
When should we use constructor for creating new String?
new String() can create at-most two Objects of String and at-least one. one in constant pool (if same is not present in constant pool) and another in heap memory.
constant pool entry is created by interning String object.
intern will create String Literal in Constant pool so that whenever you create String without new keyword it will not create string object.
suppose you have created as
String str= new String("abc");
two object will be created one in constant pool (if "abc" is not present in constant pool). jvm wil internally call intern for that object.
so next time if you are doing
String str1= "abc";
no entry will be added to constant pool because only entry can be possible in constant pool for same literal.
public native String intern(); java doc says,
A pool of strings, initially empty, is maintained privately by the class >{#code String}. When the intern method is invoked, if the pool already >contains a string equal to this {#code String} object as determined by >the {#link #equals(Object)} method, then the string from the pool is >returned. Otherwise, this {#code String} object is added to the pool and >a reference to this {#code String} object is returned. It follows that >for any two strings {#code s} and {#code t}, {#code s.intern() == >t.intern()} is {#code true} if and only if {#code s.equals(t)} is {#code >true}.
Let's consider an example:
String temp1 = new String("abcd"); this means, a new object "abcd" will be created in the heap memory and its reference will be linked to temp1.
String temp2 = new String("abcd").intern(); this means "abcd" literal will be checked in the String Pool. If already present, its reference will be linked to newly created temp2. Else a new entry will be created in String Pool and its reference will be linked to newly created temp2.
String temp3 = "abcd"; this means "abcd" literal will be checked in the String Pool. If already present, its reference will be linked to newly created temp2. Else a new entry will be created in String Pool and its reference will be linked to newly created temp3. This conclude that, Java automatically interns String literals.
Let's consider another example:
String s1 = "string-test";
String s2 = new String("string-test");
String s3 = new String("string-test").intern();
if ( s1 == s2 ){
System.out.println("s1 and s2 are same");
}
if ( s2 == s3 ){
System.out.println("s2 and s3 are same" );
}
if ( s1 == s3 ){
System.out.println("s1 and s3 are same" );
}
Output: s1 and s3 are same
Now when to create a String object using = " " or using new String(" ")?
One use case which I came across,
// imagine a multi-megabyte string here
String s = "0123456789012345678901234567890123456789";
String s2 = s.substring(0, 1);
s = null;
You'll now have a String s2 which, although it seems to be a one-character string, holds a reference to the gigantic char array created in the String s. This means the array won't be garbage collected, even though we've explicitly nulled out the String s!
The fix for this is to use String constructor like this:
String s2 = new String(s.substring(0, 1));

Confusion about new String and String literals in Java

According to Kathy Sierra's book:
String s = "abc"; // creates one String object and one
// reference variable
In this simple case, "abc" will go in the pool and s will refer to it.
String s = new String("abc"); // creates two objects,
// and one reference variable
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,the literal "abc" will be placed in the pool.
As I know, when we use literals, it stores value in pool but when we use new keyword it creates object in heap. Here I want to know, is the heap object refer pool data (String) or not?
The variable you created using new String("abc") is not the same as the pool "abc" string.
String string1 = "abc";
String string2 = new String("abc");
System.out.println(string1.equals(string2)); //will print true
System.out.println(string1 == string2); //will print false

Java String object creation

I have been reading Java String object and I had this question -
String x="a";
String y="b";
Does it create two objects in Java?
Those two lines of code will not create any objects. String literals such as "a" are put in the string pool and made available upon class loading.
If you do
String x = new String("a");
String y = new String("b");
two objects will be created in runtime.
These questions/answers should cover follow-up questions:
Questions about Java's String pool
How many Java objects are generated by this - new String("abcd")
When ever a String is initialized using new operator its new object is created.
Like if you do
String s1= new String ("string");
String s2=new String ("string");
String s3=new String ("string");
All of the three will create a separate String object in the heap.
Whereas if all the above strings are initialized without new operator then, firstly the string will be checked in string pool for its existence. If required string exist then the new reference will start pointing to the existing string.Otherwise it will create new sting in the pool. For example:
String s1= "string";
String s2="string";
String s3="string1";
In the above example only two string will be created in string pool ("string" and "string1"). Where String s1 and s2 will refer to single object "string" and s3 will refer to another string object "string1".
String with literals gets created in String Pool. whereas String through new operators gets created in Heap Memory.
Advantage of creating String through literals is if that String value is already available in String Pool then you get the same reference where through new operator everytime you create a new object new reference.
In your case you will get same reference. so only object.
String object will be created by each line, unless they already exist in string pool...if they exist in string pool only a reference will be linked to your variable and no new objects will be created.

Strings [= new String vs = ""]

So my question is in relation to declaring and assigning strings.
The way I usually declare strings is by doing the following:
String s1 = "Stackoverflow";
And then if I ever need to change the value of s1 I would do the following:
s1 = "new value";
Today I found another way of doing it and declaring a string would go like:
String s2 = new String("Stackoverflow");
And then changing the value would be:
s2 = new String("new value");
My question is what is the difference between the two or is it simply preferential. From looking at the code the fourth line
s2 = new String ("new value");
I'm assuming that doing that would create a new memory location and s2 would then point to it so I doubt it would be used to change the value but I can see it being used when declaring a string.
From the javadoc :
Initializes a newly created String object so that it represents the
same sequence of characters as the argument; in other words, the newly
created string is a copy of the argument string. Unless an explicit
copy of original is needed, use of this constructor is unnecessary
since Strings are immutable.
So no, you have no reason not to use the simple literal.
Simply do
String s1 = "Stackoverflow";
Historically, this constructor was mainly used to get a lighter copy of a string obtained by splitting a bigger one (see this question). Now, There's no normal reason to use it.
String s1 = "Stackoverflow"; // declaring & initializing s1
String s2 = new String("Stackoverflow"); // declaring & initializing s2
in above cases you are declaring & initializing String object.
The difference between
//first case
String s2 = new String("new String"); // declaring & initializing s2 with new memory
// second case
s2 = "new String" // overwriting previous value of s2
is in the first case you are creating a new object, i-e; allocating memory for a new object which will be refrenced by s2. The previous address to which s2 was pointing/referencing hasn't released the memory yet which will be gc when the program ends or when system needs to.
The good programming practice (second case) is to initialize an object once, and if you want to change its value either assign null to it and then allocate new memory to it or in case of string you can do like this
s2= "new String";
String s1 = "Stackoverflow";
This line will create a new object in the String pool if it does not exist already. That means first it will first try searching for "Stackoverflow" in the String pool, if found then s1 will start pointing to it, if not found then it will create a new object and s1 will refer to it.
String s2 = new String("Stackoverflow");
Will always create a new String object, no matter if the value already exists in the String pool. So the object in the heap would then have the value "Stackovrflow" and s2 will start pointing to it.
s2 = new String("new value");
This will again create a new Object and s2 will start pointing to it. The earlier object that s2 was pointing to is not open for garbage collection (gc).
Let me know if this helps.
The main difference is that the constructor always creates a totally new instance of String containing the same characters than the original String.
String s1 = "Stackoverflow";
String s2 = "Stackoverflow";
Then s1 == s2 will return true
String s1 = "Stackoverflow";
String s2 = new String("Stackoverflow");
Then s1 == s2 will return false
Just using the double quotes option is often better:
With a constructors you might create two instance of String.
Easier to read and less confusing
#user2612619 here i want to say is .. when ever ur creating object with "new" operator it always falls in heap memory . so wenever u have same content but different objects than also it will create new objects on heap by this u cant save memory ....
but in order to save memory java people brought concept of immutable where we can save memory .. if u r creating a different object with same content .. string will recognize dat difference and creates only one object with same content and points the two references to only one object ..
i can solve ur doubts from this figure ..
case 1:
String s = new String("stackoverflow");
String s1 = new String("stackoverflow");
as they are two different objects on heap memory with two different values of hashcode .. so s==s1 (is reference comparison) it is false .. but s.equals(s1) is content comparison ..so it is true
case 2:
String s = "stackoverflow";
String s1 = "stackoverflow";
here objects fall in scp(string constant pool memory)
same object for two different refernces .. so hashcode also same .. same reference value .. so s==s1 is true here [u can observe from figure clearly]
s.equals(s1) is true as content comparison.. this is very beautiful concept .. u will love it wen u solve some problems ... all d best
Creating String object Directly:
String s1 = "Hip Hop"
will create a string object but first JVM checks the String constant or literal pool and if the string does not exist, it creates a new String object “Hip jop” and a reference is maintained in the pool. The variable s1 also refers the same object. Now, if we put a statement after this:
String s2 = "Hip Hop"
JVM checks the String constant pool first and since the string already exists, a reference to the pooled instance is returned to s2.
System.out.println(s1==s2) // comparing reference and it will print true
java can make this optimization since strings are immutable and can be shared without fear of data corruption.
Creating String Object using new
String s3 = new String("Hip Hop")
For new keyword, a String object is created in the heap memory wither or not an equal string object already exists in the pool and s3 will refer to the newly created one.
System.out.println(s3==s2) // two reference is different, will print false
String objects created with the new operator do not refer to objects in the string pool but can be made to using String’s intern() method. The java.lang.String.intern() returns an interned String, that is, one that has an entry in the global String literal pool. If the String is not already in the global String literal pool, then it will be added to the pool.
String s4 = s3.intern();
Systen.out.println(s4 == s2); // will print `true` because s4 is interned,
//it now have the same reference to "Hip Hop" as s2 or s1
But try:
Systen.out.println(s4 == s3) // it will be false,
As the reference of s4, s2 and s1 is the reference to the pooled instance while s3 is referring to the created object in heap memory.
use of new for creting string:
prior to OpenJDK 7, Update 6, Java String.susbtring method had potential memory leak. substring method would build a new String object keeping a reference to the whole char array, to avoid copying it. You could thus inadvertently keep a reference to a very big character array with just a one character string. If we want to have minimal strings after substring, we use the constructor taking another string :
String s2 = new String(s1.substring(0,1));
The issue is resolved in JDK 7 update 6. So No need to create string with new any more for taking advantage provided by String literal pool mechanism.
Referance:
String literal pool
using new to prevent memory leak for using substring

How many objects are created including String objects [duplicate]

This question already has answers here:
String equality vs equality of location
(6 answers)
What is the difference between == and equals() in Java?
(26 answers)
Closed 9 years ago.
Can anyone tell me how many objects are created. Does s3 not reference the same hello from string pool? how many String objects are there
/**
*
*/
package agnitio;
/**
* #author admin
*
*/
public class TestString {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String s1="hello";
String s2="hello";
String s3 = new String("hello");
System.out.println(s1==s2); // true
System.out.println(s1==s3); // false
System.out.println(s2==s3); // false
}
}
Only two objects are created. First object when you do :
String s1="hello";
No object is created in memory when you do :
String s2="hello";
This is because JVM String class is based on flyweight pattern so if a string already exist in memory as in your case "hello", so creating a new reference will not create a new object. Both s1 and s2 will point to the same memory location.
Second object is created when you do:
String s3 = new String("hello");
As new operator will always create a new object.
== compares whether both the references pointing to the same memory location or not. While equals compares the contents of strings. Having said that and as I mentioned both s1 and s2 are pointing to same memory location and hence both == and equals will return TRUE for their comparison. But s3 is a different object and hence comparison wiht s1 and s2 with == operation will return false. But if you do equals comparison of s1,s2 and s3, you will get TRUE.
No, imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "hello" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say
String A = "hello"
String B = "hello"
Now String B called "hello".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.
=====EDIT=====
If we are talking about how many string objects are there:
String s = "hello"; // one string object in the string pool "hello"
String s2 = "hello"; // two object variables (s, s2)
in this simple case, "abc" will go in the pool and s and s2 will refer to it.
String s3 = new String("hello"); // creates two objects, and one reference variable.
In this case, because we used the new keyword, Java will create a new String object
in a normal (nonpool) memory and s will refer to it. In addition the literal "hello"
will be placed in the pool as well (if it doesn't exist).
.equals() method matches two strings based on values (contents present) in that String and == check whether two objects points to same reference or not.
check the link below you will get your answer,
difference between == and equals method
use String.contentEquals:
"stringA".contentEquals("StringB");
Strings are objects, and whenever you create a 'new string' it actually creates a 'new String(value)' which points to a location in memory For example a "float" is a primitive/value, whereas Float is an Object with a pointer to a location in memory. When you use '==' it simply checks if the pointers are the same. "String.contentEquals" checks to see if the contents of both objects are the same.

Categories