gpt4 book ai didi

Java:字符串文字和 + 运算符

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:03:04 24 4
gpt4 key购买 nike

import java.util.*;
import java.lang.*;
import java.io.*;

class Test {
public static void main (String[] args) {

String a="hello"+"world"; //line 1
String b="hello";
String c="world";
String d=b+c;
String e="helloworld";
System.out.println(e==a);
System.out.println(a==d);
}
}

输出:

true

false

来自这个讨论How does the String class override the + operator?我知道 'a' 和 'e' 将引用相同的字符串文字对象。

谁能告诉我

  1. 为什么 ad 指的不是同一个字符串文字对象?

  2. 第 1 行创建了多少个对象

最佳答案

来自 JLS 4.3.3. The Class String

The string concatenation operator + (§15.18.1) implicitly creates a new String object when the result is not a compile-time constant expression (§15.28).

因为 a 的字面值是 "helloworld" 而 d 的字面值是 b + c 的引用对象,它不是 a从上面的 JLS 4.3.3 开始的文字。

来自 JLS 3.10.5 String Literals

A string literal consists of zero or more characters enclosed in double quotes.

来自 15.28. Constant Expressions

A compile-time constant expression is an expression denoting a value of primitive type or a String that does not complete abruptly and is composed using only the following:

  • Literals of primitive type and literals of type String (§3.10.1, §3.10.2, §3.10.3, §3.10.4, §3.10.5)

如果你想让 System.out.println(a==d); true 使用 final 关键字看下面的代码:

  String a="hello"+"world";  //line 1
final String b="hello"; // now b is a literal
final String c="world";// now c is a literal
String d=b+c;
String e="helloworld";
System.out.println(e==a);
System.out.println(a==d);// now it will be true because both are literals.

评论答案:
第 1 行创建了多少个对象:答案是 3
String a="你好"+"世界";

1st literal object hello
2nd literal object world
3rd literal object "hello"+"world" == "helloworld"

关于Java:字符串文字和 + 运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29622770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com