S Fasda
S Fasda

Reputation: 33

How can I simplify this if-else into one statement?

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

Answers (4)

nandal
nandal

Reputation: 2634

Use the following:

result = a ? isEmpty && !b : !b;

Upvotes: 0

ninosanta
ninosanta

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

MinA
MinA

Reputation: 405

You can use ternary operator:

result = a ? isEmpty && !b : !b;

Upvotes: 1

Eran
Eran

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

Related Questions