0

EDIT?:

I'm writing some code to get a better understanding of the String class, specifically with the == and .equals comparators.

My program is relatively simple. I've declared 2 String literals and 1 String object, all with the same value "banana".

I understand that == is essentially testing the physical memory reference and .equals is actually checking the value contained.

So why then is my 3rd conditional statement coming true if I declared strtest4 as a new object? All the others make sense.

private static String str;   
private static String strtest;  
private static String strtest4 = new String();   


public static void main(String[] args) { 

    str = "banana";
    strtest = "banana";
    strtest4 = "banana";

    if (str == strtest) System.out.println("str and strtest point to same location in memory");
    if (str.equals(strtest)) System.out.println("str and strtest have the same value contained");

    if (str == strtest4) System.out.println("\nstr and strtest4 point to same location in memory");
    if (str.equals(strtest4)) System.out.println("str and strtest4 have the same value contained");     

}

I receive the following output when I run the program:

str and strtest point to same location in memory

str and strtest have the same value contained

str and strtest4 point to same location in memory

str and strtest4 have the same value contained

  • Additional answer that may provide more info: http://stackoverflow.com/a/9698305/1424875 – nanofarad May 07 '16 at 19:44
  • 1
    Because you're not creating a new instance with `new String()` but it's using the cached constant string "banana", therefore both `str` and `strtest4` point to the same object. – dabadaba May 07 '16 at 19:45
  • @dabadaba Thanks! I guess my next question would be, how do you create a completely separate new instance in this case? –  May 07 '16 at 19:49
  • I did use 'new'. What are you talking about –  May 07 '16 at 19:59
  • 1
    `strtest4 = "banana";` and `str = "banana";`... you didn't use `new` – dabadaba May 07 '16 at 20:02
  • @dabadaba ah ok, I see what you're talking about. I thought that issue was taking care of when I initially declared strtest4 with "private static String strtest4 = new String(); " ?? –  May 07 '16 at 20:07
  • 1
    it doesn't matter how you declared those objects initially, when assigning another value you're changing the reference they're pointing to. Try doing `new String("banana") == new String("banana")` and you'll see that's `false`. But the way you're doing it is `true` because it's like if you were doing `"banana" == "banana"` which is obviously the same object. – dabadaba May 07 '16 at 20:09
  • @dabadaba ahh, ok. It's because I declared "strtest4" as a literal within my main method, despite creating it as a new object. gotcha, thanks! –  May 07 '16 at 20:18
  • Don't confuse variables, reference values and objects. – Sotirios Delimanolis May 07 '16 at 20:19

0 Answers0