Register now or log in to join your professional community.
Difference between String and String Builder
A sequence of characters(string) can be repersneted by three classes in java.They are
1.String
2.StringBuilder
3.StringBuffer
Here according to your questions,String vs StringBulider is that below:
String:
1.Using String class we can instantiate string by two ways
String Car="Ford";
or
String Car=new String("Ford");
2.String class values are immutable(i.e. values can't be modified).So it is easy to share across functions.
when a string is created with double quotes(String Car="Ford"; ) it look for the String with same values in the JVM String pool,if it is found ,it returns the reference of that values or else it creates a new string pool and return that refenrence.
when a string is created with new keyword( String Car=new String("Ford");) it creates a new string in the heap memory explicitly.so this causes memory wastage.
3. + operator is used to concatenate two strings(but internally uses the StringBuilder class).
4.String overrides .equals() ,.hashcode() and .equalsIgnoreCase()
StringBuilder:
String is immutable,when ever we do string manipulation it creates a new String and unused Strings are go for garbage collection ,that leads to lot of garbage in the heap.to overcome this java provided StringBuffer(in java 1.4)and Stringbuilder class(in java 1.5).
1.StringBuilder is immutable.
2.memory waste does not happen when we try to modify the string
3.append(),insert(),delete() and substring() methods are used for string manipulation.
example:StringBuilder str=new StringBuilder("Do");
The above statement creates StringBuilder object "Do" in reference str,
when we try to append another object for the same reference it will append in to reference str,it will not create a new reference in heap memory this avoid lot of garbage in heap memory.
4.StringBuilder class is not thread safe,can use in single threaded environment,if you are working in mulit thread environment with thread safety use StringBuffer class.