300x250 AD TOP

Saturday, September 20, 2014

Tagged under: , , , , ,

String, StringBuilder and StringBuffer


String
  • Strings are objects like other objects.
  • They can create instances and they can have constructors and methods.
  • String is final class, so they can't be extended and overridden.
  • Strings are immutable objects.
  • They can be assigned to String variables.
  • They can be used as parameters in methods and constructors.


Ways of create Strings
First way: String s = "apple";
  •     In this situation String object is 'apple'. 's' is the reference variable to refer 'apple'. 
  •        Created one object and one reference variable "apple" will be placed at the heap area(pool) and "s" refers it.
Second way: String s = new String ("apple");
  •         In this way it creates two objects. Because we have used new keyword.
  •     But both are not placed at the pool. "apple" will be placed at the pool while another object(new String) stay in the normal memory. 
String Literal Pool 
  •    String literal pool is a section of heap in the memory. This is pool of Strings which is maintained by JVM(Java Virtual Machine) to store Strings.
  •      Once you create a String, JVM checks it already exists in the pool.
o   If it exist, a reference to the instance in the pool returns.
o   If it not exists a new String object will be created
 Advantages of immutability 
  • It helps to reduce memory usage(Allowing identical values to be combined together and referenced from various locations in your codes)
  • It simplifies multi-threaded programming(Once you initialized, the value cannot be changed)
  • Safe to work(There is no problem with alternatives)  
  • It simplifies the design and implementation(Re-usability of a String )
Disadvantages of immutability 
  •        Less efficient (It creates a heavy garbage collection)






String
StringBuilder
StringBuffer
immutable
mutable
mutable
Synchronized
Not synchronized
Synchronized
Thread safe
Not thread safe
Thread safe
-
Faster than string buffer
Slower than string builder
Java.lang.String
java.lang.StringBuilder
java.lang.StringBuffer
Use more memory
use a memory in efficient way
use a memory in efficient way
charAt(), concat(), equalsIgnoreCase(), length(), replace(), substring(), toLowerCase(), toString(), toUpperCase(), trim()
append(),replace(), insert(), delete(), reverse()
Same methods in string builder

0 comments: