1. We can store string in two different spaces.
    • String Pool for String Literal :
      It is special storage in Java Heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference. Below both strings are same and pointing to the same object in String Pool: You can used relational equality operator ‘==’ to compare references of two strings in above case. String is immutable, it is not efficient to use String if you need to modify your String frequently (that would create many new Strings occupying new storage areas).
    • Heap Space for String Object :
      Every String object in the heap has its own storage like any other object. There is no sharing of storage in a heap even if two String objects have the same contents. We have to use equals method to compare string. It is uncommon and not recommended to use the new operator to construct a String object in the heap.
  2. We can cache hashcode of string. As string is immutable and value of string in pool is not going to change. Same logic applies to hashmap, as hashmap doesn’t require to calculate it’s key hashcode every time.
  3. Strings are implicitly thread safe. Since String is immutable we do not require to synchronize objects if it is shared between multiple threads.
  4. String prevents security threats. Strings are used in many applications i.e. database connection, file opening, network connections etc. If string is not immutable, someone can change the value of String and change the host URL and password and gain access to the system. As java.lang.String is final no one can override String Class.
  5. String are useful in loading classes. For example if you are trying to load java.sql.Connection using driver of oracle and someone change its value to mysql driver which can do unwanted things.
It's good to share...Share on FacebookTweet about this on TwitterShare on LinkedInPin on PinterestShare on Google+Email this to someone

Leave a Reply

Your email address will not be published. Required fields are marked *