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
  • 37,241
  • 25
  • 195
  • 267
nr5
  • 4,228
  • 8
  • 42
  • 82

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,501
  • 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,914
  • 5
  • 28
  • 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
  • 202,709
  • 46
  • 318
  • 350
2

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

Anuj Balan
  • 7,629
  • 23
  • 58
  • 92
1

no, strings should be compared like this:

publisher.equals("Niho books")
Sirko
  • 72,589
  • 19
  • 149
  • 183
mooonli
  • 2,355
  • 4
  • 23
  • 32
1

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

dontcare
  • 935
  • 3
  • 16
  • 34