-6

Below code represents the same operation but results getting differes ? can any one tell me how the java executs the == operation ?

          String str = new String("Hello");
          String str1 = new String("Hello");
          System.out.println(str == str1);

o/p False

          String str = "Hello";
          String str1 = "Hello";
          System.out.println(str == str1);

o/p True

Loga Saravanan
  • 39
  • 1
  • 1
  • 5
  • 3
    One quick advice: Always search for a question before posting a new one. This is has been asked a lot of times earlier. – Juned Ahsan May 19 '15 at 06:39
  • [Possible duplicate of How do I compare strings in Java?](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – MadProgrammer May 19 '15 at 06:42

1 Answers1

1

The One line answer for the below statement ,

String str = "Hello";
String str1 = "Hello";
str == str1

Both points to the same string literal in the String pool.

And here ,

      String str = new String("Hello");
      String str1 = new String("Hello");

You are explicitily asking String pool to create a new instance of literal "Hello"

Santhosh
  • 8,181
  • 4
  • 29
  • 56