Core Java String interview questions and answers
1. What is immutable String Object?
This is one of the important questions and often asked in interview. Question may not be same, it may vary as what is the immutability of String, why String object is immutable, what really immutability means in terms of String object, what is String constant pool and String immutability etc.
You can find detailed answer of above questions here in article where immutability of String is explained in detail.
2. Is String class final and why?
Yes String class is marked as final, as we know from above answer that we need to maintain the immutability of the String for achieving String Constant Pool and memory efficiency. But if someone overrides the String class functionality then String value can be changed. To avoid overriding of the String Object String classes are made final.
3. What is the difference between creating a String object using new and using literal?
Java offers two ways of creating the String object, i.e.
String test = “test”; String test = new String(“test”);
But what is the difference between these two??
Lets look at both the cases one by one :
String test = “test”;
This creates one String literal object and store it in String Constant Pool and test refers to it.
String test = new String(“test”);
In above case there are two objects created, one is with new String which is stored in non constant pool memory and test refers to it. “test” literal object also gets created and stored in String Constant Pool.
4. What is the difference between StringBuffer and StringBuilder in java?
a. StringBuffer is thread safe but StringBuilder is not thread safe.
b. As StringBuilder do not use the synchronised methods, StringBuilder is more faster than StringBuffer.
Or question may be like this,
What is the difference between String and StringBuffer/StringBuilder in java?
As we all know String objects are immutable, but StringBuffer and StringBuilder values can be changed.
StringBuffer/StringBuilder methods act on invoking object and unlike String object, objects can changed without an explicit assignment.
StringBuffer/StringBuilder equals() method is not overridden. Unlike String object it doesn’t used for comparing values.
For more detailed explanation about What is the difference between String, StringBuffer and StringBuilder click here.
5. Which way you choose to compare two String variables - the operator == or the equals() method?
If we want to check values then appropriate option will be to use is equals() method but if you want to check if the two variables point to the same instance of the String object then you can opt for == operator.
Hope you like this post, if you have more questions or answers to share then your comments are most welcome.