sorindragan
3/19/2018 - 6:13 PM

Recursive StackTrace

In a recursive method print something only once.

public class recursiveMethod {
// print something only once in a recursive method	
	public static int y = 0;
	public static boolean recursiveMethod(int x) {
		if (x > 4) {
		  return true;
		}
		Exception e = new Exception();
		e.fillInStackTrace();
		if (e.getStackTrace().length == 2) {
		  System.out.println("First Time");
		  // print this statement only the first time
		}
		y++;
		System.out.println(y);
		e.printStackTrace();
		return recursiveMethod(x + 1);
	  }

	  public static void main(String[] args) {
		recursiveMethod(0);
	  }
}