Search code examples
javaoptimizationshort-circuiting

Java Optimization


I want to know if java optimize this code? Does it use Short-circuit (http://en.wikipedia.org/wiki/Short-circuit_evaluation) evaluation?

boolean c5 = A || B
boolean c4 = C && D
boolean c3 = E || F
boolean c2 = G && H

if ((c5) && (c4) && (c3) && (c2)){
  //execute operation
}

Solution

  • Yes. It does use Short-circuit evaluation (represented by && and || operators). Your condition

    (c5) && (c4) && (c3) && (c2)
    

    is essentially same as

    (A || B) && (C && D) && (E || F) && (G && H)
    

    which is same as

    (A || B) &&  C && D  && (E || F) &&  G && H
    

    so

    • if A will be evaluated as true then B will not be tested.
    • if A and B will be false then entire expression will be equal to

      false && C && D && (E || F) && G && H
      

      which is always false (because false && whatever is always false) so C && D && (E || F) && G && H will not be evaluated

    and so on, and on...