Sol: String str = new String(“codersarts”);
if this lieral values stored in string pool then then only 1 str string created in the String pool, if not then first its created in the String pool after that in heap space so total of 2 strings object will be createdSol: Because Due to string Imuutability Jvm save lots of memory in heap area how? its refers different String variable to the same literal in the pool. If string is not immutable then it will be a problem for an application like if we are connecting through database and provide user and password if string is mutable then anyone can stole the data. String is immutable thats whw we are able to use intern method otherwirse it can’t be achieved.String also used in Java class loader and immutability provides security so that class Loader loads the correct class.
Sol: Actually its not a method of String class its a method of object class and this method is override from the Object class in String class.
Sol: First you should ask which equals method you are asking from Object class equals method or from String class equals method because both of them are works differently. String class equals method compare contents of 2 object if its same then return true or else return false.
And, == operator comapare 2 object on behalf of reference if both objects have same refernce then it returns true or else return false.
Now talking about equals() method of Object class. Its similar to == operator.
Sol: Whenever String class object is created then its data goes into 1 final character array which is blank final and we know that blank final data is intialize only once so once value is assigned to it then it can’t be changed.
Sol:
Here interviewer trying to confuse you that you said string is immutable once it assigne can’t change but here is concatenating is happening here so you should say here 1 reference is created for “hi” and after that 2 refernce is created for “hello” and finally 3 refernce is created for “hihello” so initially s is pointing to 1 after that its pointing to 3 reference location.
Sol: Concat method is applicable for only concating string type data. But using “+” operator you can use any kind of data to concat the string.
Internally how “+” works:
Sol: codersarts
Sol:
First its add 2+2+2 when + operator gets String type then after that it consider everything string.
Sol: Some rules to create Immutable class:
Sol:
honda
123