With Java version 1.6 the output is false true
, but with version 1.8 the output changed to true true
.
Can some one explain why is this happening?
Intern method is used to refer the corresponding string constant pool of created objects in the heap, and if the object is not there then it will create a String constant pool. Please correct me if my understanding is wrong.
public class Intern_String2 {
public static void main(String[] args) {
String s1 = new String("durga"); //object created in heap
String s2 = s1.concat("software");
//object durga software created in heap at runtime
String s3 = s2.intern();
// create durga software object in string constant pool as none exist.
System.out.println(s2==s3);//should be false but print true in 1.8 version.
String s4 = "durgasoftware";
System.out.println(s3==s4);//prints true in both version..
}
}
No, typically you can not "destroy reference from String pool in Java" manually. The main reason I suppose why you are targeting it is to avoid out of memory errors. In Java 6 days all interned strings were stored in the PermGen – the fixed size part of heap mainly used for storing loaded classes and string pool.
26) In which memory a String is stored, when we create a string using new operator? Explanation: When a String is created using a new operator, it always created in the heap memory.
String pool is a storage space in the Java heap memory where string literals are stored. It is also known as String Constant Pool or String Intern Pool. It is privately maintained by the Java String class. By default, the String pool is empty.
A string constant pool is a separate place in the heap memory where the values of all the strings which are defined in the program are stored. When we declare a string, an object of type String is created in the stack, while an instance with the value of the string is created in the heap.
String.intern()
returns the canonical instance of String. But it does allow that the String you passed to intern()
(e.g. the call receiver / object you call the method on) is returned -- this may happen if String is not in the internal table yet -- that is the canonical instance now. In the same way, if that String was already in the internal String table, intern()
would return it.
String s2 = "web".concat("sarvar");
String s3 = s2.intern();
System.out.println(s2 == s3); // prints "true"
String s4 = "web".concat("sarvar");
String s5 = s4.intern();
System.out.println(s4 == s5); // prints "false"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With