Java Program to add two binary numbers using ParseInt
Program
import java.util.Scanner;
public class AddTwoBinaryNumbersUsingParseInt {
public void addBinaryNumbers(String binaryNum1, String binaryNum2)
{
int num1 = Integer.parseInt(binaryNum1, 2);
int num2 = Integer.parseInt(binaryNum2, 2);
int sum = num1 + num2;
System.out.println(Integer.toBinaryString(sum));
}
public static void main(String[] args)
{
AddTwoBinaryNumbersUsingParseInt addTwoBinaryNumbersUsingParseInt= new AddTwoBinaryNumbersUsingParseInt();
Scanner reader = new Scanner(System.in);
System.out.print("Enter the first binary number: ");
String binaryNum1 = reader.nextLine();
System.out.print("Enter the second binary number: ");
String binaryNum2 = reader.nextLine();
System.out.print("Sum of two numbers is: ");
addTwoBinaryNumbersUsingParseInt.addBinaryNumbers(binaryNum1, binaryNum2);
}
}
This program demonstrates adding two binary numbers by converting them to decimal values using Integer.parseInt()
and then performing the addition.
Use Case:
This approach is ideal for scenarios where:
- The input binary numbers can be easily converted to decimal.
- The focus is on leveraging Java's built-in methods for efficient processing.
-
Input:
- The user is prompted to enter two binary numbers as
String
inputs using theScanner
class.
- The user is prompted to enter two binary numbers as
-
Conversion:
Integer.parseInt(binaryNum, 2)
:- Converts the binary string input into its decimal (base-10) equivalent.
- The second parameter,
2
, specifies that the input string is in binary format.
-
Addition:
- The two converted decimal values are added together to compute the sum.
-
Result Conversion:
Integer.toBinaryString(sum)
:- Converts the decimal result back into a binary string.
-
Output:
- The program prints the binary representation of the sum.
-
Execution:
- Example:
Enter the first binary number: 1101 Enter the second binary number: 1011 Sum of two numbers is: 11000
- Steps:
- Convert
1101
(binary) to13
(decimal). - Convert
1011
(binary) to11
(decimal). - Add
13 + 11 = 24
(decimal). - Convert
24
(decimal) to11000
(binary).
- Convert
- Example:
Key Features:
- Simplicity:
- Using
Integer.parseInt
andInteger.toBinaryString
simplifies the addition process by leveraging built-in functions for conversions.
- Using
- Accuracy:
- The program ensures accurate addition without needing manual binary arithmetic.
Output
$ javac AddTwoBinaryNumbersUsingParseInt.java
$ java AddTwoBinaryNumbersUsingParseInt
Enter the first binary number: 10101
Enter the second binary number: 11100
Sum of two numbers is: 110001