Posts

Showing posts from 2017

Difference between String and StringBuffer

Difference between String and StringBuffer There are many differences between String and StringBuffer. A list of differences between String and StringBuffer are given below: No. String StringBuffer 1) String class is immutable. StringBuffer class is mutable. 2) String is slow and consumes more memory when you concat too many strings because every time it creates new instance. StringBuffer is fast and consumes less memory when you cancat strings. 3) String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method. StringBuffer class doesn't override the equals() method of Object class. Performance Test of String and StringBuffer 1.      public   class  ConcatTest{   2.           public   static  String concatWithString()    {   3.              String t =  "Java" ;   4.               for  ( int  i= 0 ; i< 1

Difference between StringBuffer and StringBuilder

Difference between StringBuffer and StringBuilder There are many differences between StringBuffer and StringBuilder. A list of differences between StringBuffer and StringBuilder are given below: No. StringBuffer StringBuilder 1) StringBuffer is  synchronized  i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously. StringBuilder is  non-synchronized  i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously. 2) StringBuffer is  less efficient  than StringBuilder. StringBuilder is  more efficient  than StringBuffer. Example 1.      public   class  BufferTest{   2.           public   static   void  main(String[] args){   3.              StringBuffer buffer= new  StringBuffer( "hello" );   4.              buffer.append( "java" );   5.              System.out.println(buffer

StringBuilder

StringBuilder class in Java In Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder class is same as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5. Constructors of StringBuilder class Constructor Description StringBuilder() creates an empty string Builder with the initial capacity of 16. StringBuilder(String str) creates a string Builder with the specified string. StringBuilder(int length) creates an empty string Builder with the specified capacity as length. Methods of StringBuilder class Method Description public StringBuilder append(String s) is used to append the specified string with this string. The append() method is overloaded like append(char),  append(boolean), append(int), append(float), append(double) etc. public StringBuilder insert(int offset, String s) is