Here’s a Java program to convert a decimal number to binary:
import java.util.Scanner; public class DecimalToBinary { public static void main(String[] args) { int decimalNum; Scanner scanner = new Scanner(System.in); System.out.print("Enter a decimal number: "); decimalNum = scanner.nextInt(); String binaryNum = convertToBinary(decimalNum); System.out.println("Binary equivalent: " + binaryNum); } public static String convertToBinary(int decimalNum) { String binaryNum = ""; while (decimalNum > 0) { int rem = decimalNum % 2; binaryNum = rem + binaryNum; decimalNum /= 2; } return binaryNum; } }
In this program, we first take user input for a decimal number. We then call the `convertToBinary()` method to convert the decimal number to binary.
The `convertToBinary()` method takes an integer parameter `decimalNum` and returns a string representing its binary equivalent. We first initialize an empty string `binaryNum`. We then use a while loop to repeatedly divide the decimal number by 2 and add the remainder to the beginning of the `binaryNum` string. We repeat this process until the decimal number becomes 0. At the end of the method, we return the `binaryNum` string, which is the binary equivalent of the decimal number.
At the end of the program, we print out the binary equivalent of the decimal number.