-1

The code is from https://leetcode.com/

How does opened++ > 0 work in the if statement below?

I'm new to Java and have never seen using increment and > in the same conditional statement.

public String removeOuterParentheses(String S) {
    StringBuilder s = new StringBuilder();
    int opened = 0;
    for (char c : S.toCharArray()) {
        if (c == '(' && opened++ > 0) s.append(c);
        if (c == ')' && opened-- > 1) s.append(c);
    }
    return s.toString();
}
gwen
  • 95
  • 8

2 Answers2

3

The ++ operator can be used either before or after a variable. When used before, it increments the variable, then evaluates the statement. If placed after, it evaluates the statement, then increments. So in this case, it checks if opened > 0, and then after it checks that, it increments opened.

2

In Java, the post increment operator first evaluates the statement and then increments the value.

For example,

<pre>
  int i=4;
  if(i++==4) System.out.println("In if statement evaluation i value was: "+(i-1));// prints i value was (5-1) = 4
  else System.out.println("If the if statement had pre increment operator, this line would have been printed");
</pre>