1

Possible Duplicate:
How do I compare strings in Java?

I am trying to compare a striong using || operator..

if(publisher != "Niho books" || publisher != "Diamond Comics" )

what is wrong in this ? Strings can't be compared like this ??

Cœur
  • 34,719
  • 24
  • 185
  • 251
nr5
  • 4,010
  • 7
  • 40
  • 76

6 Answers6

6

This should work:

if (!"Niho books".equals(publisher) || !"Diamond Comics".equals(publisher))

http://www.leepoint.net/notes-java/data/strings/12stringcomparison.html

  • Dont use ==, != for String compare
  • equals() can go after publisher or after your string (publisher.equals() or "string".equals()) , I think the second one is maybe better because if your publisher is a null you wont get nullpointer exception. But do however you like/is right for you
sabisabi
  • 1,461
  • 5
  • 22
  • 40
4

In this way you are not comparing contents... you are comparing references.

If you want to compare contents then use

publisher.equals("Niho books")

or 

publisher.equalsIgnoreCase("Niho books")
Pramod Kumar
  • 7,696
  • 5
  • 27
  • 37
3

Don't use != or == to compare strings in Java. Use .equals() instead. The != and == operators compare references, not the content of objects.

if (!publisher.equals("Niho books") || !publisher.equals("Diamond Comics"))
Jesper
  • 195,030
  • 44
  • 313
  • 345
2

In strings, equals() tests the equality of value where as != and == tests equality of the references.

Anuj Balan
  • 7,419
  • 23
  • 53
  • 90
1

no, strings should be compared like this:

publisher.equals("Niho books")
Sirko
  • 69,531
  • 19
  • 142
  • 174
mooonli
  • 2,275
  • 4
  • 21
  • 31
1

http://www.devdaily.com/java/edu/qanda/pjqa00001.shtml read this

dontcare
  • 925
  • 3
  • 16
  • 34