Reputation: 33
How can I simplify the following code to one line (without the if-else
statement)?
public static void main(String[] args)
{
boolean result;
boolean a = false;
boolean b = false;
boolean isEmpty = false;
if (a) {
result = isEmpty && !b;
System.out.println("if " + (isEmpty && !b));
} else {
System.out.println("else " + !b);
result = !b;
}
System.out.println(result);
}
Upvotes: 3
Views: 134
Reputation: 67
I think that what you are searching for is the ternary operator
In fact, you could summarize that if-else statement with something like this (but without the println):
result = (a ? isEmpty && !b : !b);
System.out.println(result + "\n");
Upvotes: 1
Reputation: 394156
If a
is true
, you must check that isEmpty
AND !b
are both true
. If a
is false
(or !a
is true
), it's enough to check that !b
is true
.
Therefore you can replace the logic of the if statement with:
result = !b && (isEmpty || !a);
Upvotes: 7