-2

Let's say I have boolean show and difficult method public boolean isArraySorted( ).
I want to know how if statement works, and if checking order means anything. Basicly what I want to is if( !show && isArraySorted( ) ) is faster than if( isArraySorted( ) && !show ).

As far as I know statements are checked one after another until one fails, right ? So keeping this in mind if( !show && isArraySorted( ) ) should be faster ( at least slightly ). Please, correct me if I'm wrong.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Sw3das
  • 157
  • 1
  • 12
  • Logical operator short circuiting is happening with `&&`. And yes, the order matters. Therefore, you also see thousands of examples such that `if (objVariable != null && objVariable.doSomething() )`. – izce Nov 14 '15 at 09:20
  • 3
    The more **boldface** you use in your writing, the harder it is to read, just FWIW. – T.J. Crowder Nov 14 '15 at 09:28
  • Hint for the net time: why don't you implement two methods that log to the console that they've been called and return a boolean value. Then call them two combinations of such an expression and see what's being logged. Protip: use a debugger and step into those methods, don't struggle writing console statements. Further: your question is not limited to `if` statements, the same applies for `bool result = a || b;`. Finally: for or-statements if the lefthandside is true, there's no need to evaluate the righthandside. – try-catch-finally Nov 14 '15 at 10:11

1 Answers1

1

Basicly what I want to is if( !show && isArraySorted( ) ) is faster than if( isArraySorted( ) && !show ).

Let's leave speed off to the side. if( !show && isArraySorted( ) ) won't call isArraySorted if show is true, and will if it's false. (Because you're using !show, otherwise it would be the other way around.)

As far as I know statements are checked one after another until one fails, right ?

Sort of, yes. The logical operators (&& and ||) are short-circuited. That means that they evaluate their left-hand operand and, if that operand is enough that they know their result, they don't evaluate the right-hand operand. So for &&, if the left-hand is false, there's no need to evaluate the right-hand. For ||, if the left-hand is true, there's no need to evaluate the right-hand.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875