Saturday, July 6, 2013

String (String Pool,Immutable,Other Concepts,String vs StringBuffer vs StringBuilder)


What is String literal pool:

There are two ways to create a String object in Java:
  • Using the new operator. For example,
    String str = new String("Hello");.
  • Using a string literal or constant expression). For example,
    String str="Hello"; (string literal) or
    String str="Hel" + "lo"; (string constant expression).            
     The creation of two strings with the same sequence of letters without the use of the new keyword will create pointers to the same String in the Java String literal pool. The String literal pool is a way Java conserves resources. 
    If we use the new keyword then String will not be placed in the String pool but then we can use String's intern() method to place that object in the String pool.
    Unfortunately, when you use
    String a=new String("Hello");
    a String object is created out of the String literal pool, even if an equal string already exists in the pool.
    Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption. For example
    public class Program
    {
        public static void main(String[] args)
        {
           String str1 = "Hello";  
           String str2 = "Hello"; 
           System.out.print(str1 == str2);
        }
    }
    The result is
    true
     
    There is a table always maintaining a single reference 
    to each unique String object in the global string literal pool  ever 
    created by an instance of the runtime in order to optimize space.  That 
    means that they always have a reference to String objects in string 
    literal pool, therefore,  the string objects in the string literal pool 
    not eligible for garbage collection.
     
     
    Why String is Immutable or Final in JAVA:
    
     Security,Thread safety and String pool being primary reason of making String immutable,And for making immutable you need to make a class final also.
    1) Imagine StringPool facility without making string immutable , its not possible at all because in case of string pool one string object/literal e.g. "Test" has referenced by many reference variables , so if any one of them change the value others will be automatically gets affected i.e. lets say

    String A = "Test"
    String B = "Test"

    Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A will also be "TEST" which is not desirable.

    2)String has been widely used as parameter for many Java classes e.g. for opening network connection, you can pass hostname and port number as string , you can pass database URL as string for opening database connection, you can open any file in Java by passing name of file as argument to File I/O classes.

    In case, if String is not immutable, this would lead serious security threat , I mean some one can access to any file for which he has authorization, and then can change the file name either deliberately or accidentally and gain access of those file. Because of immutability, you don't need to worry about those kind of threats. This reason also gel with, Why String is final in Java, by making java.lang.String final, Java designer ensured that no one overrides any behavior of String class.

    3)Since String is immutable it can safely shared between many threads ,which is very important for multithreaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally. Another important point to note about String is memory leak caused by SubString, which is not a thread related issues but something to be aware of.

    4) Another reason of Why String is immutable in Java is to allow String to cache its hashcode , being immutable String in Java caches its hashcode, and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java.  This one is also suggested by  Jaroslav Sedlacek in comments below. In short because String is immutable, no one can change its contents once created which guarantees hashCode of String to be same on multiple invocation.

    5) Another good reason of Why String is immutable in Java suggested by Dan Bergh Johnsson on comments is: The absolutely most important reason that String is immutable is that it is used by the class loading mechanism, and thus have profound and fundamental security aspects. Had String been mutable, a request to load "java.io.Writer" could have been changed to load "mil.vogoon.DiskErasingWriter"

    Java String interview Question

    1) What is String in Java ? Is String is data type?
    String in Java is not a primitive data type like int, long or double.  String is a class or in more simple term a user defined type. String is defined in java.lang package and wrappers its content in a character array.
    2) Why String is final in Java
    String is final by design in Java, some of the points which makes sense why String is final is Security, optimization and to maintain pool of String in Java.
    3) What is Difference between String and StringBuffer in Java
    Though String and Stringbuffer are two different class they are used in context of concatenating two Strings, Since String is immutable in Java every operation which changes String produces new String, which can be avoided by using Stringbuffer.
    4) What is difference in String on C and Java
    Well C String and Java String are completely different to each other, C String is a null terminated character array while String in Java is an Object
    5) Why char array is better than String for storing password?
    This String interview question is debatable and you might not agree with interviewer but this is also a chance to show that how deep and differently you can think of. One of the reason which people give Why you should store password in char array over String is related to immutability, since its not possible to remove erase contents of String but you can erase contents of char array. See Why char array preferred over String for password for complete discussion.
    6) How do you compare two String in Java ?
    There are multiple ways to compare two String like equals() method, equalsIgnoreCase() etc.Main thing which interviewer checks is that whether candidate mentioned equality operator or not "==", comparing String with equality operator is common mistake.
    7) Can we compare String using == operator? What is risk?
    Equality operator is used to compare primitives and equals() method should be used to compare objects. As we have seen in pitfall of autoboxing in Java that how equality operator can cause subtle issue while comparing primitive to Object, any way String is free from that issue because it doesn't have corresponding primitive type and not participate in autoboxing.In short always use equals method in Java to check equality of two String object.
    8) How substring method work in Java
    Substring shares same character array as original String which can create memory leak if original String is quite big and not required to retain in memory but unintentionally retained by substring which is very small in size and prevents large array from begin claimed during Garbage collection in Java. See How Substring works in Java for more details.
    10)What is String pool in Java
    Another tough Java question asked in  String interview. String pool is a special storage area in Java heap, mostly located on PerGen space, to store String literals like "abc". When Java program creates a new String using String literal, JVM checks for that String in pool and if String literal is already present in pool than same object is returned instead of creating a whole new object. String pool check is only performed when you create String as literal, if you create String using new() operator, a new String object will be created even if String with same content is available in pool.
    9) What does intern() method do in Java
    String object crated by new() operator is by default not added in String pool as opposed to String literal. intern() method allows to put an String object into pool.
    11) Does String is thread-safe in Java
    Since String is immutable, it is thread-safe and it can be shared between multiple thread without external synchronization.

     String vs StringBuffer vs StringBuilder:
    Many Java beginners not aware that String is immutable and final in Java and every modification in String result creates a new String object. So How do you manipulate String in Java without creating String garbage? StringBuilder and StringBuffer is answer of this question. StringBuffer is old class but StringBuilder is newly added in Java 5 along with major improvements like Enum, Generics, varargs methods and Autoboxing in Java.


    Differences between String, StringBuffer and StringBuilder in Java

    String in Java

    Before looking difference between String and StringBuffer or StringBuilder let’s see some fundamental properties of String Class in Java

    1) String is immutable in Java:  String is by design immutable in Java.Immutability offers lot of benefit to the String class e.g. his hashcode value can be cached which makes it a faster hashmap key and one of the reason why String is a popular key in HashMap. Because String is final it can be safely shared between multiple threads  without any extra synchronization.

    2) "+" operator is overloaded for String and used to concatenated two string. Internally "+" operation is implemented using either StringBuffer or StringBuilder.

    3) Strings are backed up by character Array and represented in UTF-16 format. By the way this behavior can cause memory leak in String because same character array is shared between source String and SubString which can prevent source String from being garbage collected.

    4) String class overrides equals() and hashcode() method and two Strings are considered to be equal if they contain exactly same character in same order and in same case. If you want ignore case comparison of two strings consider using equalsIgnoreCase() method. Another worth noting point is that equals method must be consistent with compareTo() method for String because SortedSet and SortedMap e.g. TreeMap uses compareTo method to compare String in Java.

    5) toString() method provides String representation of any object and its declared in Object class and its recommended for other class to implement this and provide String representation.

    6) In Java you can create String from char array, byte array, another string, from StringBuffer or from StringBuilder. Java String class provides constructor for all of these.

    Differences between String and StringBuffer in Java

    Main difference between String and StringBuffer is String is immutable while StringBuffer is mutable means you can modify a StringBuffer object once you created it without creating any new object. This mutable property makes StringBuffer an ideal choice for dealing with Strings in Java. You can convert a StringBuffer into String by its toString() method.

    Difference between StringBuilder and StringBuffer in Java

    StringBuffer is very good with mutable String but it has one disadvantage all its public methods are synchronized which makes it thread-safe but same time slow. In JDK 5 they provided similar class called StringBuilder in Java which is a copy of StringBuffer but without synchronization. Try to use StringBuilder whenever possible it performs better in most of cases than StringBuffer class. You can also use "+" for concatenating two string because "+" operation is internal implemented using either StringBuffer or StringBuilder in Java.

No comments:

Post a Comment