What is the difference between the equal() method of String class and the equivalent comparison operator (==) in Java?

Asked 2 years ago, Updated 2 years ago, 49 views

Below is the source code that separates a string into tokens, stores it in an array, and compares the strings. Why doesn't it work?

public static void main(String...aArguments) throws IOException {

    String usuario = "Jorman";
    String password = "14988611";

    String strDatos = "Jorman 14988611";
    StringTokenizer tokens = new StringTokenizer(strDatos, " ");
    int nDatos = tokens.countTokens();
    String[] datos = new String[nDatos];
    int i = 0;

    while (tokens.hasMoreTokens()) {
        String str = tokens.nextToken();
        datos[i] = str;
        i++;
    }

    //System.out.println (usuario);

    if ((datos[0] == usuario)) {
        System.out.println("WORKING");
    }
}

java string

2022-09-22 21:41

1 Answers

The string.equals(Object other) method allows you to compare strings of string objects. However, you cannot compare string data with the == operator.

The equals() method compares strings of string objects, while the == operator checks that the object has the same reference value.

There are two ways to create a string object: the first is to use the string literal, and the second is to use the constructor of the String class. When you create a string using a string literal, if an object with the same string exists, the string object is created in the form of sharing the reference value of an existing object. In this case, you can use the '==' operator to get the result "two strings are the same." But this is not a good way. Therefore, it is recommended that you always compare strings using the equals() method as shown below.

if (usuario.equals(datos[0])) {
    ...
}

Note: The example above compares the data from the usuario object with the datos[0] object. If you apply this, you can compare all strings in the datos array with the usuario string while repeating. In this case, usuario must be a String class variable with a non-null reference value, and you should also be careful about the range of indexes when accessing strings in an array. Otherwise, NullPointerException or ArrayOutOfBoundsException may occur.


2022-09-22 21:41

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.