Java Convert Decimal to Binary

You can use the Integer.toBinaryString() method in Java to convert a decimal number to its binary representation. Here’s an example:

int decimalNum = 10;
String binaryStr = Integer.toBinaryString(decimalNum);
System.out.println("Binary representation of " + decimalNum + " is: " + binaryStr);

This will output:

Binary representation of 10 is: 1010

In this example, we first define a decimal number decimalNum as 10. We then call the Integer.toBinaryString() method and pass in decimalNum as an argument. This method returns a string representation of the binary equivalent of decimalNum. Finally, we print out the result using System.out.println().

Java Decimal to Binary conversion: Integer.toBinaryString()

Yes, that’s correct! The Integer.toBinaryString() method in Java can be used to convert a decimal number to its binary representation.

This method takes an int as input and returns a String that represents the binary equivalent of the input number.

Here’s an example:

int decimalNum = 10;
String binaryStr = Integer.toBinaryString(decimalNum);
System.out.println("Binary representation of " + decimalNum + " is: " + binaryStr);

This code will output:

Binary representation of 10 is: 1010

In this example, we define a decimal number decimalNum as 10, and then call the Integer.toBinaryString() method, passing in decimalNum as an argument. This method returns a string representation of the binary equivalent of decimalNum, which we store in the binaryStr variable. Finally, we print out the result using System.out.println().

Java Decimal to Binary conversion: Custom Logic

In Java, you can also convert a decimal number to its binary representation using custom logic. Here’s an example:

int decimalNum = 10;
String binaryStr = "";
while(decimalNum > 0) {
    int remainder = decimalNum % 2;
    binaryStr = remainder + binaryStr;
    decimalNum = decimalNum / 2;
}
System.out.println("Binary representation of 10 is: " + binaryStr);

This code will output:

Binary representation of 10 is: 1010

In this example, we first define a decimal number decimalNum as 10, and initialize an empty string binaryStr to store the binary equivalent of the decimal number.

We then use a while loop to repeatedly divide decimalNum by 2 and add the remainder to the beginning of binaryStr. The loop continues until decimalNum becomes 0.

Finally, we print out the result using System.out.println(). The binaryStr variable now contains the binary equivalent of decimalNum.