Java String Instantiation

后端 未结 3 1692
梦如初夏
梦如初夏 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:00

    String literals are interned. When you create a string through any method that isn't a literal (calling new String(), reading from input, concatenation, etc) it will not be automatically interned. When you called String firstNamePlusLastName = name + lastName; You concatenated name and lastName creating a new string. This is not a literal and you didn't call intern so this string is not added to the string pool.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-13 20:14

    String Constant Pool create at compiling-time. it only using strings from pool when you concat String literals / final variables / final fields except final parameters, for example:

    Concat Literals

    String fullName = "Name Lastname";
    String firstNamePlusLastName = "Name " + "Lastname";
    
    System.out.println(fullName == firstNamePlusLastName);// true
    

    Concat Final Variables

    String fullName = "Name Lastname";
    final String name = "Name ";
    final String lastName = "Lastname";
    String firstNamePlusLastName = name + lastName;
    
    System.out.println(fullName == firstNamePlusLastName);//true
    
    0 讨论(0)
提交回复
热议问题