Tuesday, September 22, 2009

Java Code to Convert Decimal to Binary

The Java Code Online is today going to discuss the Java code for converting a decimal number to binary number. A decimal number is known to all of us. It is number whose base value is 10. All the numbers we use in normal practice are usually decimal numbers. It implies that decimal numbers can consist of numbers 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

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

Hope that the code was useful to all of you. Keep buzzing Java Code Online.

Related Java Codes
Java Code to Convert Binary to Decimal

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.