×

How to Convert Decimal to Binary in Java

How to Convert Decimal to Binary in Java There are two methods to convert Decimal to Binary.
  • Using toBinaryString() method
  • Using user-defined logic
Using Integer.toBinaryString() The toBinaryString() is a static method of Integer wrapper class. It returns the string representation of unsigned integer represented by the argument in binary. The signature of the toBinaryString() method is given below: public static String toBinaryString(int i) Where i is an integer to be converted to String. Example In the following example, we have passed two integers 25 and 45 as arguments of toBinaryString() method and store the converted value in the String variable str and str1 respectively. The println statements print the corresponding binary value of 25 and 45 respectively.
public class DecimalToBinaryExample
{ 
public static void main(String args[])
{ 
String str=Integer.toBinaryString(25);            //using toBinaryString()
String str1=Integer.toBinaryString(45);
System.out.println("Binary representation of 25 is: "+str); 
System.out.println("Binary representation of 45 is: "+str1); 
}
}
Output
Binary representation of 25 is: 11001
Binary representation of 45 is: 101101

Using user defined logic

In this method, we have to define our own logic for converting decimal to binary. Example In the following example, we have defined a class DecimaltoBinary. Inside the class, we have defined toString() method which accepts an integer n and returns the corresponding binary string. The number n will be repeatedly divided by 2 until we obtain 0 and the remainder will concatenate. The string variable ‘binary’ holds the result. The while loop has the condition n>0 which will repeatedly perform the operations in the while block until n does not become 0. The body of the while loop contains three statements. The first statement finds the remainder on dividing n by 2, which is obtained by using a modulo operator. The second statement concatenates the remainder (rem) to the binary representation we have obtained so far. Note that we have written ‘rem+binary’ not ‘binary+rem.’ That’s why the last remainder will be the first bit in the binary representation. The third statement updates the value of n, i.e., it divides the value by 2 and takes the quotient. When we invoke the method toBinary() with decimal=0 (which is the special check for n==0 is not present). The variable binary will be initialized to "". The condition n!=0 is false, so the loop will not be execute even once and the result returned would be "", which is not the correct answer, the correct answer is "0". Because of this we add a special check for decimal=0.
public class DecimalToBinary
{
public String toBinary(int n)         //n is a global variable
{
if (n == 0)            
{
return "0";
}
String binary="";
while (n>0)
{
int rem = n%2;                                                                                                       //calculates remainder
binary=rem+binary;                                                                                                //concatenates binary in remainder
n=n/2;                                                                                                                        //
}
return binary;                                                                                                     //returns binary string as a result
}
public static void main(String[] args)
{
int decimal=27;                                                                                              //decimal is a local variable
DecimalToBinary decimalToBinary = new DecimalToBinary();   //creating object of DecimalToBinary class
String binary = decimalToBinary.toBinary(decimal);                   //function calling
System.out.println("The binary representation of the number is: "+binary);
}
}
Output
The binary representation of the number is: 11011

Related Topics

Java ArrayList

Java ArrayList Class A Java ArrayList class is a dynamic array which is used to store the elements. It is a part of collection framework. It implements the List Interface and inherits the...

12 minutes read.

Java Math toIntExact() Method

The toIntExact() method of Java Math class returns the int value of the given long argument, throwing an exception if the value overflows an int. Syntax: public static int toIntExact (long value) Parameters: The...

2 minutes read.

Pernicious Number in Java

If the number of 1s in a number appearing in the binary representation is the prime number, such a number is known as a pernicious number. A pernicious number always corresponds to...

4 minutes read.

Difference Between Java and PHP

The two most used programming languages are PHP and Java. Both of them have a lot of similarities and distinctions. Let's first grasp each of them individually before examining their...

3 minutes read.

Median Of Stream Of Running Integers in Java

An integer array is given to us. Compute the median of the elements traversed so far in the input array. For the sake of simplicity, assume that there are no...

10 minutes read.

Convert Integer to Roman Numerals in Java

The main objective of this article is to convert the integers that are decimal values to the roman numbers. Problem statement: Write a software/program/code to convert any integer to a roman number. You...

10 minutes read.

Why are generics used in Java

Java has a feature called generics that allows you to make a class, interface, and function accepting any (reference) type as a parameter. In other words, it is the idea...

4 minutes read.

Java String subSequence() method

This method returns a new character sequence i.e. subsequence of current sequence Syntax: public CharSequence subSequence(int beginIndex, int endIndex) Parameter: beginIndex ? begin index, inclusive. endIndex ? end index, exclusive. Return: specified subsequnce Throws: It throws IndexOutOfBoundsException...

1 minute read.

Powerful Number in Java

We will define a powerful number in this article and write Java programs to determine whether a given number is a powerful number or not. Java coding interviews and academic...

6 minutes read.

Difference between this and super in Java

In this article, you will be very well equipped with the knowledge of this keyword and super keyword in java. You will be able to understand where to implement this...

3 minutes read.

Cosmic Superclass in Java

The parent class of all Java classes is the Object class. The Java Object class is the parent of all Java classes, whether directly or indirectly. The Object class is...

6 minutes read.

Finding middle node of a linked list in Java

To find the middle node of a linked list we have various methods in Java. Method 1 In this method two pointers are used, one of which advances quickly, and the other of...

6 minutes read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

Fall through in Java

In this article, you will be acknowledged about the fall through condition in Java along with an example program. Fall through It is a situation where there isn't a break statement in...

3 minutes read.

Alice and Bob Problem Java

Alice and Bob were two friends who liked to play games. Both together found a game, which has the description below. The game begins with an integer num, used to create...

2 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Level order Traversal of a Binary Tree in Java

In Java, a level order traversal of a tree structure is also referred to as the breadth-first traversal of the binary tree. Regarding the subsequent binary tree: Level order traversal is as...

5 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Maximizing Profit in Stock Buy Sell in Java

In this tutorial, we will deal with a popular problem, a favourite of interviewers. The problem is named as Maximising profit in stock Buy Sell. we will see certain approaches...

6 minutes read.