Java.lang.StringWhat exactly did the + operation do?

Author: Pz https://www.cnblogs.com/panzi/p/11956782.html

In previous interviews, String was frequently visited. Here are a few general points of knowledge:

  • String Constant Pool

  • new String()

  • The difference between ==and equals

  • native methodString.intern()

Although the interview was generally correct, I couldn't answer one of the questions in the WeChat group this morning. The question is as follows:

String str3 = "what";
String str4 = str3 + " a nice day";
//At runtime, + is equivalent to new, so there will be "what a nice day" objects in the heap, two "what" and "a nice day" objects in the constant pool, and no "what a nice day" objects.
//See if that's right, guys. How come I don't feel right?
//Isn't there a "what a nice day" object for a constant pool?

After looking at this question, I am a little confused to tell the truth. I just know "what a nice day" will not be in the constant pool, but I don't know the specific reason. Later, the students in the group said that the + sign was called. StringBuffer append method of.

I confirmed that I did call the append method, but I was confused that the toString() method was not called.(Finally confirmed, yes StringBuilder append method of, not StringBuffer).

Code Validation

public static void main(String[] args) {
    //#1
    String str1 = "what";
    //#2
    String str2 = str1 + " a nice day";
    //#3
    System.out.println("what a nice day".equals(str2));
    //#4
    System.out.println("what a nice day" == str2);
}

Now there are the following questions, the little buddies will see if they can answer them, even if they do, do you know why?

  1. Storage location for str1?

  2. Storage location for str2?

  3. Is the result true or false?

  4. Is the result true or false?

  5. Where is "what a nice day" stored?

Answer analysis (based on JDK1.8)

Next, let's look directly at the byte code generated:

localhost:test didi$ javap -verbose -p Main.class
Classfile /develop/project/string-test/out/production/classes/com/fanpan26/string/test/Main.class
  Last modified 2019-11-29; size 972 bytes
  MD5 checksum 1d1f1a23bfe85c2f88d2f767e8aac314
  Compiled from "Main.java"
public class com.fanpan26.string.test.Main
  minor version: 0
  major version: 52
  flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
   #1 = Methodref          #13.#34        // java/lang/Object."<init>":()V
   #2 = String             #35            // what
   #3 = Class              #36            // java/lang/StringBuilder
   #4 = Methodref          #3.#34         // java/lang/StringBuilder."<init>":()V
   #5 = Methodref          #3.#37         // java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
   #6 = String             #38            //  a nice day
   #7 = Methodref          #3.#39         // java/lang/StringBuilder.toString:()Ljava/lang/String;
   #8 = Fieldref           #40.#41        // java/lang/System.out:Ljava/io/PrintStream;
   #9 = String             #42            // what a nice day
  #10 = Methodref          #43.#44        // java/lang/String.equals:(Ljava/lang/Object;)Z
  #11 = Methodref          #45.#46        // java/io/PrintStream.println:(Z)V
  #12 = Class              #47            // com/fanpan26/string/test/Main
  #13 = Class              #48            // java/lang/Object
  #14 = Utf8               <init>
  #15 = Utf8               ()V
  #16 = Utf8               Code
  #17 = Utf8               LineNumberTable
  #18 = Utf8               LocalVariableTable
  #19 = Utf8               this
  #20 = Utf8               Lcom/fanpan26/string/test/Main;
  #21 = Utf8               main
  #22 = Utf8               ([Ljava/lang/String;)V
  #23 = Utf8               args
  #24 = Utf8               [Ljava/lang/String;
  #25 = Utf8               str1
  #26 = Utf8               Ljava/lang/String;
  #27 = Utf8               str2
  #28 = Utf8               StackMapTable
  #29 = Class              #24            // "[Ljava/lang/String;"
  #30 = Class              #49            // java/lang/String
  #31 = Class              #50            // java/io/PrintStream
  #32 = Utf8               SourceFile
  #33 = Utf8               Main.java
  #34 = NameAndType        #14:#15        // "<init>":()V
  #35 = Utf8               what
  #36 = Utf8               java/lang/StringBuilder
  #37 = NameAndType        #51:#52        // append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
  #38 = Utf8                a nice day
  #39 = NameAndType        #53:#54        // toString:()Ljava/lang/String;
  #40 = Class              #55            // java/lang/System
  #41 = NameAndType        #56:#57        // out:Ljava/io/PrintStream;
  #42 = Utf8               what a nice day
  #43 = Class              #49            // java/lang/String
  #44 = NameAndType        #58:#59        // equals:(Ljava/lang/Object;)Z
  #45 = Class              #50            // java/io/PrintStream
  #46 = NameAndType        #60:#61        // println:(Z)V
  #47 = Utf8               com/fanpan26/string/test/Main
  #48 = Utf8               java/lang/Object
  #49 = Utf8               java/lang/String
  #50 = Utf8               java/io/PrintStream
  #51 = Utf8               append
  #52 = Utf8               (Ljava/lang/String;)Ljava/lang/StringBuilder;
  #53 = Utf8               toString
  #54 = Utf8               ()Ljava/lang/String;
  #55 = Utf8               java/lang/System
  #56 = Utf8               out
  #57 = Utf8               Ljava/io/PrintStream;
  #58 = Utf8               equals
  #59 = Utf8               (Ljava/lang/Object;)Z
  #60 = Utf8               println
  #61 = Utf8               (Z)V
{
  public com.fanpan26.string.test.Main();
    descriptor: ()V
    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 6: 0
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0       5     0  this   Lcom/fanpan26/string/test/Main;

  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V
    flags: ACC_PUBLIC, ACC_STATIC
    Code:
      stack=3, locals=3, args_size=1
         0: ldc           #2                  // String what
         2: astore_1
         3: new           #3                  // class java/lang/StringBuilder
         6: dup
         7: invokespecial #4                  // Method java/lang/StringBuilder."<init>":()V
        10: aload_1
        11: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
        14: ldc           #6                  // String  a nice day
        16: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
        19: invokevirtual #7                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
        22: astore_2
        23: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream;
        26: ldc           #9                  // String what a nice day
        28: aload_2
        29: invokevirtual #10                 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
        32: invokevirtual #11                 // Method java/io/PrintStream.println:(Z)V
        35: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream;
        38: ldc           #9                  // String what a nice day
        40: aload_2
        41: if_acmpne     48
        44: iconst_1
        45: goto          49
        48: iconst_0
        49: invokevirtual #11                 // Method java/io/PrintStream.println:(Z)V
        52: return
      LineNumberTable:
        line 9: 0
        line 11: 3
        line 13: 23
        line 15: 35
        line 16: 52
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
            0      53     0  args   [Ljava/lang/String;
            3      50     1  str1   Ljava/lang/String;
           23      30     2  str2   Ljava/lang/String;
      StackMapTable: number_of_entries = 2
        frame_type = 255 /* full_frame */
          offset_delta = 48
          locals = [ class "[Ljava/lang/String;", class java/lang/String, class java/lang/String ]
          stack = [ class java/io/PrintStream ]
        frame_type = 255 /* full_frame */
          offset_delta = 0
          locals = [ class "[Ljava/lang/String;", class java/lang/String, class java/lang/String ]
          stack = [ class java/io/PrintStream, int ]
}
SourceFile: "Main.java"

As you can see from the information in Constant pool:#2, #6, #9 can answer the 1,5 questions above.

  • str1 is stored in a constant pool

  • "what a nice day" (not str2) is also stored in a constant pool

Now let's see what the + action did, as you can see in Code, that it called StringBuilder.append Method

11: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
14: ldc           #6                  // String  a nice day
16: invokevirtual #5                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
19: invokevirtual #7                  // Method java/lang/StringBuilder.toString:()Ljava/lang/String;

So here's all the answers

  • str2 is stored in the heap

  • equals is true

  • ==false

So in fact, STR1 + "a nice day" is equivalent to new StringBuilder (). append (str1). append ("a nice day");

//The byte codes produced by these two writings are the same.
//String str2 = str1 + " a nice day";
String str2 = new StringBuilder().append(str1).append(" a nice day").toString();

and StringBuffer The toString method for is as follows:

@Override
public String toString() {
    //So str2 is actually a new String, it's not in the constant pool.
    return new String(value, 0, count);
}

summary

By the byte code of the class ( Three Sao operations to show you Java byte codes ) You can see how the underlying implementation works, so while it seems like a simple String problem, digging deeper still investigates the understanding of the generated byte code.

Also, when you encounter a question, you can't remember the answer by heart. Some people tell you, +operation is a new object, but have you thought about it or why?If there are any errors in the above, you are welcome to point out.

Have a try

/**
 * What is the output of the following programs?
 * */
public static void main(String[] args) {
    String str1 = "what";
    String str2 = str1 + " a nice day";
    System.out.println("what a nice day".equals(str2));
    System.out.println("what a nice day" == str2);
}

/**
 * What is the output of the following programs?
 * */
public static void main(String[] args) {
    String str1 = "what a nice day";
    String str2 = new String("what a nice day");
    System.out.println(str1.equals(str2));
    System.out.println(str1 == str2);
}


/**
 * What is the output of the following programs?
 * */
public static void main(String[] args) {
    String str1 = "what";
    String str2 = str1.concat(" a nice day");
    System.out.println("what a nice day".equals(str2));
    System.out.println("what a nice day" == str2);
    System.out.println("what a nice day"==str2.intern());
}

Recommend going to my blog to read more:

1.Java JVM, Collections, Multithreaded, New Features Series Tutorial

2.Spring MVC, Spring Boot, Spring Cloud series tutorials

3.Maven, Git, Eclipse, Intellij IDEA Series Tools Tutorial

4.Latest Interview Questions for Java, Backend, Architecture, Alibaba, etc.

Feel good, don't forget to say yes + forward!

Tags: Programming Java Spring jvm Maven

Posted on Thu, 21 May 2020 19:54:34 -0700 by phpretard