Thursday, 27 July 2017

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

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...