Friday, September 16, 2016

String StringBuffer StringBuilder

  1. String is Java class backed by char array
  2. String in immutable (you can’t change the object itself but can change the reference of the object) since String objects are cache in String pool. String used to open JDBC and for opening file, so security can become a thread if class in not immutable
  3. String is final so no one can override the class
  4. String overrides equals() and hashCode() methods, two Strings are equal only if they have same characters in same order. Note that equals() method is case sensitive, so if you are not looking for case sensitive checks, you should use equalsIgnoreCase() method.
  5. We can create string in 2 ways
·         By using new : A new object is created
String B2= “Hi”; --O1
String A1=new String(“Hi”); -- O2
·         By using String literal “”- checks for similar String literal and if found same reference
String A2= “Hi”; -- Obj1
String B2= “Hi”; same object
String A1=new String(“Hi”); -- Obj2
String B1=new String(“Hi”); -- Obj2

  1. Immutable: When we modify a string a new object is created along with the existing one and the reference to the modified is changed. A,BàObj1 ..after modification Aà Obj1 Bà Obj2
String A="Hi";
            String B ="Hi";
            if(A.equals(B)){ -- True
                  System.out.println("A=B");
            }
B=B.toUpperCase();
                  if(A.equals(B)){ -- False
                        System.out.println("2 A=B");
                  }else{
                        System.out.println("2 A!=B");}
  1. Since immutable it is thread-safe
  2. Allows hashcode to be stored in cache so it is fast
  3. String maintained in String pool more specifically in PermGen Space
  4. .equals and == à == refers to references
String personalLoan = new String("loans");
      String homeLoan = new String("loans");
                 
      //since two strings are different object result should be false
            boolean result = personalLoan == homeLoan; -- False
           //since strings contains same conten , equals() should return true
      result = personalLoan.equals(homeLoan);
                 
homeLoan = personalLoan;
//since both homeLoan and personalLoand reference variable are pointing to same object
      //"==" should return true
      result = (personalLoan == homeLoan);
  1. Important methods indexOf(); lastIndexOf(); matches(String regex)
  2. Substring method: can create memory leaks. Backed by array of char. if beginIndex is equal to length in substring or beginindex = endindex null string will be returned.
    How substring works: it internally calls String (int offset, int count, char value [])
    constructor to create new String object. In this char value[] is the original string. So if the original string is very long the new string will be equally long. Also, this will stop original string from being garbage collected, in case it does not have live references. Thus creating memory leaks where memory is retained even though it is not required.
Solution: Simple solution is to trim the string, and keep size of character array according to length of substring. Or to use intern() method on substring since it is an original string it will occupy only the required space. Intern() has to be called on substring and not original string
String str="hello hi how are you";
            String subStr=new String(str.substring(0,3));
Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created string is a copy of the argument string.

subStr.intern();
  1. + can be used to concat strings. Internally it uses StringBuffer or StringBuilder which are mutable thus are temporary.
  2. trim(): trims the leading and trailing spaces in a string. If removes white spaces then a new string is returned else same string is returned. Inside trim(), if no trailing and leading whitespaces then this else substring method is called which in turn returns a new string.
String str1=new String(" hello hi how are you");
      String str2=new String("hello");
      String trim1=str1.trim();
String trim2=str2.trim();
      if(trim1.equals(str1)){
            System.out.println("true");
            }else{
            System.out.println("false"); --False
            }
      if(trim2.equals(str2)){
            System.out.println("true"); --True
            }else{
            System.out.println("false");
  1. split() can be used to split a string based on delimiter.
String str1=new String(" hello hi how are you");
String[] splitString=str1.split(" ");
String[] splitString=str.split(“\\|”);
  1. don’t store sensitive information in String since String is immutable and is stored in string pool(memory), it stays on heap for a long time and exposes risk of being seen by anyone who has access to Java memory like reading from dump. Instead char[] should be used to store password or sensitive information.
  2. Encoding is important in java specially if u use languages like German or French.  String represents a string in the UTF-16 format.

String Builder and String Buffer
1.      If string is created with String literal, it remains in String Pool. Since String is immutable, it remains in string pool and any method on string creates new String.

2.      StringBuffer is mutable i.e. you can modify a string buffer without creating a new object.


3.      String Builder is copy of String Buffer except, String Buffer methods are synchronized and hence is thread-safe which make is slow at the same time.

4.      Use String if you require immutability, use StringBuffer in java if you need mutable + thread-safety and use StringBuilder in Java if you require mutable + without thread-safety.

No comments:

Post a Comment