Home  >  Q&A  >  body text

Java 中各种空(""、\u0000、null)的区别?

String s1 = "";
String s2 = "\u0000";
String s3 = null;

s1、s2、s3 的区别,分别在字符串常量池和栈中的储存情况?

PHPzPHPz2743 days ago890

reply all(2)I'll reply

  • 巴扎黑

    巴扎黑2017-04-18 10:53:28

    Let’s understand it from the perspective of class bytecode
    1.String s1 = "", the following is the compiled bytecode, you can see that there is actually no difference in this case s1="aaa", they are all Push a string from the constant pool to the top of the stack and assign it to a local variable.

    0: ldc           #16                 // String
    2: astore_1
    3: return

    2. In the case of String s2=null, at this time, no string constant is generated in the constant pool, only null is pushed to the top of the stack and assigned to the variable.

    0: aconst_null
    1: astore_1
    2: return

    3. In the case of String s3 = "u0000", a string representing NUL will be generated in the constant pool, which is the so-called Control Character.

    0: ldc           #16                 // String NUL
    2: astore_1
    3: return

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:53:28

    Test environment: jdk-8.0-102

    reply
    0
  • Cancelreply