A program written in Java to convert an integer to binary

Discussion in 'Other Languages' started by sfidirectory, Apr 8, 2011.

  1. sfidirectory

    sfidirectory Senior Member

    Mar 29, 2010
    Likes Received:
    Web developer/BTC enthusiast
    php artisan make:migration
    Home Page:
    Hi all,

    If you have Dr Java or know how to use the Linux command line, here is a relatively simple Java program I created in my lab session today. Basically it reads in an integer from the user and then performs integer division (by 2) and pushes the remainders after each division onto a stack until the division result reaches 0. Then each remainder is popped off the stack and printed on one line (the code should be self explanatory, although feel free to ask questions if need be), showing the conversion result. In Java, integers (and other types of objects/values) are pushed/popped onto/off the stack on a first in-first out basis. Anyway here is the code...

    import java.util.*;
     * A class that uses a stack to convert an integer into binary code.
    public class IntegerToBinary{
       * The main method of the application. Takes in an integer input from the
       * user, divides the integer until it reaches zero. The remainders are
       * then used via the push and pop stack methods to determine the binary
       * equivalent of the users input. The conversion process will not work if
       * you enter an input that is not an integer (that includes numbers of
       * Java type "long".
       * @param args the users input from the Command Line.
      public static void main(String[] args){
        ArrayList<Integer> decimalInt = new ArrayList<Integer>();
        int size = 0;
        int number, number2;
        Stack<Integer> intStack = new Stack<Integer>();
        Scanner scan = new Scanner(System.in);
          number = scan.nextInt();
          number2 = number;
          System.out.print("The number " + number2 + " in binary code is ");
          if(number == 0){
          while(number > 0){
            if(number == 0){
              number /= 2;
    I suggest if you don't understand the code before you use it, that you ask myself or other Java experts (I don't consider myself an expert per se but I created and compiled 95% of this code myself, and had more senior programmers in my class help me with the remaining 5% - which were "minor" bugs). I hope that this code will help you in some way :).

    P.S I'm not sure how to use the cmd from Windows but have a fair idea about linux commands, so if anyone has questions about how to compile and execute java code via Windows command line I can't help :(, but someday I shall learn it :).