-1

When we do

  String a=new String("mac");
String b=new String("mac");

if(b == a)
{
    System.out.println("condition 1 is true");
}
if(b.equals(a))
{
    System.out.println("condition 2 is true");
}

condition 1 fails and condition 2 is true since b and a are two different objects

But when we do

String a="mac";
String b="mac";

    if(b == a)
    {
        System.out.println("condition 1 is true");
    }
    if(b.equals(a))
    {
        System.out.println("condition 2 is true");
    }

Both the conditions are true. Why didn't java create a new object for second case. If java creates a new object only when we use new() then if we give different values to both the strings then what happens internally in java?

Maclean Pinto
  • 1,075
  • 2
  • 17
  • 39
  • Related: http://stackoverflow.com/questions/2009228/strings-are-objects-in-java-so-why-dont-we-use-new-to-create-them and http://stackoverflow.com/questions/3801343/what-is-string-pool-in-java – Jason C Apr 23 '14 at 05:32
  • How many duplicates ... let me count them ... – Brian Roach Apr 23 '14 at 05:33

1 Answers1

2

When you declare like below, Java create String literals in the String constant pool, and both references a and b will refer that String object "mac" in the pool

String a="mac";
String b="mac";

So, both == and .equals() returning true.

But, when you create String object by using new operator, String objects are created in the heap like other regular objects in java.

So == operator will return false, since both references referring two different object in the heap.

Abimaran Kugathasan
  • 31,165
  • 11
  • 75
  • 105