The offset of the instance property of the String type in memory does not change with the length of the string.

public class A {
  public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
    //System.out.println(  ClassLoader.getSystemClassLoader().toString());
    Unsafe unsafe = UnsafeUtil.getUnsafe();
    Person person = new Person();
    long offset = unsafe.objectFieldOffset(person.getClass().getDeclaredField("name1"));
    System.out.println(offset); // 16
    person.setName1("fasfsa321312");
    long offset1 = unsafe.objectFieldOffset(person.getClass().getDeclaredField("name1"));
    System.out.println(offset1);

  }

  private static class Person{
   // private int a;
    private String name;
    private String name1;
   // private static int c;
   // private int b;
    public void setName(String name){
      this.name = name;
    }

    public String getName(String name){
      return this.name;
    }

    public void setName1(String name){
      this.name1 = name;
    }

    public String getName1(String name){
      return this.name1;
    }
  }

  private static class UnsafeUtil {
    private static Unsafe getUnsafe() throws NoSuchFieldException, IllegalAccessException {
      Field field = Unsafe.class.getDeclaredField("theUnsafe");
      field.setAccessible(true);
      return (Unsafe) field.get(null);
    }
  }
}

output result is
16
16

what I want to know is why the memory address does not change when the string changes? Bosses help answer

.
Mar.29,2021


when the object is created, java creates the object in the memory heap and stack respectively, and the changes you make to its properties are all stack-based operations. After the update is finished, the address in the heap will be updated to the heap, and the address in the heap will not change. The memory address is the address of the heap


is my own confusion, and the address stored in the object is the address.

  • A little question about JMM

    < H1 > Hello, everyone. I just watched a video tutorial. I have a question < H1 >. Video tutorial. Is it true to say that stack data can be shared in jmm? I remember that the data in the heap can be shared. Is he wrong? ...

    May.22,2021
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e3c4cb-4361c.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e3c4cb-4361c.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?