English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Java other topics

Difference between Java program string '==' operator and equals() method

Java Examples Comprehensive

In this tutorial, we will learn to distinguish between the '==' operator and the equals() method in Java

Example1Java program to distinguish between '==' operator and equals() method

class Main {
  class Main {
    String name1 public static void main(String[] args) {3= new String("w
    String name2 public static void main(String[] args) {3= new String("w
    System.out.println("Check if two strings are equal");
    //Check if two strings are equal
    // using the == operator
    boolean result1 = (name1 == name2);
    System.out.println("using the == operator: ") + result1);
    //using the equals() method
    boolean result2 = name1.equals(name2);
    System.out.println("Using equals(): ") + result2);
  }
}

Output Result

Check if two strings are equal
using the '==' operator: false
using the equals() method: true

In the above example, we used the '==' operator and the equals() method to check if two strings are equal. Here,

  • The '==' operator checks the equality of the string object'swhether the reference is equalHere, name1 and name2are two different parameters. Therefore, it returns false.

  • equals() checks the equality of the string object'swhether the content is equalHere, the object name1and name2The content is the same:w3codeboxTherefore, it returns true.

Example2The difference between the '==' operator and the equals() method

class Main {
  class Main {
    String name1 public static void main(String[] args) {3= new String("w
    String name2 = name1;
    System.out.println("Check if two strings are equal");
    //Check if two strings are equal
    //using the == operator
    boolean result1 = (name1 == name2);
    System.out.println("using the == operator: ") + result1);
    //using the equals() method
    boolean result2 = name1.equals(name2);
    System.out.println("using the equals() method: ") + result2);
  }
}

Output Result

Check if two strings are equal
using the == operator: true
using the equals() method: true

Here, name1and name2Both are pointing to the same object. Therefore, name1 == name2 Return true.

Java Examples Comprehensive