How to compare String equality in Java?


You can check the equality of two Strings in Java using the equals() method. This method compares this string to the specified object. The result is true if and only if the argument is not null and is a String object that represents the same sequence of characters as this object.

Example

import java.lang.*
public class StringDemo {
   public static void main(String[] args) {
      String str1 = "Tutorialspoint";
      String str2 = "Tutorialspoint";
      String str3 = "Hi";
     
      // checking for equality
      boolean retval1 = str2.equals(str1);
      boolean retval2 = str2.equals(str3);
     
      // prints the return value
      System.out.println("str2 is equal to str1 = " + retval1);
      System.out.println("str2 is equal to str3 = " + retval2);
   }
}

Output

str2 is equal to str1 = true
str2 is equal to str3 = false





Updated on: 26-Feb-2020

212 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements