0

I have an if statement where one of two conditions can be met, but I don't want to use nested if.

For example, what I would like is to have;

String s;

if(s == "foo" || "bar") {
    // true
} else {
    // false
}

However, operator || cannot be applied to a String.

Is there any way around this?

Jonny Wright
  • 1,100
  • 4
  • 20
  • 36

6 Answers6

3

You can use regex:

String s = "foo";
if (s.matches("foo|bar"))
    // true
else
    // false
shmosel
  • 45,768
  • 6
  • 62
  • 130
thibsc
  • 3,435
  • 2
  • 18
  • 33
  • 1
    It should be noted that `String.matches()` internally calls `Pattern.matches()`, which again calls `Pattern.compile()`, making it quite a heavy operation (compared to a simple `equals()` comparison). Just something to keep in mind if the code in question is called really frequently. – Mick Mnemonic Mar 10 '17 at 23:34
2

equals() method should be used to compare Strings.

if statements evaluate as booleans (true or false). Also, reverse the order of your equals comparison to avoid NPE's.

String s;

if ("foo".equals(s) || "bar".equals(s)) {

} else {

}
Ousmane D.
  • 52,579
  • 8
  • 80
  • 117
1

Use equals to compare strings in Java:

String s;

if(s.equals("foo") || s.equals("bar")) {
    // true
} else {
    // false
}

See How do I compare strings in Java?

Community
  • 1
  • 1
runcoderun
  • 431
  • 6
  • 10
1

Just an alternative to those already given:

if (Arrays.asList("foo", "bar").contains(s)) {
    // true
} else {
    // false
}

Of course, you can build the collection beforehand:

Set<String> wordsToMatch = new HashSet<>(Arrays.asList("foo", "bar"));

and then use it over and over:

if (wordsToMatch.contains(s)) {
  // ...
Andy Turner
  • 131,952
  • 11
  • 151
  • 228
0

You're comparing the Strings incorrectly.

below shows how to compare Strings using equals() method of the String class.

String s;

if(s.equals("foo") || s.equals("bar")) {
    // true
} else {
    // false
}

Further reading regarding how to compare Strings?

Community
  • 1
  • 1
Ousmane D.
  • 52,579
  • 8
  • 80
  • 117
-1
if(s.equals("foo") || s.equals("bar")){
   //Your Code
}
Ousmane D.
  • 52,579
  • 8
  • 80
  • 117
Sahir
  • 199
  • 1
  • 1
  • 9