Convert From Decimal to Binary with Recursion in Java.

Recursion has always been a confusing topic in programming. In this tutorial I’ll try to make it simple to understand, and for that I’ll use a simple method that converts decimal numbers 10 to binary recursively.

here’s the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public class Tester2 {
 
    static String strBinary;
 
    private static String toBinary(int num)
    {
        if(num < 2)
        {
            strBinary = "" + num;
            return strBinary;
        }
        else
        {
            if(num != 0)
            {
                toBinary(num/2);
                strBinary += ""+num%2;
            }
        }
        return strBinary;
    }   
 
    public static void main(String[] args) {        
 
     System.out.println(toBinary(10));               
 
    }
}

At first the recursive call might be confusing, but all it does it calls itself over, and every time dividing the variable num by 2. What happens with the line following the recursive call? Well, for now that line is on hold until the base case is true and the recursive call gets a return back; then, strBinary += “”+num%2; executes all the num/2 that are waiting in memory.
1st recursive call “num = 10” stored in memory
2nd recursive call “num = 5” stored in memory
3rd recursive call “num = 2” sotred in memory. Here the recursive call gets the return b/c toBinary(num/2) = 1 so the expression (num < 2) evaluates to true; therefore executes "return strBinary."Now strBinary += ""+num%2; start to excute for all those variable stored in memory starting from the most resent recursive call which is "num = 2" and works its way to the 1st recursive call which is "num = 10" if after this you still confuse, I suggest you print the variable just before the recursive call so you know what its value is, or you can also use the debugger in your IDE. This second option makes much clear as you can stop right before the recursive call and look at all variables. In order to stop before the recursive call click on the line number to place a stop sign, so the debugger knows you want to pause there, then use the “Step in” button to continue.

Share This!

1 thought on “Convert From Decimal to Binary with Recursion in Java.

  1. Reda

    Hi admin, i found this post on 12 spot in google’s search results.
    You should decrease your bounce rate in order
    to rank in google. This is major ranking factor nowadays.
    There is very handy wordpress plugin which can help you.
    Just search in google for:
    Sisonum’s Bounce Plugin

Leave a Reply

Your email address will not be published.