-2

I have two Strings:

String s = "ABC";
String s1 = new String("ABC");

In theory, If I am not wrong two objects are created in this case. I can verify that using hashcode().

public static void main(String[] args) {
        System.out.println(s.hashCode());
        System.out.println(s1.hashCode());
    }

}

Output:

2125849484
2125849484

If I am not wrong, hashcode() only help us in verifying that both the strings having similar value assigned to it "ABC", because of that hashcode value is same. What about that 2nd object which is created in heap memory? How can we verify that whether it is created or not.

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
G.Chahar
  • 185
  • 6
  • 19
  • 5
    Do you really need to know this? – Carcigenicate Apr 23 '17 at 15:07
  • @Carcigenicate, If it is possible to find out. Then, Yes! – G.Chahar Apr 23 '17 at 15:09
  • To see if two references are not the referencing the same object, use `s != s1`, which is also why you can't use `==` to compare strings, except that actually want to check for object identity of `String` objects. So, the **opposite of** [How do I compare strings in Java?](http://stackoverflow.com/q/513832/5221149). – Andreas Apr 23 '17 at 15:09
  • Are you saying you want to test if `s` and `s1` are the same object, or are you saying you want to test whether `s1` was created with a literal or a call to `new`? – Radiodef Apr 23 '17 at 15:14
  • @G.Chahar I meant that it's kind of odd to need to know whether an object was created through `new` or not. I'm wondering if this is an XY problem. – Carcigenicate Apr 23 '17 at 15:23

2 Answers2

1

You can use !=, which confirms that two variables do not reference the same object:

String first = "ABC";
String second = new String("ABC");
System.out.println(first != second); //=> true

This technique is in contrast to !first.equals(second), which checks whether two strings hold a different sequence of characters. See the post How do I compare strings in Java?

gyre
  • 16,369
  • 3
  • 37
  • 47
1

If what you want is checking for s1 and s2 being physically the same object you can use the (==) operator.

String s1 = "ABC"
String s2 = new String("ABC");
boolean b1 = s1 == s2;      //false
boolean b2 = s1.equals(s2); //true

Contrarily to the equals methods that checks for structural equality (same values).

ghilesZ
  • 1,502
  • 1
  • 18
  • 30