-6

Possible Duplicate:
How do I compare strings in Java?

Someone can tell me why this condition

if (lista.getString(0)=="username")

do not return true? I've used to try

if (lista.getString(0)==lista.getString(0))

and dont work, and i have understand that is a language problem.

Community
  • 1
  • 1
Axiomatic.it
  • 63
  • 2
  • 10

4 Answers4

2

== tests for reference equality.

.equals tests for value equality.

Threfore you should use:

if (lista.getString(0).equals("username"))

See How do I compare strings in Java?

Community
  • 1
  • 1
Darren
  • 68,902
  • 24
  • 138
  • 144
1

For String comparison always use equals().

if (lista.getString(0).equals("username"))

Using == , you will end up comparing references, not values.

A simple snippet to clarify further:

String s1 = "Hello";
String s2 = new String(s1);
System.out.println(s1.equals(s2)); // true because values are same
System.out.println((s1 == s2)); // false because they are different objects
Kazekage Gaara
  • 14,972
  • 14
  • 61
  • 108
0

From Java Techniques

Since Strings are objects, the equals(Object) method will return true if two Strings have
the same objects. The == operator will only be true if two String references point to the  
same underlying String object. Hence two Strings representing the same content will be  
equal when tested by the equals(Object) method, but will only be equal when tested with 
the == operator if they are actually the same object.

Use

if (lista.getString(0).equals("username"))
Girish Rao
  • 2,609
  • 1
  • 20
  • 24
0

The correct way to compare objects is with,

object1.equals(object2)

And String is an object in Java, so it implies same for String too

s1.equals(s2)

eg :

if (lista.getString(0).equals("username"))
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75