Java String creates object instance resolution

  • 2021-01-18 06:28:37
  • OfStack

This paper mainly studies the problem of creating objects in Java String, which is described as follows.

The first two concepts we need to understand are reference variables and objects. Object 1 is usually created in the heap via new. String is just a reference variable.

All strings are String objects. Due to the heavy use of string constants, in java, to save time, all string constants are put into the string constant pool at compile time. One of the advantages of string constant pool is that the same string can be merged into one space.

In Java, you can't get the address of a variable directly, but you can use == to determine if the two referenced variables under 1 refer to an address, i.e. an object.

栈内存 堆内存
基础类型,对象引用( 堆内存地址 ) 由new 创建的对象和数组
存取速度快 相对于栈内存较慢
数据大小在声明周期必须确定 分配的内存由java 虚拟机自动垃圾回收器管理。动态分配内存大小
共享特性,栈中如果有字符串,则直接引用;如果没有,开辟新的空间存入值 每new1次都在堆内存中生成1个新的对象。不存在任何复用


package com.demo.test;

import java.lang.reflect.Field;

public class StringDemo {

  public static void main(String[] args) {
    // First, look in memory for the existence of the string object, if there is a point to the string object; 
    String str1 = "abc";
    String str2 = "abc";
    /*
     public String toString() {
      return this;
     }
     */
    String str3 = "abc".toString();
    // The string object is created regardless of whether it already exists in memory 1 An object. 
    String str4 = new String("abc");
    String str5 = new String("abc");
    String str6 = str5;
    String str7 = "a" + "b" + "c";
    String str8 = "a" + "b" + new String("c");
    //String Is an immutable string object, StringBuilder and StringBuffer Is a mutable string object (its internal character array has a variable length), StringBuffer Thread safety, StringBuilder Non-thread safe 
    String str9 = new StringBuilder().append("a").append("b").append("c").toString();
    String str10 = new StringBuffer().append("a").append("b").append("c").toString();

    System.out.println("--------> ==");
    System.out.println("---> 1");
    System.out.println(str1==str2);//true

    System.out.println("---> 3");
    System.out.println(str3==str1);//true

    System.out.println("---> 4");
    System.out.println(str4==str1);//false
    System.out.println(str4==str3);//false
    System.out.println(str4==str5);//false
    System.out.println(str4==str6);//false

    System.out.println("---> 7");
    System.out.println(str7==str1);//true
    System.out.println(str7==str3);//true
    System.out.println(str7==str4);//false

    System.out.println("---> 8");
    System.out.println(str8==str1);//false
    System.out.println(str8==str3);//false
    System.out.println(str8==str4);//false
    System.out.println(str8==str7);//false

    System.out.println("---> 9");
    System.out.println(str9==str1);//false
    System.out.println(str9==str3);//false
    System.out.println(str9==str4);//false
    System.out.println(str9==str7);//false
    System.out.println(str9==str8);//false

    System.out.println("---> 10");
    System.out.println(str10==str1);//false
    System.out.println(str10==str3);//false
    System.out.println(str10==str4);//false
    System.out.println(str10==str7);//false
    System.out.println(str10==str8);//false
    System.out.println(str10==str9);//false

    System.out.println("--------> equals");
    System.out.println(str1.equals(str4));//true
    System.out.println(str1.equals(str7));//true
    System.out.println(str1.equals(str8));//true

    System.out.println("--------> hashCode");
    /*
     hashCode A formula to calculate : s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
       so hashCode Are all 1 Same, and every run 1 sample 
     */
    System.out.println(str1.hashCode());//96354
    System.out.println(str2.hashCode());
    System.out.println(str3.hashCode());
    System.out.println(str4.hashCode());
    System.out.println(str5.hashCode());
    System.out.println(str6.hashCode());
    System.out.println(str7.hashCode());

    System.out.println("--------> normal change value");
    //String Is an immutable class, string This is just a reference to the heap memory, which stores the address of the object in the heap, not the object itself string Assignment simply changes the reference object, not the object itself 
    str6 = "123";
    System.out.println(str5);//abc
    System.out.println(str6);//123

    System.out.println("--------> reflect change value");
    /*
      If you have to change String The value of, is not impossible. I have to use reflection. 
     public final class String implements java.io.Serializable, Comparable<String>, CharSequence {
       // The value is used for character storage.
       private final char value[];
        ... 
     }
    */
    str6 = str5;
    try {
      Field field = String.class.getDeclaredField("value");
//     Field field = str6.getClass().getDeclaredField("value");
      if(!field.isAccessible()) {
        field.setAccessible(true);
      }
      char[] value = (char[])field.get(str6);
      value[0] = '0';
      System.out.println(str5);//0bc
      System.out.println(str6);//0bc
    } catch (NoSuchFieldException | SecurityException | IllegalArgumentException | IllegalAccessException e) {
      e.printStackTrace();
    }

    System.out.println("--------> obj.toString()");
    Object obj = new Object();
    /*
    public String toString() {
      return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }
    */
    System.out.println(obj.toString());//java.lang.Object@15db9742

    String[] arr1 = {"0"};
    String[] arr2 = {"0"};
    System.out.println(arr1.equals(arr2));//false
  }
}

conclusion

If String refers to a string constant, it will first look in the string constant pool (stack), and then refer directly to it. If not, the constant is created in the pool of string constants, and String points to the constant. If String is initialized with the keyword new, a fixed space in the heap is set up for the value of the string, and then String points to the constant. With string constant concatenation, since the expression evaluates the rvalue first, it is equivalent to pointing String to a new concatenated string constant. It also looks in the string constant pool, and points to it if it has one; If not, the constant is created in the pool of string constants, and String points to the constant. But if there is a string generated using new in the concatenation, the new string is equivalent to the one created in the heap using new. If you change the value of String, you can only change the reference to String, not the object that String points to. If you must change the object itself, you can use reflection. In the case of an array, since it is an object, ES33en only compares its array pointer address and does not compare the equality of its elements.

This article is about Java String create object instance resolution of all content, I hope to help you. Interested friends can continue to refer to the site of other related topics, if there are shortcomings, welcome to leave a message to point out. Thank you for your support!


Related articles: