What is the immutable object? What is the difference between creating
String as new () and literal? What is
difference between Strings
vs. StringBuffer vs. StringBuilder in
Java?
Immutable object:
Immutable
classes are Java classes whose objects cannot be modified once created. Any
modification in Immutable object results in a new object. For example, is String is immutable in Java. Mostly Immutable
are also final in Java, in order to prevent sub class from overriding
methods in Java which can compromise Immutability. You can achieve the same
functionality by making member as non-final but private and not
modifying them except in constructor.
Difference between
creating String as new() and literal:
·
String
with new() Operator, it’s created in heap and not added
into string pool.
·
String created
using literal are created in String pool itself which
exists in PermGen area of heap.
String s = new
String("Test");
·
Does not put
the object in String pool, we need to call String.intern() method
which is used to put them into the String pool explicitly.
·
It’s
only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.
Difference
between Strings vs.
StringBuffer vs. StringBuilder in Java:
·
String
is immutable whereas StringBuffer and StringBuilder are mutable classes.
·
StringBuffer
is thread-safe and synchronized whereas StringBuilder is not, that’s why StringBuilder is faster than StringBuffer.
·
String
concat + operator internally uses StringBuffer or StringBuilder class.
·
For
String manipulations in a non-multi threaded environment, we should use
StringBuilder else use StringBuffer class.
No comments:
Post a Comment