Java Integer toBinaryString Method

JavaJavaBeginner
Practice Now

Introduction

In this lab, we will learn how to use the toBinaryString() method of the Integer class in Java. This method is used to convert a decimal number into its binary equivalent.

Import the java.lang.Integer package

In order to use the Integer class, we need to import the java.lang.Integer package.

import java.lang.Integer;

Use toBinaryString() method

The toBinaryString() method takes an integer as input and returns its binary equivalent as a String. Let's see an example where we will convert the integer "10" into its binary equivalent.

int decimalValue = 10;
String binaryValue = Integer.toBinaryString(decimalValue);

Print the output

Now that we have the binary equivalent of the decimal value, let's print it to the console.

System.out.println("Binary representation of " + decimalValue + " is: " + binaryValue);

Summary

In this lab, we learned about the toBinaryString() method of the Integer class in Java. We learned how to import the package, use the method, and print the binary equivalent. We also learned how to test the code with different decimal values.

Other Java Tutorials you may like