Java – string S1 = = string S2 (true) but fieldoffset is different

When I was learning Java, I already knew that the correct way to compare two strings was to use equals instead of "= =" This line

static String s1 = "a";
static String s2 = "a";
System.out.println(s1 == s2);  

True will be output because the JVM seems to optimize the code so that they actually point to the same address I'm trying to prove that this is using a great article I found here

http://javapapers.com/core-java/address-of-a-java-object/

But the address seems different I'm missing what

import sun.misc.Unsafe;
import java.lang.reflect.Field;
public class SomeClass {
    static String s1 = "a";
    static String s2 = "a";
    public static void main (String args[]) throws Exception {
        System.out.println(s1 == s2); //true

        Unsafe unsafe = getUnsafeInstance();
        Field s1Field = SomeClass.class.getDeclaredField("s1");
        System.out.println(unsafe.staticFieldOffset(s1Field)); //600

        Field s2Field = SomeClass.class.getDeclaredField("s2");
        System.out.println(unsafe.staticFieldOffset(s2Field)); //604

    }

    private static Unsafe getUnsafeInstance() throws SecurityException,NoSuchFieldException,IllegalArgumentException,illegalaccessexception {
        Field theUnsafeInstance = Unsafe.class.getDeclaredField("theUnsafe");
        theUnsafeInstance.setAccessible(true);
        return (Unsafe) theUnsafeInstance.get(Unsafe.class);
    }
}

Solution

You haven't lost anything. The unsafe library is reporting what actually happened

Bytecode:

static {};
  Code:
   0:   ldc #11; //String a
   2:   putstatic   #13; //Field s1:Ljava/lang/String;
   5:   ldc #11; //String a
   7:   putstatic   #15; //Field s2:Ljava/lang/String;
   10:  return

Note that both strings are placed in different locations in memory, 13 and 15

These variables are stored in memory, which requires a separate address, and whether a new object is placed on the heap In this case, it assigns two separate addresses to two variables, but it does not need to create a new string object because it recognizes the same string text So both variables refer to the same string

How can I get the memory location of a object in Java? The answer in Make sure you read the notes before use, but I did a quick test that seems to work

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>