Java - Things to know before your OCJP Exam - String

1. .equals() compares the content of the object whereas == compares to see if the references are holding the same object.

       String str1 = new String("Hello");
      String str2 = new String("Hello");
      System.out.println(str1 == str2); // displays false

      System.out.println(str1.equals(str2)); // displays true

2. Java maintains a String Pool for reusing String objects. If we try to create a String object using String literal or using intern() method of String, Java first look for the match in String Pool. If a match is found , reference for the existing object in Pool is returned. 

       String str1 = "Hello";
       String str2 = "Hello";
       String str3 = new String("Hello").intern();
       System.out.println(str1 == str2); // displays true
       System.out.println(str1 == str3); // displays true  

3. String objects are immutable. Once an object is created, its value cannot be changed. concat() method concatenates the string but then stores the string as a new object.    

        String str1 = "Hello";

        System.out.println(str1 == str1.concat("World")); // displays false

4. StringBuffer and StringBuilder object are mutable

5. StringBuffer is thread safe whereas StringBuilder is not.

6. Literals with double quotes are String Literals. 

      String str1 = "Hello";
      StringBuffer str2 = "World"; // compile time error - Type Mismatch: cannot convert from String to StringBuffer.

7. Modifying String objects is not cost effective. Whenever we attempt to modify String objects , it actually creates a new object and assign the reference to the new object and hence making the earlier object eligible for garbage collection.

      String str1 = "Hello";
      str1 = str1.concat("World"); // object created on previous line with value "Hello" is now eligible for garbage collection.

8. Comparing non homogeneous objects using equals always returns false irrespective of their content.

      String str1 = "Hello";
      StringBuffer str2 = new StringBuffer(str1);

9. .equals method matches the content of String , StringBuffer and StringBuilder because equals method has been overridden in these classes.

10.  String literals gets sorted when added to some collections because it implements comparable interface and hence it defines the compareTo method. StringBuffer does not implement Comparable interface.

11. String is a final class i.e it cannot be subclassed. StringBuffer and StringBuilder are not final classes.

12. String and StringBuilder class implements serializable, comparable and charSequence. StringBuffer only implements serializable.