Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String.equals versus == [duplicate]

Tags:

java

string

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");     } } 
like image 583
franvergara66 Avatar asked Apr 20 '09 08:04

franvergara66


People also ask

Can you compare strings with ==?

You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.

What is difference between == and equals in string?

In simple words, == checks if both objects point to the same memory location whereas . equals() evaluates to the comparison of values in the objects. If a class does not override the equals method, then by default, it uses the equals(Object o) method of the closest parent class that has overridden this method.

What happens if you use == for strings?

In String, the == operator is used to comparing the reference of the given strings, depending on if they are referring to the same objects. When you compare two strings using == operator, it will return true if the string variables are pointing toward the same java object. Otherwise, it will return false .

Which is better == or equals?

Answering to the point “There is no difference between equality comparison using “==” and “Equals()”, except when you are comparing “String” comparison.


1 Answers

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.

like image 157
Alnitak Avatar answered Oct 11 '22 17:10

Alnitak