[Methods for comparing strings]

package cn.itcast.day08.demo02;

/*
== is to compare the address value of the object. If you determine that you need to compare the content of the string, you can use two methods:

public boolean equals (Object obj): The parameter can be any object, only if the parameter is a string and the content is the same, it will give true, otherwise it will return false
Precautions:
1. Any object can be received by Object
2. The equals method is symmetrical, that is, a.equals(b) and b.equals(a) have the same effect
3. If comparing a constant and a variable between the two parties, it is recommended to write the constant string first
Recommended: "abc".equals(str) Deprecated: str.equals("abc")

public boolean equalsIgnoreCase(String str): Ignore case and compare content
 */
public class Demo01StringEquals {
    public static void main(String[] args) {
        String str1 = "Hello";
        String str2 = "Hello";
        char[] charArray = {'H','e','l','l','o'};
        String str3 = new String(charArray);

        System.out.println(str1.equals(str2));//true
        System.out.println(str2.equals(str3));//true
        System.out.println(str3.equals("Hello"));//true
        System.out.println("Hello".equals(str1));//true

        String str4 = "hello";
        System.out.println(str1.equals(str4));//false
        System.out.println("================================");

        String str5 = null;
        System.out.println("abc".equals(str5));//Recommend false
// System.out.println(str5.equals("abc"));//Not recommended: error, null pointer exception
        System.out.println("==================================");

        String strA = "Java";
        String strB = "java";
        System.out.println(strA.equals(strB));//false, strictly case sensitive
        System.out.println(strA.equalsIgnoreCase(strB));//true, ignore case
    }
}

Guess you like

Origin blog.csdn.net/m0_48114733/article/details/123291244