Hi
All,
Welcome
to Java-recent.,a blog explaining Java related concepts.
In
this post we will discuss about important core Java concept-
Differences between String ,String Buffer,String Builder .
Lets
see the basic info
String
:-
·
represents
sequence of characters,which cannot be modified(Immutable),If we modify
a value, a
new Object will be created.
·
As
they are immutable they can be shared across objects
Different
ways of declaring String variables are:-
String
blogName="Java-recent";
String
blogName=new
String("Java-recent");
String
Buffer:-
- implements mutable(can be modified) sequence of characters
- String buffer is thread safe(Synchronized),means at any point of time only single thread can access
- Uses append() for concatenating Strings,which is efficient than String + operator
StringBuffer
blogName=new
StringBuffer("Java-recent");
Stirng
Builder :-
- implements mutable sequence of characters
- String Builder is not thread safe
- Introduced in Java5
- String Builder is faster than String buffer as it is not Synchronized by default.
StringBuilder
blogName=new
StringBuilder("Java-recent");
After
brief overview now lets move to most important differences among them
String
|
String Buffer
|
String Builder
|
Immutable | Mutable | Mutable |
Thread safe | Thread safe | Not Thread safe |
Uses + for concatenating Strings | Uses append method | Uses append method |
Widely used as key in hashmaps | Widely used if there are lot of modifications on a String value | Widely used if there are lot of modifications on a String value |
Disadvantages
of using String :-
- As String is immutable ,modification of a String like converting to upper case,substring etc. actions will always create new objects
- String modification should be done sparingly
- Concatenating String using '+' operator is costlier than using Append method in String Buffer and String Builder.,Reason behind this is Append () will produce most optimized byte code than + operator
when
there is use of repeated Strings in a particular class its better to
use String literals,because they will be Stored in String literal
pool
Happy
Learning
Please
provide your valuable comments on this article and share it across
your network.
Contact
me @ sudheer@javarecent.com
or admin@java-recent.com
No comments:
Post a Comment