Java – Convert Decimal to Binary using Recursion Java


I am trying to simply convert to Binary with recursion. I am having problems with the return statement. This compiles but give an overflow error when run. I don't know what to return (or if my statement is wrong) to prevent this error.


public static String convertToBinary(int number)
  if(number > 0)
      convertToBinary(number / 2);
      convertToBinary((number % 2 ));

   return convertToBinary((number));

Best Solution

Your problem was calling convertToBinary on both number/2 and number%2 I believe. This code works fine for me and isn't that different from what you had:

import java.util.Scanner;

public class DecToBin {

public static void main(String[] args) {

    int input;
    Scanner scan = new Scanner(;

    System.out.print("Enter number to convert to binary: ");
    input = scan.nextInt();


public static void convert(int num) {
    if (num>0) {
        System.out.print(num%2 + " ");