Consider a class which prints out the count down sequence(excluding 0) of a passed in number as below i.e if 5 is passed, it should print 5, 4, 3, 2 and 1.

public class CountdownPrinter {
  public void print(int i) {
    if (i < 0) {
      throw new IllegalArgumentException("Passed value should be a positive number");
    }

    if (i == 0) {
      return;
    }

    System.out.println(i);

    this.print(i--);
  }

  public static void main(String[] args) {
    CountdownPrinter countdownPrinter = new CountdownPrinter();
    countdownPrinter.print(5);
  }
}

Does the above class work as expected?

Bam, the stack explodes.

The culprit is the line “this.print(i–)”, the post decrement operator.

The above line is as good as

this.print(i);
i = i - 1;

How do you fix this?

this.print(–i) or this.print(i – 1)

My opinion on this is, combining decrement operators and method invocation is not a good practice. Use the subtraction mathematical operator to achieve this.

Advertisements