HOW JAVA HANDLES STRING OBJECTS IN MEMORY?

To make Java more memory efficient, the JVM sets aside a special area of memory called the "String constant pool." When the compiler encounters a String literal, it checks the pool to see if an identical String already exists. If a match is found, the reference to the new literal is directed to the existing String, and no new String literal object is created. (The existing String simply has an additional reference.) Now we can start to see why making String objects immutable is such a good idea. If several reference variables refer to the same String without even knowing it, it would be very bad if any of them could change the String's value.

What is the difference between
String s=”bhabani” and
String s=new String(“bhabani”)

String s = "abc"; // creates one String object and one
// reference variable

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.

No comments:

Post a Comment