0

So I'm trying to check a list of account names to see if the username entered by the operator is in the database or not. At the moment I have:

for(int i = 0; i < rowCount; i ++){
            System.out.println("Stored in array:" + accounts[i+1]);
            System.out.println("name entered:" + LoginPage.usrname);
            if(accounts[i+1] == LoginPage.usrname){
                System.out.println("match");
            }else{
                System.out.println("no match");
            }
        }

I tried messing around with things like indexOf string and can't get anything to work. I'm sure there's a simple solution, just having trouble finding one. I don't understand why I can't compare a String array index to a String variable, seems like ti should be cake.

thermite
  • 85
  • 2
  • 10

2 Answers2

2

This is what you're looking for:

if(acounts[i+1].equals(LoginPage.usrname))

Using the == operator on Strings in Java doesn't do what you think it does. It doesn't compare the contents of the Strings, but rather their addresses in memory. The equals method compares the contents of the Strings.


As a note that may help you remember, this isn't anything particularly special about Strings. Strings are objects, and in Java, using == to compare objects of ANY type will present the same problem. If you want to compare the contents of two objects of a custom class you create, you'll have to write an equals method for that class. Strings work exactly the same.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
0

String are unique reference type that behave like value type.

At Java when trying to compare String's using == operator, Java will try to check if both of the reference are equals, Not the strings. In order to achieve a value type comparison you will be to use one of the following:

Method 1: str1.equals(str)
Method 2: str1.compareTo(str) == 0

Orel Eraki
  • 11,940
  • 3
  • 28
  • 36