219k views
5 votes
Create a java code that can do the following:

A decimal number to its corresponding binary number
b. A binary number to its corresponding decimal number

1 Answer

4 votes

Final answer:

In Java, decimal to binary conversion can be done using Integer.toBinaryString(), and binary to decimal using Integer.parseInt() with radix 2.

Step-by-step explanation:

Decimal to Binary Conversion

To convert a decimal number to its corresponding binary number in Java, you can use the Integer.toBinaryString() method. Here's an example of how you could write a method to perform this conversion:

public String decimalToBinary(int decimal) {
return Integer.toBinaryString(decimal);
}

Binary to Decimal Conversion

Converting a binary number to its decimal equivalent in Java can be achieved using the Integer.parseInt() method with a radix of 2. Below is a method that demonstrates this:

public int binaryToDecimal(String binary) {
return Integer.parseInt(binary, 2);
}

Note that the parseInt() method throws a NumberFormatException if the provided string is not a valid binary number.

User Aspirinemaga
by
8.5k points