Class 11 Class 12

Convert Decimal to Binary in Java using Recursion

A class Converter has been defined that takes a positive integer N from the user and prints out its binary representation. Some of the members of the class are given below:

Class name: Converter
Data members/instance variables:
int num: stores the value of N.
long bin: stores the binary equivalent of N.
Converter(int): parameterized constructor to initialize num and other variables with legal values.
long convert(): converts the decimal number num into its binary equivalent using recursive technique.
display(): displays the values of both decimal number and its binary equivalent with proper message.

Specify the class Converter giving details of the constructor, long convert() and display(). Define the main() function to create an object and call the functions accordingly to enable the task.

class Converter{
    int num;
    long bin;
    public Converter(int n){
        num = n;
        bin = 0L;
    public long convert(){
        if(num == 0)
            return 0L;
        else if(num == 1)
            return 1L;
            int rem = num % 2;
            num /= 2;
            return rem + convert() * 10L;
    public void display(){
        System.out.println("Decimal number: " + num);
        bin = convert();
        System.out.println("Binary equivalent: " + bin);
    public static void main(String args[])throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(;
        System.out.print("Positive integer: ");
        int n = Integer.parseInt(br.readLine());
        Converter obj = new Converter(n);

By admin

I am a Computer Science teacher in one of the renowned schools in India. I teach Java programming language to my students, and I maintain a website

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.