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

nan*_*itv 7 java string

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);
     }
}
Run Code Online (Sandbox Code Playgroud)

输出:

true

false
Run Code Online (Sandbox Code Playgroud)

从这个讨论中,String类如何覆盖+运算符?我知道'a'和'e'将引用相同的String文字对象.

有谁能告诉你

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

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

Sum*_*ngh 15

来自JLS 4.3.3.类字符串

+当结果不是编译时常量表达式(第15.28节)时,字符串连接运算符(第15.18.1节)隐式创建一个新的String对象.

因为a的"helloworld"字面值和d的字面值是b+ 的参考对象c,而不是从JLS 4.3.3以上的文字.

来自JLS 3.10.5字符串文字

字符串文字由用双引号括起来的零个或多个字符组成.

15.28开始.常数表达式

编译时常量表达式是表示基本类型的值的表达式或不突然完成的字符串,仅使用以下内容组成:

  • 原始类型的文字和String类型的文字(§3.10.1,§3.10.2,§3.10.3,§3.10.4,§3.10.5)

如果你想System.out.println(a==d); 真正使用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.
Run Code Online (Sandbox Code Playgroud)

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

第一个文字对象hello
第二个文字对象world
第三个文字对象"hello"+"world"=="helloworld"