Ťhis article is originally published at https://coderolls.com/compare-strings-in-java/

在本文中,您将学习如何比较字符串。 当您使用比较字符串时会发生什么问题等于(=)运算符。

Introduction

的串 is a special Class in Java. We use 串 regularly in Java programs, so comparing two string is a common practice in Java. In this article I tried to answer the most common questions about the string, ‘How do I compare strings in Java?’

比较字符串对身份验证,排序,引用匹配等过程非常有帮助。

我列出了3种比较Java字符串的方法。

  1. 使用等于()方法(比较内容)使用==运算符(比较对象引用)使用相比于()方法(按字典顺序比较字符串)

1. Compare strings using equals() method

这样,我正在使用。等于()String类的实例方法。 本来。等于()方法是宾语类方法,String类覆盖它。

**等于()**methodthecomparetwostringsforvalueequality,weathertheyarelogicallyequal.

等于()String类中的方法将另一个字符串作为参数,并将其与指定的字符串进行比较,然后返回真正当且仅当参数字符串不为null并且包含与指定字符串相同的字符时。

public boolean equals(Object anObject)

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.

param -
another string

returns -

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

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

public boolean equals(Object anObject)

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.

param -
another string

returns -

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

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

我给了程序来比较使用等于()下面的方法

/**
 * A Java program to compare two strings using equsls()
 * and equalsIgnoreCase() method of the String.
 * 
 * @author Gaurav Kukade at coderolls.com
 */

public class CompareUsingEquals {

  public static void main(String[] args) {
    String firstString = "coderolls";
    String secondString = "javablog";
    String thirdString = "coderolls";
    String fourthString = "CodeRolls";

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

    // Using equals() method
    System.out.print("firstString.equals(secondString) : ");
    System.out.println(firstString.equals(secondString));

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

    /*
     * Using equalsIgnoreCase() method to ignore
     * case consideration (i.e. Capital or small) of both the strings.
     */
    System.out.print("firstString.equalsIgnoreCase(fourthString) : ");
    System.out.println(firstString.equalsIgnoreCase(fourthString));
  }

}

/**
 * A Java program to compare two strings using equsls()
 * and equalsIgnoreCase() method of the String.
 * 
 * @author Gaurav Kukade at coderolls.com
 */

public class CompareUsingEquals {

  public static void main(String[] args) {
    String firstString = "coderolls";
    String secondString = "javablog";
    String thirdString = "coderolls";
    String fourthString = "CodeRolls";

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

    // Using equals() method
    System.out.print("firstString.equals(secondString) : ");
    System.out.println(firstString.equals(secondString));

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

    /*
     * Using equalsIgnoreCase() method to ignore
     * case consideration (i.e. Capital or small) of both the strings.
     */
    System.out.print("firstString.equalsIgnoreCase(fourthString) : ");
    System.out.println(firstString.equalsIgnoreCase(fourthString));
  }

}

输出:

Comparing strings using equals() and equalsIgnoreCase() method

firstString.equals(secondString) : false
firstString.equals(thirdString) : true
firstString.equalsIgnoreCase(fourthString) : true

Comparing strings using equals() and equalsIgnoreCase() method

firstString.equals(secondString) : false
firstString.equals(thirdString) : true
firstString.equalsIgnoreCase(fourthString) : true

2. Compare strings using == operator

在字符串中**==**operatorisusedtocomparingthereferenceofthegivenstrings,whethertheyarereferringtothesameobjects.

当您使用比较两个字符串时==操作符,它将返回真正如果字符串变量指向相同的java对象,则它将返回假。

我给了一个Java程序进行比较==下面的运算符

/**
 * A Java program to compare strings using == operator.
 * 
 * == operator ckecks weather both the strings referring
 * to the same String Object.
 * 
 * @author Gaurav Kukade at coderolls.com
 */

public class CompareUsingEqualsToOperator {

  public static void main(String[] args) {

    String firstString = "coderolls";
    String secondString = "javablog";
    String thirdString = "coderolls";

    // creating new String object with the same value as firstString or thirdString
    String fourthString =  new String("coderolls");

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

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

    /*
     * Here firstString and thirdString is referring to the same String object
     * hence it will print 'true'.
     */
    System.out.print("firstString == thirdString : ");
    System.out.println(firstString == thirdString);

    /*
     * Here firstString and fourthString have same value
     * but they are referring to the different String object.
     * 
     * hence it will print 'false'
     */
    System.out.print("firstString == fourthString : ");
    System.out.println(firstString == fourthString);
  }

}

/**
 * A Java program to compare strings using == operator.
 * 
 * == operator ckecks weather both the strings referring
 * to the same String Object.
 * 
 * @author Gaurav Kukade at coderolls.com
 */

public class CompareUsingEqualsToOperator {

  public static void main(String[] args) {

    String firstString = "coderolls";
    String secondString = "javablog";
    String thirdString = "coderolls";

    // creating new String object with the same value as firstString or thirdString
    String fourthString =  new String("coderolls");

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

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

    /*
     * Here firstString and thirdString is referring to the same String object
     * hence it will print 'true'.
     */
    System.out.print("firstString == thirdString : ");
    System.out.println(firstString == thirdString);

    /*
     * Here firstString and fourthString have same value
     * but they are referring to the different String object.
     * 
     * hence it will print 'false'
     */
    System.out.print("firstString == fourthString : ");
    System.out.println(firstString == fourthString);
  }

}

输出:

Comparing strings using == operator 

firstString == secondString : false
firstString == thirdString : true
firstString == fourthString : false

Comparing strings using == operator 

firstString == secondString : false
firstString == thirdString : true
firstString == fourthString : false

Problem with using == operator for string comparison

大多数初学者Java开发人员通过使用==运算符比较两个字符串来犯此错误。

从逻辑上讲,他们必须检查两个字符串是否包含相同的字符序列。

在Java String中,==运算符,用于检查字符串对象和等于()用于检查两个字符串的值相等性的方法。

==–检查引用是否相等

等于()–检查值是否相等

当我们为字符串变量分配一个字符串值时,JVM将检查字符串池中是否已经存在具有相等值的字符串。 如果它在字符串池中不存在,它将被添加到常量池中,并返回对该字符串对象的引用。

如果它存在于字符串池中,则返回对该字符串对象的内存地址的引用。

下图显示了相同的图片说明。

Java项目test测试包 java中test_字符串

指向字符串池中“ coderolls”字符串的“ firstString”

如果我们将相等的值分配给另一个字符串变量,则JVM将检查具有该值的字符串是否存在于字符串常量池中。

由于具有该值的字符串对象已在上一步中创建。 另一个字符串变量开始引用以前创建的字符串对象实例。

下图显示了相同的图片说明

Java项目test测试包 java中test_java_02

指向字符串池中“ coderolls”字符串的“ firstString”和“ secondString”

当我们使用新 operator, a 新 string object is created and stored in the Java heap space.

Java项目test测试包 java中test_字符串_03

“ firstString”和“ secondString”指向字符串池中的“ coderolls”字符串,“ thirdString”指向java堆空间中的“ coderolls”。

3. Compare strings using compareTo() method

相比于()方法用于按字典顺序比较两个字符串。 即按字母顺序

相比于()方法将参数字符串的字符序列与指定字符串的字符序列进行比较。

Java项目test测试包 java中test_System_04

显示参数字符串和指定的字符串。

如果参数字符串在字典上大于指定的字符串,则返回负整数。 即参数字符串是否在指定字符串之后。 (参数String>指定的String)

如果参数字符串在字典上小于指定的字符串,则返回正整数。 即参数字符串是否在指定字符串之前。 (参数String <指定的String)

如果两个字符串在字典上都相等,则返回零。 (参数String =指定的String)

如果要忽略两个字符串都使用的情况compareToIgnoreCase()方法。

我给了一个程序来比较使用相比于()方法。 它还包括一个忽略情况的案例compareToIgnoreCase()方法。

* A Java program to compare strings using compareTo()
 * and compareToIgnoreCase() method.
 * 
 * compareTo() compare strings lexicograpgically.
 * 
 * @author Gaurav Kukade at coderolls.com
 */

public class CompareUsingCompareTo {

  public static void main(String[] args) {

    String firstString = "java";
    String secondString = "coderolls";
    String thirdString = "sql";
    String fourthString = "CodeRolls";

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

    // Using compareTo() method
    System.out.print("firstString.compareTo(secondString) : ");
    System.out.println(firstString.compareTo(secondString));

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

    /*
     * Using compareToIgnoreCase() method to ignore
     * case consideration (i.e. Capital or small) of both the strings.
     */
    System.out.print("secondString.compareToIgnoreCase(fourthString) : ");
    System.out.println(secondString.compareToIgnoreCase(fourthString));
  }

}

 * A Java program to compare strings using compareTo()
 * and compareToIgnoreCase() method.
 * 
 * compareTo() compare strings lexicograpgically.
 * 
 * @author Gaurav Kukade at coderolls.com
 */

public class CompareUsingCompareTo {

  public static void main(String[] args) {

    String firstString = "java";
    String secondString = "coderolls";
    String thirdString = "sql";
    String fourthString = "CodeRolls";

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

    // Using compareTo() method
    System.out.print("firstString.compareTo(secondString) : ");
    System.out.println(firstString.compareTo(secondString));

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

    /*
     * Using compareToIgnoreCase() method to ignore
     * case consideration (i.e. Capital or small) of both the strings.
     */
    System.out.print("secondString.compareToIgnoreCase(fourthString) : ");
    System.out.println(secondString.compareToIgnoreCase(fourthString));
  }

}

输出:

Comparing strings using compareTo() and compareToIgnoreCase() method

firstString.compareTo(secondString) : 7
firstString.compareTo(thirdString) : -9
secondString.compareToIgnoreCase(fourthString) : 0

Comparing strings using compareTo() and compareToIgnoreCase() method

firstString.compareTo(secondString) : 7
firstString.compareTo(thirdString) : -9
secondString.compareToIgnoreCase(fourthString) : 0

I have written a detailed article on how to compare strings lexicographically in java. In this article, I have also created a user-defined method to compare two strings lexicographically.

Conclusion

我们可以使用下面给出的方法比较字符串

  1. Using equals() method : equals() method in the strings used to check the string value equality whether they contain the same character sequence.
  2. Using == operator : == operator used to check the reference equality of the two strings, whether they are pointing towards the same string object.
  3. Using compareTo() method : compareTo() method used to check the strings lexicographically. I.e alphabetically. Check the detailed articles on How to compare strings lexicographically.

大多数初学者Java开发人员在比较字符串时都会犯错。 他们实际上想要检查字符串的内容,但是他们使用==操作员进行检查。

总是建议使用等于()根据字符串内容比较字符串的方法。

如果您对上面给出的代码块有任何疑问,请在下面的注释部分写下来。 也。 让我知道您是否还有其他方法可以在注释部分中比较java中的两个字符串。

Ťhis article is originally published at https://coderolls.com/compare-strings-in-java/

Related Article

  • How To Reverse A String In Java (5 ways)
  • How To Compare Two Strings Lexicographically In Java
  • Introduction to Java Technology (Language and Platform)