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.

Case2) Now lets create two String objects and repeat the same exercise we did above.

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 offirstLanguage 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.