0

I want to print tabs recursively but the code is generating an error.

public String Tab(int temp) {  
    if(temp==0)  
        return null;  
    else {  
        return ("\t"+Tab(temp--));    
    }
}
Collin
  • 11,977
  • 2
  • 46
  • 60
boson
  • 9
  • 2

3 Answers3

1

Change your line return ("\t"+Tab(temp--)); to return ("\t" + Tab(--temp));

Check

what is the difference between i++ & ++i in for loop (Java)?

i++ vs ++i as operation (NO loop)

Community
  • 1
  • 1
Vicky Thakor
  • 3,847
  • 7
  • 42
  • 67
  • The links explain what the difference is between the two, so implies what's wrong with the code, but it would be good to briefly explain this difference in the answer itself, and **explicitly** explain what the problem is with using `temp--`. Also, actually `temp-1` would be way better - in this case it doesn't make a difference, but you're going to shoot yourself in the foot eventually if you're used to modifying a variable while passing it to a function. – Bernhard Barker Jul 13 '15 at 13:59
1

if you use return ("\t"+Tab(temp--)); Tab method always will take first temp value.it will be Infinite loop. For exapmle;Tab(5); 5 5 5 5 . . .

tarikfasun
  • 314
  • 6
  • 16
  • To the semi-untrained eye, `temp--` looks like it should work, so you may want to explain what exactly that part specifically does, and how to fix the issue. – Bernhard Barker Jul 13 '15 at 14:40
0

You must be getting a stack overflow error.

return ("\t"+Tab(temp--));

The above line causes an infinite loop, as the temp variable is reduced after the completion of the method.

The value of temp is passed and not the reference. You should just simplify the code as

return ("\t"+Tab(temp-1));

Also read Is Java "pass-by-reference" or "pass-by-value"?

Community
  • 1
  • 1
Aditya
  • 2,148
  • 3
  • 21
  • 34
  • I'm not sure if the pass-by-reference/value discussion is particularly relevant here - if Java were passing by reference here, assuming the code would compile, `Tab(temp--)` would most likely cause `temp` to decrease and result in a temporary variable with `temp`'s value before decreasing being passed to `Tab`, resulting in the same infinite loop. – Bernhard Barker Jul 13 '15 at 14:47
  • The second part is just a clarification as to why the easier to understand *temp-1* can be used here to the same effect, as *--temp* does not provide any advantage even assuming a more complicated method implementation. – Aditya Jul 14 '15 at 06:31