Java String equals example

String's equals method compares String with specified object. It checks if both have same character sequence. It is generally used to compare two Strings.

Method Signature:

public boolean equals(Object anObject)

String equals Example:

package org.arpit.java2blog;

public class StringEqualsExamplesMain {
 public static void main(String[] args) {
  String str1 = "Hello world from java2blog.com";
  String str2 = new String("Hello world from java2blog.com");
  String str3 = "Hello world from JAVA2BLOG.COM";

  if (str1.equals(str2)) {
   System.out.println("1st and 2nd Strings are equal");
  } 
  else {
   System.out.println("1st and 2nd Strings are not equal");
  }

  if (str1.equals(str3)) {
   System.out.println("1st and 3rd Strings are equal");
  } 
  else {
   System.out.println("1st and 3rd Strings are not equal");
  }
 }
}


When you run above program, you will get below output:
1st and 2nd Strings are equal
1st and 3rd Strings are not equal

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012