String


  • String is nothing but a sequence of characters that holds in a single variable.

           Eg:      String s="onlyviewz";

  • String is not a primitive datatype ,even though you are using along with other primitive types like (int ,char...) but strings in java are the instances of the java.lang.String class.
StringBuffer
  • StringBuffer is a mutable class
  • StringBuffer can be changed dynamically
  • StringBuffer is preferred when heavy modification of characters in string like the following
      append(), insert(), reverse(), charAt(), delete(), capacity()  etc......

Example on StringBuffer and String

       String str=new String("only");
       str +="viewz!!!";

       StringBuffer str=new StringBuffer("only");
       str.append("viewz");

mutable and immutable:

  • mutable means we can alter the data
  • immutable means we can not alter the data it will fix forever
  • immutable objects are automatically thread-safe.
  • String is a mutable 
  • StringBuffer is a immutable
Note :
if we want to pass sensitive information,with out worrying of altering the data in the  middle use immutable object

Example on mutable

 public class Mutableclass{
   private int a;
    public Mutableclass(int a){
              this.a=a;
    }
     //  setter and getter methods
 }

Example on immutable  

public class Immutableclass{
      private final int a;
      public Immutableclass(final int a){
          //this value is fix forever
           this.a=a;
      }    
    //setter and getter methods
}

Note :
char[] is better than String to store password,we can change the content in char[] but not in String

No comments:

Post a Comment