Creating Java String

Why does this code return 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 it right:

String firstNamePlusLastName = name + lastName;

Should create a line that points to an existing address in memory (string pool), because we have already declared a string with the value: "Name Lastname", should it not be interned automatically in the string pool and should not output be "true", since Do we already have a string with the same value in the string pool as String firstNamePlusLastname?

EDIT:

, .equals() , , Java , , , , , , "" . , .

+4
4

String Constant Pool create . , / final/ final, final, :

String fullName = "Name Lastname";
String firstNamePlusLastName = "Name " + "Lastname";

System.out.println(fullName == firstNamePlusLastName);// true

String fullName = "Name Lastname";
final String name = "Name ";
final String lastName = "Lastname";
String firstNamePlusLastName = name + lastName;

System.out.println(fullName == firstNamePlusLastName);//true
+1

.equals()

fullName.equals(firstNamePlusLastName)

== ( , ), , , .

.equals() , , , .

:

    String a = new String("a");
    String anotherA = new String("a");
    String b = a;
    String c = a;

a == anotherA -> False;
b == a -> True
b == c -> true
anotherA.equals(a) -> True
0

.equals() .

+ , , , String .

-1

. , ( new String(), , ..), . String firstNamePlusLastName = name + lastName; name lastName, . , intern, .

-1

Source: https://habr.com/ru/post/1677720/


All Articles