Software Training Institute in Chennai with 100% Placements – SLA Institute

Easy way to IT Job

Share on your Social Media

How to compare two Strings in Java – 11 Methods

Published On: March 30, 2023

String manipulation can be useful in many areas. It can help with data mining, text analysis, and data matching. In this tutorial, we will look at a comparison of two Java strings for different string manipulation purposes. In Java, you can compare two strings in several ways. A Java function called string compare compares an array of characters to a string. Use the methods provided by the following classes to learn the process of compare two strings in Java. Using the String class from Java.lang package. Using the Objects class from Java.util package. Using StringUtils class from package org.apache.commons.lang3.

Method 1: String equals() method

When two String objects are compared for equality, the Java String equals() function finds a match.

Syntax

public boolean equals(Object anObject)

equals() method parameters:

anObject – the string used as a parameter for comparing strings.

return types from the equals() method.

  • If the supplied string literally matches the original string, the function returns true.
  • If the first string is different from the given string, it returns false.

Example

public class CompareTwoStrings {

public static void main(String[] args) {

String stringOne = “SLA567”;

String stringTwo = “SLA567”;

System.out.println(“is SLA567 equal to SLA 567: “+stringOne.equals(stringTwo));

String stringThree = “Sla567”;

System.out.println(“is SLA567 equal to SLA567: “+stringOne.equals(stringThree));

}

}

Output

is SLA567 equal to SLA567: true

is SLA567 equal to Sla567: false

The reason we received the wrong one in the previous printout was that the item shipped had a different case.

Use the string equality method to compare characters separated by strings. Use the “equalsIgnoreCase” function to compare string objects with different string values.

Method 2: Equals() function on objects. 

Two String objects are compared using the Java Objects equals() method to see if they have the same values.

Syntax:

public static boolean equals(Object a, Object b)

equals() method parameters

a – the argument string of the first string object.

b – argument string to another string object.

return types from the equals() method.

  • Returns true if the string literals are equivalent. Both parameters can be left blank and the result will still be true.
  • Returns false if string literals are not equal.

Example

import java.util.Objects;

public class CompareTwoStrings {

    public static void main(String[] args) {

        String stringOne = “SLA123”;

        String stringTwo = “SLA123”;

        System.out.println(“is SLA123 equal to SLA123: ” + Objects.equals(stringOne, stringTwo));

        String stringThree = null;

        String stringFour = null;

        System.out.println(“is SLA123 equal to SLA123: ” + Objects.equals(stringThree, stringFour));

    }

}

Output

is SLA123 equal to SLA123: true

is SLA123 equal to SLA123: true

Given that the strings were compared for equality, you can see from this example that the result is a boolean.

Method 3. String comparisonTo() function

Two strings are compared alphabetically with the Java String compare() function. This is often called the lexicographic sequence.

Syntax:

public int compareTo(String str)

compareTo() method parameters

str – The string is compared to the currently used string.

Compare() returns the results

  • If the given object and the current string are equal, null is returned.
  • If this string is shorter than the given object, a value less than zero is returned. If this string is longer than the supplied string, it returns a value greater than zero.

Example

public class CompareTwoStrings {

public static void main(String[] args) {

String stringOne = “SLA123”;

String stringTwo = “SLA123”;

System.out.println(“is SLA123 equal to SLA123: ” + stringOne.compareTo(stringTwo));

String stringThree = “Sla123”;

System.out.println(“is SLA123 equal to Sla123: ” + stringOne.compareTo(stringThree));

}

}

Output

is SLA123 equal to SLA123: 0

is SLA123 equal to Sla123: 32

Since the first and second strings are equal, the first result gives zero. Considering that the signs are separate, the second result gives the value of thirty-two. Note. You can use the “compareToIgnoreCase” function to ignore case characters.

Method 4: StringUtils equals() method

The equals() function of the Java StringUtils class checks whether two strings are equal. Make sure your software includes the “org.apache.commons.lang3” library. You can then compare the strings in Java using the StringUtil method.

Syntax

public static boolean equals(CharSequnce cs1, CharSequence cs2)

Equals() method arguments to StringUtils

  • cs1 – the string for the first argument.
  • cs2 – The string name of the second parameter is cs2.

The equals() function of StringUtils produces

  • Returns true if the string comparison succeeds. It can be used if one of the two parameters is empty.
  • If the string comparison does not match, it returns false.

Example

import org.apache.commons.lang3.StringUtils;

public class CompareTwoStrings {

public static void main(String[] args) {

String stringOne = “SLA123”;

String stringTwo = “SLA123”;

System.out.println(“is SLA123 equal to SLA123: ” + StringUtils.equals(stringOne, stringTwo));

String stringThree = “Sla123”;

System.out.println(“is SLA123 equal to Sla123: ” + StringUtils.equals(stringOne, stringThree));

}

}

Output

is SLA123 equal to SLA123: true

is SLA123 equal to Sla123: false

The result is true because the contents of the first and second strings are the same.

Use the “equalsIgnoreCase” function to ignore the case.

Method 5: StringUtils equals each() method 

The equalsAny() function of Java StringUtils determines whether the inputs contain a string.

Syntax

public static boolean equalsAny(CharSequence string, Charsequence… searchStrings)

Parameters for the StringUtils equalsAny() method

string – The first argument’s string value. The argument may as an alternative be empty.

In order to decide whether or not the primary parameter string is a gift, the feature makes use of a listing of string arguments known as searchStrings.

The equalsAny() feature of StringUtils produces

  • If the desired string is given a few of the diverse seek strings, then the actual is returned. If one or each argument is null, this holds.
  • If not one of the strings withinside the variable wide variety of seek strings healthy the string to healthy, the feature returns false.

Example

import org.apache.commons.lang3.StringUtils;

public class CompareTwoStrings {

    public static void main(String[] args) {

        String stringOne = “SLA123”;

        String[] stringTwo = new String[] {

            “SLA123”,

            “SLAIns123”

        };

        System.out.println(“is SLA123 available: ” +

            StringUtils.equalsAny(stringOne, stringTwo));

        String[] stringThree = new String[] {

            “SLA123”,

            “SLAIns123”

        };

        System.out.println(“is Sla123 available: ” +

            StringUtils.equalsAny(stringOne, stringThree));

    }

}

Output

is SLA123 available: true

is Sla123 available: false

The result is actual for the reason that the first and 2nd strings’ contents are identical. To push aside the case, use the “equalsAnyIgnoreCase” function.

Method 6: Using == operator

The item references of strings are checked for equality in the use of the == operator.

Example

public class CompareTwoStrings {

public static void main(String[] args) {

String stringOne = “SLA123”;

String stringTwo = “SLA123”;

System.out.println(“is SLA123 == to SLA123: ” + (stringOne == stringTwo));

String stringThree = “Sla123”;

System.out.println(“is SLA123 == to Sla123: ” + (stringOne == stringThree));

}

}

Output

is SLA123 == to SLA123: true

is SLA123 == to Sla123: false

A genuine boolean cost is back because of the first result. The string stocks an available to cope with due to the fact strings with identical contents are delivered to the identical string pool.

A boolean cost of fake is back with the aid of using the second outcome. The items’ numerous contents result in numerous string pools. As a result, the output is fake for the reason that strings comprise impartial item references.

Method 7: Develop a completely unique Java technique to evaluate strings

Create a technique that makes use of lexicographic order to evaluate strings.

Syntax:

public static int compareTwoStrings(String str1, String str2)

Custom method parameters

str1 – The string to compare.

str2 – The string to compare against.

Custom technique returns

  • = 0 – If the primary and 2nd strings are equal, zero is returned.
  • < 0 – If the first string is shorter than the second string, the function returns a value that is less than zero.
  • > 0- If the primary string is longer than the second string, the result aside from 0 is returned.

Example

public class CompareTwoStrings

{

public static int compareTwoStrings(String stringOne, String stringTwo)

{

int lengthOfStringOne = stringOne.length();

int lengthOfStringTwo = stringTwo.length();

int minStringLength = Math.min(lengthOfStringOne, lengthOfStringTwo);

for (int i = 0; i < minStringLength; i++) {

char stringOneCharValue = stringOne.charAt(i);

char stringTwoCharValue = stringTwo.charAt(i);

if (stringOneCharValue != stringTwoCharValue) {

return stringOneCharValue – stringTwoCharValue;

}

}

if (lengthOfStringOne != lengthOfStringTwo) {

return lengthOfStringOne – lengthOfStringTwo;

} else {

return 0;

}

}

public static void main(String[] args) {

String stringOne = “SLA123”;

String stringTwo = “SLA123”;

System.out.println(“is SLA123 equal to SLA123: ” + compareTwoStrings(stringOne, stringTwo));

}

}

Output

Is SLA123 equals to SLA123: 0

The custom characteristic is running as predicted due to the fact the result back 0 as its value

Recap

The following variables have an effect on which Java methods to be used to examine strings.

  • Want to be in charge of your process? Create a unique method in this situation.
  • Legacy code isn’t permitted. the usage of Java 6 and earlier.
  • the technique that plays best.
  • What sort of records you’re using. Taking a string suit from a listing of variable inputs as an example.

The features that the reduced-in-size library gives. For instance, the StringUtils package deal gives quite a few features for string differences.

If you’re inquisitive about gaining knowledge of string contrast deeply, join the Best Java Courses in Chennai with IBM Certifications at SLA Institute.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.