×

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 Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Root exception in java

Java: The main feature of java which is not in C or object oriented programming language is platform independence. Not only the platform independence there are many other features in java...

3 minutes read.

Unicode System in Java

In this tutorial, we will understand the meaning and emergence of the Unicode system in java. The Unicode system is one of the important and useful features in the world...

6 minutes read.

Package Program in Java

Package Program in Java The package program in Java helps us to understand the significance of packages in Java. Packages are mainly used to group together similar classes, interfaces and sub-packages....

6 minutes read.

Java 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

GCD Program in Java

GCD Program in Java The GCD program in Java outputs the GCD of the given numbers. In mathematics, Greatest Common Divisor (GCD), Greatest Common Factor or Highest Common Factor (HCF) of...

14 minutes read.

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Operators in Java

There is a good operator environment provided by Java. These operators are divided into four different groups i.e. arithmetic, bitwise, relational, and logical. There are other operators also available to...

7 minutes read.

Race Condition in Java

Java is a multi-threaded programming language, race conditions are more likely to arise. Mostly because data can change when multiple threads visit the same resource simultaneously. Race conditions are concurrency...

3 minutes read.

JAR File in Java

What is a JAR File? JAR stands for Java Archive. It is a file format mainly used to combine many Java class files and the corresponding metadata and resources into one...

4 minutes read.

How to Update Java

As we all know that java can be installed in all operating systems like windows, Linux, macOS. We are available with the java 17 and java 18 versions in the...

3 minutes read.

Java Math cosh() Method

The cosh() method of Math class returns the first hyperbolic cosine((e+e)/2) of a double value. Syntax: public static double cosh(double x) Parameters: The parameter ‘x’ represents the number whose hyperbolic cosine is to be...

2 minutes read.

Java SE vs EE

Java : Java is an independent platform. It works on any kind of operating system. We use java to develop and to focus on large or major projects. The goal of...

3 minutes read.

Java Calculate Average of List

The list is a linear data structure used in Java to store ordered data collections. Additionally, it accepts duplicate values while maintaining insertion order. It is sometimes necessary to find...

3 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

Best Java Security Framework

The security of applications is currently our top concern when creating them. The applications or bits of code running over the network are exposed to dangers and may jeopardize integrity,...

3 minutes read.

Java Case Keyword

Case keyword: In this article we are going to learn the concept of a java case keyword.Generally, java case keyword is used with the switch statements.Case keyword is implemented in conditional...

3 minutes read.

How to increment and decrement date using Java?

Before understanding how to increment and decrement the date, one must know about the Calendar class in Java. The Java calendar class offers methods for converting dates between a given moment...

3 minutes read.

Java Localization

Internationalization is the process of creating a software application that can be translated into different languages and regions without modifying the application. Creating a locale-specific application raises the cost of...

3 minutes read.