2

Possible Duplicate:
How do I compare strings in Java?

I have this code:

    System.out.println(staff.getEmail().length());
    System.out.println(staff.getEmailList());
    if ((staff.getEmail().length() > 0) && (staff.getEmailList() == "Y")) {
        System.out.println(staff.getEmail());

This is the output on my eclipse console:

12
Y

My problem is that even though both conditions in the if statement are satisfied, my program can never get to the last line of code above (System.out.println(staff.getEmail())). I don't any error too.

Any ideas what could I've done wrong? thanks :)

Community
  • 1
  • 1
mrjayviper
  • 2,258
  • 11
  • 46
  • 82

3 Answers3

7

You should use String.equals() and not operator == for string equality in java.

staff.getEmailList() == "Y" should be converted into "Y".equals(staff.getEmailList())

The reason for it is operator== checks for identity. If the two operands are the same object (referencing to the same object), while equals() checks for equality - if the two operands equal each other.

amit
  • 175,853
  • 27
  • 231
  • 333
0

Here you compare not actualy string values, but their references (pointers in C-language).

(staff.getEmailList() == "Y")

You should do this

(staff.getEmailList().equals("Y"))
fycth
  • 3,410
  • 25
  • 37
0

When you do the comparison staff.getEmailList() == "Y" you are asking if the two strings are the same String instances, not if they have the same value. YOu you should staff.getEmailList().equals("Y") instead.

John Percival Hackworth
  • 11,395
  • 2
  • 29
  • 38