Java String Instantiation

后端 未结 3 1714
梦如初夏
梦如初夏 2021-01-13 19:18

Why is this code returning \"false\" instead of \"true\":

package com.company;


public class Main {

    public static void main(String[] args) {

        S         


        
3条回答
  •  自闭症患者
    2021-01-13 20:11

    Because you must use .equals() to strings

    fullName.equals(firstNamePlusLastName)

    == tests for reference equality (whether they are the same object), meaning exactly the same, the same reference even.

    .equals() refers to the equals implementation of an object, it means, for string, if they has the same chars in the same order.

    Consider this:

        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
    

提交回复
热议问题