1
public class Test {
    public static void main(String[] args) {
        final String fName = "James";
        String lName = "Gosling";
        String name1 = fName + lName;
        String name2 = fName + "Gosling";
        String name3 = "James" + "Gosling";
        System.out.println(name1 == name2);
        System.out.println(name2 == name3);
    }
}

output:

false 
true

Can anyone if possible please explain this output with reason?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • Probably you won't see the answer to your question directly in the linked answer. Anyway, the point of your code is that `fName` is `final` whend `lName` is not. That means the compiler cannot internal the String reference from `lName`. – PeterMmm Feb 12 '22 at 09:22
  • Yes, this was clearly NOT a duplicate of the "How do I compare strings in Java" question. I've reopened it, so that @PeterMmm can turn his comment into an answer if he so wishes. PeterMmm, if you don't write an answer, I will, because this is actually an interesting question. – Dawood ibn Kareem Feb 12 '22 at 22:48
  • 3
    It isn't a dupe of #513832, but it is an exact dupe of https://stackoverflow.com/questions/47959691/difference-between-string-and-final-string and nearly of https://stackoverflow.com/questions/19418427/comparing-strings-with-which-are-declared-final-in-java @DawoodibnKareem – dave_thompson_085 Feb 13 '22 at 00:01
  • Perfect! The OP should be satisfied with the answers to those questions. – Dawood ibn Kareem Feb 13 '22 at 06:38

0 Answers0