Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to convert decimal to binary number.

Java Code Example — Simple Programs

ADVERTISEMENT

Java Program to convert decimal to binary number.

Objective

Write a Java program to manually convert a decimal (base 10) integer into a binary (base 2) string using bitwise operators.

Algorithm / Approach

  1. Read a decimal integer x from the user.
  2. Run a for loop counting down from 15 to 0.
  3. In each iteration, perform a right shift operation r = x >> i.
  4. Use the bitwise AND operator to check the least significant bit: (r & 1).
  5. If the result is 1, print "1". If it is 0, print "0".
Test.java
import java.util.Scanner;
class Test {
 public static void main(String[] a)
 {
  Scanner s=new Scanner(System.in);
  System.out.print("Enter a Num: ");
  int x = s.nextInt();
  int r;
  for(int i = 15; i>=0; i--) {
   r = x>>i;
   if((r & 1)==1)
    System.out.print("1");
   else
    System.out.print("0");
  }
 }
}

Expected Output

Enter a Num: 10
0000000000001010

Explanation of the Program

  • Bitwise operators work directly on the binary representation of the integer in memory.
  • By right-shifting the number by i positions (x >> i), the bit at position i is pushed to the furthest right spot (the least significant bit).
  • The bitwise AND operation (r & 1) isolates this specific bit, allowing the program to evaluate if it is a 1 or a 0.
  • The loop runs backwards from 15 to 0 to print the bits in standard left-to-right reading order (starting with the most significant bit of a 16-bit number).

Complexity

Time Complexity O(1) - The loop runs exactly 16 times regardless of input size.
Space Complexity O(1)

Common Mistakes

  • Printing the bits backwards by running the loop from 0 to 15.
  • Forgetting parentheses around (r & 1) == 1, which can cause evaluation order issues due to Java's operator precedence rules.
ADVERTISEMENT