gpt4 book ai didi

java - 当我们在java中使用连接两个字符串对象时编译器如何工作

转载 作者:行者123 更新时间:2023-12-01 18:30:03 24 4
gpt4 key购买 nike

 class Simple{  
public static void main(String args[]){
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}

编译器将其转换为:

    String s = (new StringBuilder()).append("Sachin").append(" Tendulkar").toString();  

最后一行是什么意思?

最佳答案

Java 编译器只会在编译时连接这两个字符串,并生成以下指令

代码

public class StringConcatInspection {
public static void main(String[] args) {
String s = "Sachin" + " Tendulkar";
}
}

它将编译为

  Last modified Jul 9, 2014; size 473 bytes
MD5 checksum 5238429068ccae4ec199f4af970ad46e
Compiled from "StringConcatInspection.java"
public class StringConcatInspection
SourceFile: "StringConcatInspection.java"
minor version: 0
major version: 52
flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
#1 = Methodref #4.#20 // java/lang/Object."<init>":()V
#2 = String #21 // Sachin Tendulkar
#3 = Class #22 // StringConcatInspection
#4 = Class #23 // java/lang/Object
#5 = Utf8 <init>
#6 = Utf8 ()V
#7 = Utf8 Code
#8 = Utf8 LineNumberTable
#9 = Utf8 LocalVariableTable
#10 = Utf8 this
#11 = Utf8 LStringConcatInspection;
#12 = Utf8 main
#13 = Utf8 ([Ljava/lang/String;)V
#14 = Utf8 args
#15 = Utf8 [Ljava/lang/String;
#16 = Utf8 s
#17 = Utf8 Ljava/lang/String;
#18 = Utf8 SourceFile
#19 = Utf8 StringConcatInspection.java
#20 = NameAndType #5:#6 // "<init>":()V
#21 = Utf8 Sachin Tendulkar
#22 = Utf8 StringConcatInspection
#23 = Utf8 java/lang/Object
{
public StringConcatInspection();
flags: ACC_PUBLIC
Code:
stack=1, locals=1, args_size=1
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return
LineNumberTable:
line 4: 0
LocalVariableTable:
Start Length Slot Name Signature
0 5 0 this LStringConcatInspection;

public static void main(java.lang.String[]);
flags: ACC_PUBLIC, ACC_STATIC
Code:
stack=1, locals=2, args_size=1
0: ldc #2 // String Sachin Tendulkar
2: astore_1
3: return
LineNumberTable:
line 6: 0
line 7: 3
LocalVariableTable:
Start Length Slot Name Signature
0 4 0 args [Ljava/lang/String;
3 1 1 s Ljava/lang/String;
}

编译器版本:1.7.0_60-ea

尊重萨钦

关于java - 当我们在java中使用连接两个字符串对象时编译器如何工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24640006/

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