Core java interview questions on String Handling



1.What is the meaning of immutable in terms of string?
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.

2.Why string objects are immutable in java?
Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "sachin".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

3.How many ways we can create the string object?

4.Why java uses the concept of string literal?
To make Java more memory efficient (because no new objects are created if it exists already in string constant pool).

5.What is basic difference between Stringbuffer and StringBuilder?
StringBuffer
StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.StringBuffer is less efficient than StringBuilder.
StringBuilder
StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.StringBuilder is more efficient than StringBuffer.

6.What is basic difference between String and StringBuffer object?
String
String class is immutable.
String is slow and consumes more memory when you concat too many strings because every time it creates new instance.
String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method.
StringBuffer
StringBuffer class is mutable.
StringBuffer is fast and consumes less memory when you cancat strings.
StringBuffer class doesn't override the equals() method of Object class.

7.How can we create immutable class in java?
There are many immutable classes like String, Boolean, Byte, Short, Integer, Long, Float, Double etc. In short, all the wrapper classes and String class is immutable. We can also create immutable class by creating final class that have final data members



Related Post

Comments


©candidjava.com