String str1="Hello",String str2=new String("Hello")

package com.HelloWorld;
/*
String str1= "hello", String str2="he"+"llo"; The reason why str1==str2 returns true is because both are in the string constant pool
(because the initialization will Distribute memory in this area) and the constant pool has a feature similar to the stack area, that is, when the constant pointed to by str2 already exists in the constant area,
he will not create a new memory space to store this constant, but point to the existing constant. There is constant memory (this should save space), at this time, the values ​​of the two reference
variables are the memory space addresses of "hello", but String str3= "he"+a;String a= "llo"; when str1==str3 returns false,
because: hello pointed to by str1 is allocated in the constant area as always at compile time, and llo pointed to by a is also in the constant area. Although str3 is also initialized, the
compiler cannot Determine what the situation of a is, and then not declare the right side of the equal sign of str3 in the constant area, but declare it in
the memory outside the non-constant pool in the heap area during construction, so far str3 and str1 Not only is the time of allocation of memory different (one at compile time, one at runtime) but also in the
area , the top-voted answer above only distinguishes between time and not space.
*/
public class StringOne {

public static void main(String[] args) {
  String str1="kobe";
  String str7="kobe";//str1与str7同时指向kobe字符串
  String str2="bryant";
  String str3="kobebryant";
  String str4="kobe"+"bryant";
  String str5="ko"+"be"+"bryant";
  String str6=str1+str2;
  System.out.println(str1==str7);//true
  System.out.println(str3==str4);//true
  System.out.println(str3==str5);//true
  System.out.println(str3==str6);//false
  System.out.println(str3.equals(str6));//true
  String str8;
  str8=str7;
  str8="ok";//str8重新指向ok字符串
  System.out.println(str1);//kobe

  }

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325032599&siteId=291194637