How many String objects using new operator [duplicate] - java

This question already has answers here:
Questions about Java's String pool [duplicate]
(7 answers)
Closed 5 years ago.
When we use new operator to create a String object, I read that two Objects are created one Object is string constant pool and second one is in heap memory.
My question here is We are using new operator hence only one object should be created in Heap. Why then one more object has to be created in String Constant pool. I know Java stores String object whenever we not use new operator to create a String. For eg:
String s = "abc" .
In this case only it will create in String constant pool.
String s2 = new String("abc")
only one object hast to be created in heap and not in Constant pool.
Please explain why I am wrong here.

We are using new operator hence only one object should be created in Heap.
Sure - the new operation only creates one object. But its parameter is a String literal, which already represents an object. Any time you use a String literal, an object was created for that during class loading (unless the same literal was already used elsewhere). This isn't skipped just because you then use the object as a parameter for a new String() operation.
And because of that, the new String() operation is unnecessary most of the time and rarely used.

See http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28
Compile-time constant expressions of type String are always "interned" so as to share unique instances, using the method String.intern
Thus when you write
String s2 = new String("abc")
The Compile-time constant expression "abc" will be interend.

It will be created two object, one object into pool area and other one in non pool area because you are using new and as well as string literal as a parameter.
String s = new String("abs");

String s2 = new String("abc")
It will create only one object in heap memory. We need to use intern() method of java.lang.String explicitly to make the entry in String pool.
String s = "def".
Two Objects will be created here. When you create using String literal notation of Java, it automatically call intern() method to put that object into String pool, provided it was not present in the pool already.

String in java is Immutable, once created its cannot be changed. also, any string literal will be stored in the string pool for later use whenever the same literal is used again, for example:
String name = "my name"; // one intern object is created in pool
String otherName = "my name"; // the old intern object is reused
System.out.println( name == otherName); // true , the same reference refer to same object
the two reference refer to the same location in the pool.
String name = new String("my name"); // one object is created, no string pool checking
String otherName = new String("my name"); // other object is created, no string pool checking
System.out.println( name == otherName); // false, we have 2 different object
here we have two different String object in memory each of them have its own value.
see this article for more:
http://www.javaranch.com/journal/200409/Journal200409.jsp#a1

form this below line of code will create 3 object in the JVM
String s2 = new String("abc")
for "abc" in String pool memory.
for new operator one object in heap.
one more for s2.

String s2 = new String("abc");
here 1 literal and 1 object will be created.
With new operator 1 String object will be created in heap as "abc" and s2 will refer it, moreover "abc" is string literal also that is passed in String Constructor so it will go in String Constant pool.
literal is consider as object so 2 object will be created here.

Related

If declared string using new keyword and same string be assigned another value using assignment operator what will happen in java

String newString=new String("JAVA");
newString="JAVA8";
WHAT will happen here if we print newString we know output will be JAVA8 only but 2nd line created new object in heap or constant pool.
How its behave internally
In Java Strings are immutable.
What that means is that once a String object is created it cannot be updated.
Also Java has something called Java String Pool, a memory location where Java stores Strings.
To minimize the memory space used by this String Pool, Java performs Interning when a new String literal is create using the following statement.
String s = "apple";
What Interning means is that JVM looks in the String Pool to see if the string literal "apple" exists, if it does it just passes its reference to new variable, no new object is created, if it does not exist it creates a new object passes its reference and also can pass the same reference if another string is created with same value. For Example:
String t= "apple";
If you check if the both strings created above are reference to the same string literal in string pool, you can do that as follows:
System.out.println(s == t); // True
When a string is created using new keyword it always creates a new Object in the String pool, even if the string literal exists in the string pool.
String u = new String("apple");
You can check that the new object is created by following statement:
System.out.println(s == u); // False
System.out.println(t == u); // False
In yoru case the first statement created a new object in String pool and passed its reference. The second line created another object and passed its reference. The first object is still in String pool but not being referenced by any variable and eventually the memory occupied by it will be released by Garbage collection.
Hope this answers your question, you can read about Java String pool to know more.
First, newString is not a String!!!
newString is a reference to an instance of the class String! A C programmer would name it pointer and write String* newString.
With
String newString = new String( "JAVA" );
you declare the variable newString of type "reference to String" and assign the reference to (the address for) the new object, created by a call to the constructor of the class java.lang.String from the compile time constant "JAVA".
newString = "JAVA8";
now assigns the reference to the compile time constant "JAVA8" to that previously created variable. At the same time, the previously reference object gets abandoned (no more references to that object were hold) and therefore it is now ready to be garbage collected.
Most Java implementations do store the compile time constants not on the heap, and strings are usually stored in the string pool. Also it is possible that the call to new String() will never be executed; instead the compiler will directly use the reference to the compile time constant. Or it will be executed and the resulting String object is stored on the Heap, with or without referencing the string value in the string pool.
The details can be found in the Java Language Specification and the JVM Specification for the respective version, and if that says "implementation dependent", in the documentation for the respective JVM/Java implementation.

Does new String() update the string pool in Java? [duplicate]

This question already has answers here:
Questions about Java's String pool [duplicate]
(7 answers)
Closed last month.
If I write something like this:
String s1 = new String("ABC");
String s2 = "ABC";
In which scenarios does the string pool get updated? The first, second or both?
In the above programming code ,when string pool get updated?
The first statement will update/add to the String pool with "ABC" String literal, but create another object in the heap and the variable s1 will refer the heap object.
The second statement will refer the already created Pool String object.
String s = new String("ABC");
this always create a new String object on the heap and add "ABC" to the pool(if not present).
String s= "ABC";
Whereas this line is called string literal. It checks whether the string pool already has the same string "ABC" or not. If present then s will refer to that object otherwise a new object will be created.
Conclusion: new String() will always create a new object and string literal checks the string pool before creating one.
String s1=new String("ABC");//creates two objects and one reference variable
In your case, JVM will create a new String object in normal(nonpool) Heap memory and the literal "ABC" will be placed in the string constant pool.The variable s1 will refer to the object in Heap(nonpool).
String Constant Pool
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.
Whenever you use new keyword to create String Object,it will create in Heap and then it will check the String Constant Pool for the same String Literal.If SCP doesn't contain that String literal then Only it will create String literal in the SCP.
Nope. Strings created with the constructor never enter the string pool.
In the example, two separate objects are created. Therefore:
s1 != s2

Best practice curiosity regarding String instantiation [duplicate]

This question already has answers here:
Strings are objects in Java, so why don't we use 'new' to create them?
(15 answers)
Closed 9 years ago.
I was reading some advices about best practices in java and I got the following idea which made me curious
Also whenever you want to instantiate a String object, never use its constructor but always instantiate it directly.
For example:
//slow instantiation
String slow = new String("Yet another string object");
//fast instantiation
String fast = "Yet another string object";
Why is this? doesn't the 'fast' call the default string constructor?
When you use new you get a new string object, but if you use string literal then see here:
In computer science, string interning is a method of storing only one
copy of each distinct string value, which must be immutable. Interning
strings makes some string processing tasks more time- or
space-efficient at the cost of requiring more time when the string is
created or interned. The distinct values are stored in a string intern
pool. The single copy of each string is called its 'intern' and is
typically looked up by a method of the string class, for example
String.intern() in Java. All compile-time constant strings in Java are
automatically interned using this method.
If you do:
String a = "foo";
String b = "foo";
Then a==b is true !
A String will be created only if it hasn't been interned.
An object will be created in the first time, and it'll be stored in a place called the String constant pool.
But using the new which will create a different object for each string, will output false.
String a = new String("foo");
String b = new String("foo");
Now a==b is false.
So when using literal it is easier to read, plus easier for the compiler to make optimizations. So.. use it when you can.
The JVM maintains a pool of String literals for optimizations. When you create a String using the constructor,
String s1 = new String("foo");
A new String object is created, and the literal "foo" is added to the pool. After this, anytime you use "foo" in your code, the "foo" refers to the item in the pool and a new object is not created. Since String is immutable, this does not create any problems.
So when you create a String using the "shortcut":
String s2 = "foo"
the JVM looks into the pool, if "foo" already exists there, it will make s2 refer to the item in the pool.
This is a major difference with possible performance impacts: The constructor always creates an object, and adds the literal to the pool if it is not already present there. The shortcut refers to the item in the pool and creates a new object only if the liuteral is not in the pool.

Please explain intern() method functionality [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
When should we use intern method of String?
what is string interning?
Please explain the inner workings of the following code:
System.out.println(new String("ABC").intern()==new String("ABC").intern());
In the above code it prints "true". But according java rules, in the case of the new operator, it always creates a new object. object.intern() method also creates an object in the string pool. So my question is, in the above code how many objects are created.
According to me, 3 new objects will created. One goes to String pool, and two anonymous objects will be created by the new operator. But i am not sure.
If i am wrong please explain.
Assuming no cleverness in the optimizer, two objects are created. (A smart enough optimizer could optimize this to just an unconditional true, in which case no objects are created.)
tl;dr version: You were almost right with your answer of 3, except that the string that goes into the String pool is not generated as part of this statement; it's already created.
First, let's get the "ABC" literal out of the way. It's represented in the runtime as a String object, but that lives in pergen and was created once in the whole life of the JVM. If this is the first class that uses that string literal, it was created at class load time (see JLS 12.5, which states that the String was created when the class was loaded, unless it previously existed).
So, the first new String("ABC") creates one String, which simply copies the reference (but does not create a new object) to the chars array and hash from the String that represents the "ABC" literal (which, again, is not created as part of this line). The .intern() method then looks to see whether an equal String is already in permgen. It is (it's just the String that represents the literal to begin with), so that's what that function returns. So, new String("ABC").intern() == "ABC". See JLS 3.10.5, and in particular:
Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.
The same thing exactly happens with the second occurrence of new String("ABC").intern(). And, since both intern() method return the same object as the "ABC" literal, they represent the same value.
Breaking it down a bit:
String a = new String("ABC"); // a != "ABC"
String aInterned = a.intern(); // aInterned == "ABC"
String b = new String("ABC"); // b != "ABC"
String bInterned = b.intern(); // bInterned == "ABC"
System.out.println(new String("ABC").intern()==new String("ABC").intern());
// ... is equivalent to...
System.out.println(aInterned == bInterned); // ...which is equivalent to...
System.out.println("ABC" == "ABC"); // ...which is always true.
When you call intern() method, jvm will check if the given string is there, in string pool or not. If it is there, it will return a reference to that, otherwise it will create a new string in pool and return reference to that.
In your case : System.out.println(new String("ABC").intern()==new String("ABC").intern());
The first new String("ABC").intern() will create a string "ABC" in pool.When you call new String("ABC").intern() second time, jvm will return the reference to previously created string.That is the reason you are getting true when comparing both(btn are pointing to same reference).
I believe you are right, as new operation create a new object so there are 2 anonymous objects and intern() creates a new string in the string pool only if it is not already and returns it's reference

Why new keyword not needed for String

I am new in java.
In java, String is a class.But
we do not have to use new keyword to create an object of class String where as new is used for creating objects for other classes.
I have heard about Wrapper classes like Integer,Double which are similar to this.
But String is not Wrapper,isn't it?
Actually what is happening when i use
String message = "Hai";
??
How it is different from
String message = new String("Hai");
Here is message a reference variable or something else??
Are there other classes which do not require new to create object ??
With the following line you are not creating a new String object in the heap but reusing a string literal (if already available):
String message = "Hai";
"Hai" is a string literal in the string literal pool. Since, strings are immutable, they are reusable so they are pooled in the string literal pool by the JVM. And this is the recommended way, because you are reusing it.
But, with the following you are actually creating a new object (in the heap):
String message = new String("Hai");
new String("Hai") is a new String object. In this case, even if the literal "Hai" was already in the string literal pool, a new object is created. This is not recommended because chances are that you might end with more than one String objects with the same value.
Also see this post: Questions about Java's String pool
Are there other classes which do not require new to create object ??
Actually, you can not create any object in Java without using the keyword new.
e.g.
Integer i = 1;
Does, not mean that the Integer object is created without using new. It's just not required for us to use the new keyword explicitly. But under the hood, if the Integer object with value 1 does not already exist in cache (Integer objects are cached by JVM), new keyword will be used to create it.
The Java language specification allows for representation of a string as a literal. You can consider it a shortcut initialization for a String that has one important side-effect that is different from regular initialization via new
String literals are all interned, which means that they are constant values stored by the Java runtime and can be shared across multiple classes. For example:
class MainClass (
public String test = "hello";
}
class OtherClass {
public String another = "hello";
public OtherClass() {
MainClass main = new MainClass();
System.out.println(main.test == another);
}
}
Would print out "true" since, both String instances actually point to the same object. This would not be the case if you initialize the strings via the new keyword.
String and Integer creation are different.
String s = "Test";
Here the '=' operator is overloaded for string. So is the '+' operator in "some"+"things".
Where as,
Integer i = 2;
Until Java 5.0 this is compile time error; you cant assign primitive to its wrapper. But from Java 5.0 this is called auto-boxing where primitives are auto promoted to their wrappers wherever required.
String h1 = "hi";
will be different from
String h2 = new String("hi");
The reason is that the JVM maintains a string table for all string literals. so there will be an entry in the table for "hi" , say its address is 1000.
But when you explicitly create a string object, new object will be created, say its address is 2000. Now the new object will point to the entry in the string table which is 1000.
Hence when you say
h1 == h2
it compares
1000 == 2000
So it is false
In java
"==" compares the left & right hand sides memory locations(and not the value at that memory location) and therefore in case of
new String("hai")==new String("hai")
it returns false.
In case of "Hai"=="Hai", java doesn't allocate separate memory for same string literal therefore here "==" returns true. You can always use equals method to compare values.
The reason why doesn't recommended because of memory, using new keyword and creating String object, JVM create 2 object between HEAP and SCP, but using just literal is that JVM creating only SCP. That's why we creating String object, just using literal.

Categories

Resources