0

Hi I have a strange problem with my code and I cant figure out whats wrong.

I have:

ArrayList called players

Class: Player

Class: Name

Player class contains Name class which contains 3 Strings FirstName MiddleName LastName

The problem is when im trying to do

For( int i = 0; i < players.size(); i++)
{
    if( players.get(i).getName().getFirst() == "First1")
    {
         // Some Code 
    }

    System.out.printf(players.get(i).getName().getFirst());
}

If statement is never true, weird thing is when im using system.out to check as below

System.out.printf(players.get(i).getName().getFirst());

it returns:

First1 First2 First3

getName() method returns object name and getFirst() returns String FirstName

Any ideas where the problem is?

2 Answers2

4

Never EVER EVER EVER compare Strings with ==. use .equals() instead. "==" compares references of Strings. .equals() compares actual values.

TheLostMind
  • 35,966
  • 12
  • 68
  • 104
3

To compare String objects in java use .equals() method instead of "==" operator. If you want ignore the case use .equalsIgnoreCase() method.

For String comparison you should use like this

if( "First1".equals(players.get(i).getName().getFirst()))
Prabhakaran Ramaswamy
  • 25,706
  • 10
  • 57
  • 64