String class
Java String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on the same reference. A java.lang.String class is final which implies no class and extend it. The java.lang.String class differs from other classes, one difference being that the String objects can be used with the += and + operators for concatenation.
What is String Pool?
A JVM has the Pool. All the String Object which are created by assignment stored in the pool. This pool is present in the heap. So whenever any assignment is done for String first it check in the String Pool whether that String is already exist or not... This is done by calling intern() method present in the String class. If it find the same String then it return the same reference else it create new 1. But with new Operator everytime it creates the new Object.
eg.
String str "Sample" // first check wheather its present in the pool
String str1 "Sample"
So now str and str1 have the same reference so .equals and method will return true.
String str2 new String("sample");// this will create the new object in heap.
So above only 2 objects are created1 by str and other by str2
No comments:
Post a Comment