Thursday 11 July 2019

java - String.equals versus ==





This code separates a string into tokens and stores them in an array of strings, and then compares a variable with the first home ... why isn't it working?



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");
}
}


Answer



Use the string.equals(Object other) function to compare strings, not the == operator.



The function checks the actual contents of the string, the == operator checks whether the references to the objects are equal. Note that string constants are usually "interned" such that two constants with the same value can actually be compared with ==, but it's better not to rely on that.



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



NB: the compare is done on 'usuario' because that's guaranteed non-null in your code, although you should still check that you've actually got some tokens in the datos array otherwise you'll get an array-out-of-bounds exception.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...