Sunday 17 March 2013

Interview Question #5 What is the difference between creating string as new () and as a literal?

This is a very common and most basic interview question asked in Java and yet programmers are not able to explain it properly.

  • When we create a String using new operator it is created in heap and not added to String pool whereas String created as literals are created in String pool itself which exist in PermGen area of heap.
  • Let us take example to understand this better -

    1. Case1)   Lets create two string literals with different names.
      String firstLanguage = "Java";
      String secondLanguage = "Java";


      Now if we say

      if(firstLanguage == secondLanguage )
      {
           System.out.println("Both references point to same String \n");
      }
      else
      {
           System.out.println("Both references point to different Strings \n");
      }


      Output : Both references point to same String

      Explaination :
      When we create firstLanguage as literal it is created and stored in String pool. Now when we try to create secondLanguage JVM know that such a string already exists in the pool and hence returns reference of the same String and hence the output shown above.

      Note : '==' operator will return true only if both references or variables point to same object. In case of String if you really need to check if content of two strings are equal you must use .equals() method.
    2. Case2) Now lets create two String objects and repeat the same exercise we did above.

      String firstLanguage = new String("Java");
      String secondLanguage = new String("Java");


      Now if we say

      if(firstLanguage == secondLanguage )
      {
           System.out.println("Both references point to same String \n");
      }
      else
      {
           System.out.println("Both references point to different Strings \n");
      }



      Output :Both references point to different Strings

      Explaination :
      When we create firstLanguage as new() it is created and stored on the heap as a String object. Similarly when we create secondLanguage as new() it is again cretaed on heap as a different String object. Now since == operator returns true only when both variables point to same object which is not the case we get false.

      Note : As mentioned above if you want to check whether contents of firstLanguage object and secondLanguage object are the same that you can use .equals() method. It will return true if content of both String objects are same.
t> UA-39527780-1 back to top