Adam
Adam

Reputation: 365

Taking a || (or) statement as input?

I have this class with a foo method and the main method where I have a few variables and a print statement.

public static boolean foo(int x, boolean b) {
    if (x < 0) {
          return true;
    }
    return !b; 
}

Say I print the following:

foo (-3, c || !c)

I'm having trouble understanding what the || is supposed to do. I declared boolean c = false in main, but I don't see how it can choose to input c (false) or !c (true). Also, side-question: the exclamation point in front of a boolean variable will just give the opposite right? i.e. if the input was false, and foo returns !b, it'd return true?

Upvotes: 2

Views: 101

Answers (5)

k_ssup
k_ssup

Reputation: 348

"||" means OR, so any x || !x will always return true, no matter whether you declare x as false or true.

Upvotes: 1

Yogendra Singh
Yogendra Singh

Reputation: 34387

If you declared c as:

 boolean c = false;// or true

then c || !c will always result into true.

so you method call foo (-3, c || !c) is nothing but equivalent to foo (-3, true)

Upvotes: 1

Swadq
Swadq

Reputation: 1837

c || !c will always be true - you might as well replace the code with

foo (-3, true)

Upvotes: 1

Matt Ball
Matt Ball

Reputation: 359986

I don't see how it can choose to input c (false) or !c (true)

It's not "choosing to input" two different possibilities. It's passing the value that is the result of evaluating c || !c, a single boolean.

Note: x || !x will always evaluate to true, for any boolean value of x.

Upvotes: 1

Prof. Falken
Prof. Falken

Reputation: 24937

It's a tautology so to speak, always true.

c || !c means: "c OR not c". One of these is always true.

Upvotes: 3

Related Questions