1

i am trying to print all size n binary numbers, for example if size is 3 , i want to print all numbers from 0 to (2^3)-1 in binary form, below if my code implementating, it prints 000 and gives me this error

"Exception in thread "main" java.lang.StackOverflowError
at java.lang.String.getChars(String.java:854)
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:391)
at java.lang.StringBuilder.append(StringBuilder.java:119)
at java.lang.StringBuilder.<init>(StringBuilder.java:93)
at NBinary.tobinary(NBinary.java:11)
at NBinary.tobinary(NBinary.java:12)". 

String temp = str+x; is line 11
tobinary(temp, size); is line 12

below is my code

public class NBinary {

static int arr[] = {0,1};
static void tobinary(String str,int size){

    if(str.length() == size){
        System.out.println(str);
    }
    for(int x : arr){
        String temp = str+x;
        tobinary(temp, size);
    }


}

public static void main(String[]args){

    tobinary("", 3);

}

}

please help me find the error. thanks

2
  • Does it have to use recursion? Commented Nov 2, 2014 at 17:33
  • 1
    Did you googled StackOverflowError? Commented Nov 2, 2014 at 17:42

1 Answer 1

1

One problem is that you are not giving any Recursion Termination condition. So the function recurses infinitely. No condition is there to cease the calling.

That is why the stack allocated for the function call runs out of space and you get StackOverflowError.

See more here:

http://docs.oracle.com/javase/7/docs/api/java/lang/StackOverflowError.html

What is a StackOverflowError?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.