» How to convert decimal to binary in Java with Example

How to convert decimal to binary in Java with Example

This tutorial explains how to Convert decimal value into binary value.

Integer class of java.lang package contains a method toBinaryString() which takes a decimal int value as argument and returns binary String value.

Here is the complete program.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class DecToBinaryExample {

	public static void main(String args[]) throws IOException {
		// Preparing for console Input
		BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in));

		// asking input
		System.out.println("Please provide value in Decimal:");
		String decimalStr = bReader.readLine();

		try {
			// Converting the String value to int.
			int decimalVal = Integer.valueOf(decimalStr);

			// Converting to binary
			String binaryVal = Integer.toBinaryString(decimalVal);
			System.out.println("Value in Binary: " + binaryVal);
		} catch (NumberFormatException e) {
			System.out.println("Please provide correct value.");


If you run the above program, the Input/Output will be like below:

Please provide value in Decimal:
Value in Binary: 11001

Please provide value in Decimal:
Please provide correct value only.
This entry was posted in About us, Adobe Flex, Adobe flex2, C and Cpp, ColdFusion, CSS, Delphi, Dreamweaver, eCommerce, HTML, Java-J2ee, Marketing, Microsoft Asp.Net, MM Fusion, MS Access, MS Excel, MS Frontpage, MySQL, Perl and CGI, PHP, Prestshop, Python, Ruby on Rails, SEO, Uncategorized, Visual Basic, Web Design, XML. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>