Java字符串实例化 [英] Java String Instantiation

查看:252
本文介绍了Java字符串实例化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此代码返回false而不是true:

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);

    }
}

如果我没记错的话:

String firstNamePlusLastName = name + lastName;

应该创建一个指向内存中现有地址的String(String pool),因为我们已经声明了一个带有值的字符串:Name Lastname,它不应该被自动插入到字符串池中,并且输出不应该是true,因为我们已经在字符串池中具有与String firstNamePlusLastname相同的字符串?

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 ?

编辑:

我知道在测试两个字符串是否相同时我应该使用.equals()方法,但我不知道我想在上面的例子中做到这一点,我实际上确实想测试参考相等性,并且基于Java实习,我在上面的代码中比较的两个字符串应该相等,但它们不是,它们应该指向相同的在内存中的地址,因为它们具有相同的内容,并且两个字符串都不是使用new关键字创建的。我想知道为什么会发生这种情况。

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.

推荐答案

字符串常量池在编译时创建。当你连接字符串文字 / 最终变量/ 最终字段时,它只使用池中的字符串,除了最终参数,示例:

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:

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

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



< h2> Concat最终变量

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

这篇关于Java字符串实例化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆