Java how to compare strings for equality

In java you can use either compareTo() method or equals() method. If you you don't care about the case of the Strings then use compareToIgnoreCase() method or equalsIgnoreCase() method. Here is an example...

Java Program Source Code

package com.as400samplecode;

public class CompareStrings {

 public static void main(String[] args) {

  String string1 = "My Sample Code";
  String string2 = "my sample code";

  //compareTo method returns a 0 if the strings match
  if(string1.compareTo(string2) == 0){
   System.out.println("The strings match.");
  }
  else {
   System.out.println("The strings don't match.");
  }
  
  //same as compareTo method but is case insensitive
  if(string1.compareToIgnoreCase(string2) == 0){
   System.out.println("The strings match.");
  }
  else {
   System.out.println("The strings don't match.");
  }
  
  //returns true if the two objects are equal
  if(string1.equals(string2)){
   System.out.println("The strings match.");
  }
  else {
   System.out.println("The strings don't match.");
  }
  
  //same as equals methods but is case insensitive
  if(string1.equalsIgnoreCase(string2)){
   System.out.println("The strings match.");
  }
  else {
   System.out.println("The strings don't match.");
  }
  
 }
}

Result

The strings don't match.
The strings match.
The strings don't match.
The strings match.

No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.