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,119
  • 4
  • 20
  • 38

6 Answers6

3

You can use regex:

String s = "foo";
if (s.matches("foo|bar"))
    // true
else
    // false
shmosel
  • 49,289
  • 6
  • 73
  • 138
thibsc
  • 3,747
  • 2
  • 18
  • 38
  • 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.
  • 54,915
  • 8
  • 91
  • 126
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
  • 531
  • 6
  • 11
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
  • 137,514
  • 11
  • 162
  • 243
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.
  • 54,915
  • 8
  • 91
  • 126
-1
if(s.equals("foo") || s.equals("bar")){
   //Your Code
}
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Sahir
  • 329
  • 1
  • 2
  • 9