Java Code to Convert Decimal to Binary

Decimal to Binary


A decimal number is known to all of us. It is number whose base value is 10. All the number in normal practice are usually decimal numbers. It implies that decimal numbers can consist of number from 0-9.


A binary number is a number whose base value is 2. It means that a binary number system consists of only 0 and 1. In computers all the data is transferred in the form of binary numbers.

The Java Code presented today, asks the user to enter a decimal number, and displays the binary equivalent of that number.

The Java code is displayed below:-

/////////////////////////////////////////////

package developer;

import java.util.Scanner;

public class DecimalToBinary {

    public static void main(String[] args) {
   
        System.out.println("Enter a decimal number: ");
        Scanner scanStr = new Scanner(System.in);
               
        String num = null;       
       
        //Check for an integer number entered by the user
        if(scanStr.hasNextInt())
        { 
            //Convert the decimal number to binary String
            num = Integer.toBinaryString(scanStr.nextInt());
        }           
       
        System.out.println("The decimal number in binary is: "+num);           
    }
}

/////////////////////////////////////////////

When the code is executed, the output is as shown below:-

/////////////////////////////////////////////

Enter a decimal number: 
23
The decimal number in binary is: 10111

/////////////////////////////////////////////