5

Possible Duplicate:
String is not equal to string?

I'm new to java and I can't figure out what's wrong with this code block. I know the array isn't null I'm testing it elsewhere. Maybe there is a syntax problem I'm used to program in c#.

     Scanner input = new Scanner(System.in);
     System.out.println("Enter ID :");
     String employeeId = input.nextLine();
     int index =  -1;
     for(int i = 0 ; i < employeeCounter ; i++)
     {
         if(employeeId == employeeNumber[i])
         {
           index = i;
         }
     }

     if(index == -1)
     {
         System.out.println("Invalid");
         return;
     }

I always get to the 'Invalid' part. Any idea why ? Thanks in advance


employeeNumber[0] is "12345" employeeId is "12345" but I can,t get into the first if statement although employeeId IS equal to employeeNumber[0].

Community
  • 1
  • 1
phadaphunk
  • 12,785
  • 15
  • 73
  • 107

7 Answers7

12

Don't compare strings with ==.

Use

if (string1.equals("other")) {
    // they match
}
Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
John3136
  • 28,809
  • 4
  • 51
  • 69
6

Compare strings like that

if(employeeId.equals(employeeNumber[i]) {

}
juergen d
  • 201,996
  • 37
  • 293
  • 362
4

As others have pointed - full code will be helpful, but my guess would be this line of the code:

if(employeeId == employeeNumber[i])

You don't compare 2 strings by using ==. Use equals() or equalsIgnoreCase() instead. == only checks for object equality i.e. are employeeId and employeeNumber referencing to the same object in memory. So, for objects always use the equals() method..for Strings you can also use equalsIgnoreCase() for a case insensitive match. == should be used on primitive types like int, long etc.

legendofawesomeness
  • 2,901
  • 2
  • 19
  • 32
3

When you use == with two string, it compares pointer addresses You should use firststring.equals(secondstring) in order to compare two strings

omartin
  • 135
  • 1
  • 16
2

Use equals() method to compare Strings

if(employeeId.equals(employeeNumber[i])){}
Shashank Kadne
  • 7,993
  • 6
  • 41
  • 54
2

When you compare strings, use String1.equals(String2); This should give you the result

beachwood23
  • 431
  • 2
  • 5
  • 14
0

"==" checks whether the reference for two objects are same. But equals() method checks whether the content is same or different.

Dheeraj Joshi
  • 3,057
  • 8
  • 38
  • 55