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]
.
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.
The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.
The Java equals() method compares two string objects, the equality operator == compares two strings, and the compareTo() method returns the number difference between two strings. String comparison is a crucial part of working with strings in Java.
The == operator can't compare conflicting objects, so at that time the compiler surrenders the compile-time error. The equals() method can compare conflicting objects utilizing the equals() method and returns “false”.
Don't compare strings with ==
.
Use
if (string1.equals("other")) {
// they match
}
Compare strings like that
if(employeeId.equals(employeeNumber[i]) {
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With