Why is the string String an immutable string && "".equals(str) and str.equals("") difference

Why is the string String an immutable string

In fact, the implementation of the String class is an array of type char

Although the source code is set to private final char[] value;

The final keyword means immutable

But it just can't start directly at the reference address of the value array

Or can you make changes in the array value

Like value[2] = 1;

But the designer cleverly avoided this pit

Also make the array final

public static void main(String[] args) {
  final char[] value = {1,2,3,4};
  char[] v = new char[4];
  value = v;
}
public static void main(String[] args) {
    final char[] value = {1,2,3,4};
    value[2] = 6;
    System.out.println(value);
}

Although the string itself cannot be changed

But you can change the string variable to point to the address of another string

And the string has a shared string constant pool (here I will fill in the hole after I read "In-depth Java Virtual Machine")

So if you copy a string variable

The original string shares the same characters as the copied string

In fact, it is also because of one of the characteristics of java - there is no pointer that can directly change memory variables

 

 

 

The difference between "".equals(str) and str.equals("")

"".equals(str) This way of writing can avoid the system reporting null pointer exception error

1 class Solution {
2   private static String a;
3   public static void main(String[] args) {
4     if("".equals(a))
5       System.out.println("''.equals(a)");
6     if(a.equals(""))
7       System.out.println("a.equals('')");
8   }
9 }

 

Guess you like

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