[Java] How to compare with equals method

Programming study diary

November 11, 2020 In yesterday's article, I dealt with the content [Java] == and equals difference. Today, I'll summarize how to compare case-insensitively with the equals method and how to compare nulls with the equals method of the Objects class.

What is the equals method (difference from ==)

Used to compare whether two strings are equal. Primitive types such as int type and double type are compared with ==, but String type is a reference type, so compare using equals method.

public static void main(String[] args) {
    //Initialize the String type variables str1 and str2 with the same string
    String str1 = "hello";
    String str2 = "hello";

    if(str1 == str2)
        System.out.println("1st time: str1=str2 (==Compare with) ");
    else
        System.out.println("1st time: str1 ≠ str2(==Compare with) ");

    //Add the same string
    str1 += "!";
    str2 += "!";

    if(str1 == str2)
        System.out.println("Second time: str1=str2 (==Compare with) ");
    else
        System.out.println("Second time: str1 ≠ str2(==Compare with) ");

    if(str1.equals(str2))
        System.out.println("Third time: str1=str2 (Compare with equals) ");
    else
        System.out.println("Third time: str1 ≠ str2(Compare with equals) ");
}

Execution result


1st time: str1=str2 (==Compare with) 
Second time: str1 ≠ str2(==Compare with) 
Third time: str1=str2 (Compare with equals) 

This code returns true in the first comparison using the == operator, but returns false in the second comparison after adding the string. The third comparison using the equals method returns true. In this way, when the == operator is used, false is returned if the object is different even if the referenced character string is the same, so use the equals method to compare the character strings.

How to make a case-insensitive comparison

Use equalsIgnoreCase if you want to compare as the same string without distinguishing between uppercase and lowercase letters.

public static void main(String[] args) {
    String str1 = "hello";
    String str2 = "HELLO";

    if(str1.equalsIgnoreCase(str2))
        System.out.println("str1=str2 ([Compare with equalsIgnoreCase) ");
    else
        System.out.println("str1≠str2 ([Compare with equalsIgnoreCase) ");

    if(str1.equals(str2))
        System.out.println("str1=str2 (Compare with equals) ");
    else
        System.out.println("str1≠str2 (Compare with equals) ");
}

Execution result


str1=str2 ([Compare with equalsIgnoreCase) 
str1≠str2 (Compare with equals) 

How to safely compare nulls

Use the equals method of the Objects class to make a safe comparison without raising a nullPointerException exception. In the equals method of the String class, a nullPointerException exception is thrown when the object that calls the method is null. First, you need to import java.util.Objects to use the equals method of the Objects class.

import java.util.Objects;
 
public class Main {
 
    public static void main(String[] args) {
 
        String str1 = null;
        String str2 = "abc";
        String str3 = null;
 
        System.out.println(Objects.equals(str1, str2));
        System.out.println(Objects.equals(str1, str3));
    }
}

Execution result


false
true

When comparing null verbs in this way, true can be returned.

References

[Quick learning Java] Difference between ”==” and “equals” (explains how to deny) [Introduction to Java] Summary of how to compare with equals method

Recommended Posts

[Java] How to compare with equals method
How to avoid exceptions with Java's equals method
[Java] How to use join method
How to compile Java with VsCode & Ant
How to use submit method (Java Silver)
[Java] How to use the toString () method
[Java] How to test for null with JUnit
How to use Java framework with AWS Lambda! ??
How to use Java API with lambda expression
How to use the replace () method (Java Silver)
[Java] How to use compareTo method of Date class
[Java] How to use Map
How to call functions in bulk with Java reflection
How to lower java version
[Java] How to use Map
How to uninstall Java 8 (Mac)
Java to play with Function
Java --How to make JTable
[Java] How to omit spring constructor injection with Lombok
How to deploy Java to AWS Lambda with Serverless Framework
How to use java Optional
How to minimize Java images
How to write java comments
[Java] How to encrypt with AES encryption with standard library
How to use java class
[Java] How to use Optional ②
[Java] How to use removeAll ()
[Java] How to display Wingdings
[Java Silver] About equals method
[Java] How to use string.format
How to number (number) with html.erb
How to use Java Map
How to update with activerecord-import
How to set Java constants
Connect to DB with Java
Connect to MySQL 8 with Java
How to build Java development environment with VS Code
How to use Java variables
How to convert Java radix
[Java] How to implement multithreading
[Java] How to use Optional ①
Compare Java 8 Optional with Swift
How to initialize Java array
How to create a method
[Java] How to start a new line with StringBuilder
(Java) How to implement equals () for a class with value elements added by inheritance
How to get the class name / method name running in Java
How to decompile apk file to java source code with MAC
How to use trained model of tensorflow2.0 with Kotlin / Java
How to handle exceptions coolly with Java 8 Stream or Optional
How to test a private method with RSpec for yourself
Be sure to compare the result of Java compareTo with 0
Investigated how to call services with Watson SDK for Java
How to scroll horizontally with ScrollView
How to study Java Silver SE 8
How to use Java HttpClient (Get)
Java to learn with ramen [Part 1]
How to use the form_with method
How to get started with slim
Studying Java # 6 (How to write blocks)
[Java] Points to note with Arrays.asList ()