Why is this code returning "false" instead of "true":
package com.company;
public class Main {
public static void main(String[] args) {
String fullName = "Name Lastname";
String name = "Name ";
String lastName = "Lastname";
String firstNamePlusLastName = name + lastName;
System.out.println(fullName == firstNamePlusLastName);
}
}
If I remember correctly:
String firstNamePlusLastName = name + lastName;
Should create a String that points to an existing address in memory (String pool) because we already have declared a String with value: "Name Lastname", shouldn't it be automatically interned into String pool and shouldn't the output be "true" since we already have string with same value in String pool as String firstNamePlusLastname ?
EDIT:
I know I should use .equals() method when testing two strings for equality of content, but I don't want to do that in the example above, I actually do want to test for reference equality, and based on Java interning the two strings that I compare in the code above should be equal, but they are not, they should point to the same address in memory as they have same content and neither of the Strings was created using "new" keyword. I want to know why is this happening.