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:
Scanner
class from the Java Standard Library.ConvertToBinary
.main
method, an integer variable num
is declared to store the user-input integer.Scanner
object named s
is created and associated with the standard input stream System.in
.num
variable using the nextInt()
method of the Scanner
class.Scanner
object s
is closed to free up resources.num
is obtained using the Integer.toBinaryString(num)
method.num
is then printed to the console with a message that includes the decimal representation of num
.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);
}
}
Please enter a number: 13
Binary value of number 13 is: 1101