String comparison problem in Java

  • == compares whether the addresses of the two strings are equal (whether they are the same address); the equals() method compares whether the contents of the two string objects are the same
  • If you use the new keyword to declare two String variables, even if the contents of the two variables are the same, but the storage location is not the same address, then use == to return false; use equals() to return true
  • If you use string constants to initialize two String type variables, such as String s = "abc"; the string object declared in this way is stored in the constant pool. When the reference String s2 = "abc" is created, the Java bottom layer will take precedence. Look for the existence of "abc" in the constant pool. If it exists, let s2 point to this value and will not be recreated. At this time, when using == comparison, the address is the same and true is returned

Reference: https://blog.csdn.net/liangwenmail/article/details/87978181

Guess you like

Origin blog.csdn.net/mugeit/article/details/114665022