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