Java Code Example: convert decimal to binary number

This Java program converts a decimal number to its binary representation. The program uses the Scanner class from the Java Standard Library to read an integer from the user, and the Integer.toBinaryString() method to convert the integer to its binary representation.

Here’s an explanation of the code:

  1. The first line imports the Scanner class from the Java Standard Library.
  2. The program defines a public class named ConvertToBinary.
  3. In the main method, an integer variable num is declared to store the user-input integer.
  4. A Scanner object named s is created and associated with the standard input stream System.in.
  5. The program prompts the user to enter an integer by printing a message to the console.
  6. The next integer entered by the user is read and stored in the num variable using the nextInt() method of the Scanner class.
  7. The Scanner object s is closed to free up resources.
  8. The binary representation of num is obtained using the Integer.toBinaryString(num) method.
  9. The binary representation of num is then printed to the console with a message that includes the decimal representation of num.
  10. The program ends.
import java.util.Scanner;

public class ConvertToBinary {
  public static void main(String[] args) {
    int num;

    Scanner s = new Scanner(System.in);
    System.out.print("Please enter a number: ");

    num = s.nextInt();

    s.close();
    
    String binary = Integer.toBinaryString(num);
    System.out.println("Binary value of number " + num + " is: " + binary);
  }
}
Output
Please enter a number: 13
Binary value of number 13 is: 1101