How to compare strings in Java?

In this article, you will learn how to compare strings and the problems that occur when you compare strings using the equal (=) operator.

introduce

String is a special class in Java. We use string regularly in Java programs, so comparing two strings is a common practice in Java. In this article, I try to answer the most common questions about strings, such as: "how do I compare strings in Java?"

In the process of authentication, sorting and reference matching, it is very helpful to compare strings.

I've listed three ways to compare strings in Java.

1. Use the equals () method (compare content)

2. Use = = operator (compare object reference)

3. Use the compareTo() method (compare strings in dictionary order)

1. Use the Equals () method to compare strings

So, I'm using the. equals () instance method of the String class. Initially, the. equals () method is an Object class method, which is overridden by the String class.

The equals () method compares the value equality of two strings, whether they are logically equal or not.

The equals () method in the String class takes another String as a parameter and compares it with the specified String. It returns true when and only if the parameter String is not null and contains the same characters as the specified String.

1

public boolean equals(Object anObject)

2

3

It compare this string with the argument strings and return true if the argument is not null and contains the same character as the specified string.

4

5

param -

6

another string

7

8

returns -

9

10

true - if argument is not null and it contains same characters as the specified string

11

false - if the argument is null or it does not contain same characters as the specified string

12

13

ex. firstString.equals(secondString)

14

// returns true if and only if the secondString is not null and contains the same characters as firstString.

I've asked the program to compare strings using the equals () method below:

1

/**

2

 * A Java program to compare two strings using equsls()

3

 * and equalsIgnoreCase() method of the String.

4

 *

5

 * @author Gaurav Kukade at coderolls.com

6

 */

7

8

public class CompareUsingEquals {

9

10

  public static void main(String[] args) {

11

    String firstString = "coderolls";

12

    String secondString = "javablog";

13

    String thirdString = "coderolls";

14

    String fourthString = "CodeRolls";

15

16

    System.out.println("Comparing strings using equals() and equalsIgnoreCase() method\n");

17

18

    // Using equals() method

19

    System.out.print("firstString.equals(secondString) : ");

20

    System.out.println(firstString.equals(secondString));

21

22

    System.out.print("firstString.equals(thirdString) : ");

23

    System.out.println(firstString.equals(thirdString));

24

25

    /*

26

     * Using equalsIgnoreCase() method to ignore

27

     * case consideration (i.e. Capital or small) of both the strings.

28

     */

29

    System.out.print("firstString.equalsIgnoreCase(fourthString) : ");

30

    System.out.println(firstString.equalsIgnoreCase(fourthString));

31

  }

32

33

}

 

Output:

1

Comparing strings using equals() and equalsIgnoreCase() method

2

3

firstString.equals(secondString) : false

4

firstString.equals(thirdString) : true

5

firstString.equalsIgnoreCase(fourthString) : true

2. Use = = operator to compare strings

In String, the = = operator is used to compare references to a given String, depending on whether they refer to the same object.

When comparing two strings using the = = operator, if the string variable points to the same Java object, it returns true. Otherwise, it will return false.

I gave a Java program, which can be compared with = = operator in the following:

1

/**

2

 * A Java program to compare strings using == operator.

3

 *

4

 * == operator ckecks whether both the strings referring

5

 * to the same String Object.

6

 *

7

 * @author Gaurav Kukade at coderolls.com

8

 */

9

10

public class CompareUsingEqualsToOperator {

11

12

  public static void main(String[] args) {

13

14

    String firstString = "coderolls";

15

    String secondString = "javablog";

16

    String thirdString = "coderolls";

17

18

    // creating new String object with the same value as firstString or thirdString

19

    String fourthString =  new String("coderolls");

20

21

    System.out.println("Comparing strings using == operator \n");

22

23

    System.out.print("firstString == secondString : ");

24

    System.out.println(firstString == secondString);

25

26

    /*

27

     * Here firstString and thirdString is referring to the same String object

28

     * hence it will print 'true'.

29

     */

30

    System.out.print("firstString == thirdString : ");

31

    System.out.println(firstString == thirdString);

32

33

    /*

34

     * Here firstString and fourthString have same value

35

     * but they are referring to the different String object.

36

     *

37

     * hence it will print 'false'

38

     */

39

    System.out.print("firstString == fourthString : ");

40

    System.out.println(firstString == fourthString);

41

  }

42

43

}

 

Output:

1

Comparing strings using == operator

2

3

firstString == secondString : false

4

firstString == thirdString : true

5

firstString == fourthString : false

 

 

There was a problem comparing strings using the = = operator

Most novice Java developers make this error by comparing two strings using = = operator.

Logically, they have to check that both strings contain the same sequence of characters.

In Java strings, the = = operator is used to check references to two string objects, and the equals () method is used to check that the values of the two strings are equal.

==– check that references are equal

equals() - check if the values are equal

When we assign a string value to a string variable, the JVM checks whether a string with an equal value already exists in the string pool. If it does not exist in the string pool, it is added to the constant pool and a reference to the string object is returned.

If it exists in the string pool, a reference to the memory address of the string object is returned.

The following illustration shows the same picture description.

Above, we have "firstString" pointing to the string "coderolls" in the string pool.

If we assign an equal value to another string variable, the JVM checks whether the string with that value exists in the string constant pool.

Because the string object with this value was created in the previous step, another string variable begins to reference the previously created string object instance.

The following figure shows a graphical description of "firstString" and "secondString" pointing to the "coderolls" string in the string pool.

When we create a string using the new operator, a new string object is created and stored in the Java heap space.

At the top, we can see that "firstString" and "secondString" point to "coderalls" in the string pool, while "thirdString" points to "coderalls" in the Java heap space.

If the parameter String is greater than the specified String in the dictionary, that is, after the specified String, a negative integer is returned. (String > the specified String)

Returns a positive integer if the parameter String is less than the specified String in the dictionary, that is, before the specified String. (parameter String < specified String)

Returns zero if both strings are equal in the dictionary. (parameter String = specified String)

If you want to ignore the case of two strings, use the compareToIgnoreCase() method.

I provide a program to compare strings using the compareTo () method. It also includes a case that is ignored with the compareToIgnoreCase () method.

1

/**

2

 * A Java program to compare strings using compareTo()

3

 * and compareToIgnoreCase() method.

4

 *

5

 * compareTo() compare strings lexicograpgically.

6

 *

7

 * @author Gaurav Kukade at coderolls.com

8

 */

9

10

public class CompareUsingCompareTo {

11

12

  public static void main(String[] args) {

13

    

14

    String firstString = "java";

15

    String secondString = "coderolls";

16

    String thirdString = "sql";

17

    String fourthString = "CodeRolls";

18

    

19

    System.out.println("Comparing strings using compareTo() and compareToIgnoreCase() method\n");

20

    

21

    // Using compareTo() method

22

    System.out.print("firstString.compareTo(secondString) : ");

23

    System.out.println(firstString.compareTo(secondString));

24

    

25

    System.out.print("firstString.compareTo(thirdString) : ");

26

    System.out.println(firstString.compareTo(thirdString));

27

    

28

    /*

29

     * Using compareToIgnoreCase() method to ignore

30

     * case consideration (i.e. Capital or small) of both the strings.

31

     */

32

    System.out.print("secondString.compareToIgnoreCase(fourthString) : ");

33

    System.out.println(secondString.compareToIgnoreCase(fourthString));

34

  }

35

36

}

 

Output:

1

Comparing strings using compareTo() and compareToIgnoreCase() method

2

3

firstString.compareTo(secondString) : 7

4

firstString.compareTo(thirdString) : -9

5

secondString.compareToIgnoreCase(fourthString) : 0

 


conclusion

We can compare strings using the following methods:

1. Use the equals() method: used to check whether the equals() method in the string whose value is equal contains the same character sequence.

2. Use the = = operator: = = operator to check the referential equality of two strings, that is, whether they point to the same string object.

3. Use the compareTo() method: the compareTo() method is used to check strings in dictionary order (that is, alphabetically). See a detailed article on how to compare strings in dictionary order.

Most beginner Java developers make mistakes when comparing strings. They want to check the contents of the string, but they use the = = operator to check it.

It is always recommended to use the equals () method to compare strings based on their contents.

If you have any questions about the code block given above, please write them down in the comments section below. In addition, in the comments section, let me know if you have other ways to compare two strings in Java.

 

Thank you for reading!

In addition, a complete set of java architecture mind map has been compiled recently and shared with every friend who is also studying hard~

Tags: Java jvm less SQL

Posted on Sat, 08 Feb 2020 00:28:43 -0800 by ManWithNoName