💻

Java Program for Number System Conversion

Sep 7, 2024

Java Program: Decimal to Binary Conversion

Overview

  • The tutorial discusses a Java program that converts a decimal number to its binary pattern and vice versa.

Key Concepts

  • Main Class: The program is contained within a main Java class named DecimalBinary.
  • Scanner Object: A Scanner object named sc is created to read user input for decimal and binary numbers. This requires importing the java.util package.

Steps for Decimal to Binary Conversion

  1. Input Decimal Number:

    • The program prompts the user to enter a decimal number using System.out.print.
    • The decimal number is read using sc.nextInt() and stored in variable d.
  2. Convert Decimal to Binary:

    • To convert the decimal number to binary, use the Integer.toBinaryString(d) method from the Integer wrapper class.
    • This method returns the binary equivalent in string format.
    • The binary string is displayed directly using System.out.print().

Steps for Binary to Decimal Conversion

  1. Input Binary Number:

    • The program prompts the user to enter a binary number using sc.next() which accepts a binary string.
    • The binary string is stored in variable p.
  2. Convert Binary to Decimal:

    • To convert the binary string to decimal, use Integer.parseInt(p, 2), where:
      • p: the binary string representation.
      • 2: the radix (base) for binary.
    • This method returns the corresponding decimal integer.

Conclusion

  • Both Integer.toBinaryString() and Integer.parseInt() are static methods and can be called directly from the Integer class.
  • The program can be executed to see the output results of the conversions.