0

I wrote up a postfix calculator for boolean expressions given that it was in postfix form. The first time I went about writing it, I used the expression

s.add(s.pop() [operation] s.pop());

where s is my stack and the operation is and, xor, or or.

For some reason, the pop methods did not seem to peel of the value from the stack, so I instead rewrote this operation using two boolean variables: b1 and b2. These variables contained the popped values which then are passed through the add method with the proper operation.

if(str.equals("or")){
    boolean b1 = s.pop();
    boolean b2 = s.pop();
    s.add(b1 || b2);
    //out.println(s);
}

Why couldn't I use the first statement mentioned?

Ian L
  • 154
  • 8
  • 6
    Please post a [mcve]. – OldProgrammer May 29 '17 at 21:01
  • How are you declaring the stack? – Zachary Weixelbaum May 29 '17 at 21:03
  • Stack s = new Stack();. It is supposed to be reassigned to a new stack each time it looks at a new expression, but I know for sure that part works. – Ian L May 29 '17 at 21:05
  • 7
    when using ``||`` and the left value is ``true`` (which happens when the left ``s.pop()`` returns true), the right side is not evaluated. When the right side is a method call such as ``s.pop()``, this leads to the value remaining on the stack since ``pop()`` is not called. – f1sh May 29 '17 at 21:06
  • @f1sh Thank you so much! – Ian L May 29 '17 at 21:06
  • @IanLimarta you're welcome. Omitting the evaluation of un-needed values (which is what happens here) is called short-circuiting. If you want to read more about it: https://stackoverflow.com/questions/8759868/java-logical-operator-short-circuiting – f1sh May 29 '17 at 21:09
  • "Why couldn't I use the first statement mentioned?" because `and`, `xor` or `or` are not valid operators in Java, use `&`, `^` and `|` instead... [:-| – user85421 May 29 '17 at 21:21
  • 2
    @f1sh you should write that as an answer :) – Kevin Anderson May 29 '17 at 23:55

1 Answers1

2

Copied from my comments since it's now considered an answer:

When using || and the left value is true (which happens when the left s.pop() returns true), the right side is not evaluated. When the right side is a method call such as s.pop(), this leads to the value remaining on the stack since pop() is not called.

Omitting the evaluation of un-needed values (which is what happens here) is called short-circuiting. If you want to read more about it: Java logical operator short-circuiting

f1sh
  • 11,489
  • 3
  • 25
  • 51