Find number is binary or not in java



In this core java programming tutorial we will write a program to Find number is binary or not in java.



What is binary number?
Binary number consists of only 0 & 1.


Example>
11001011 is binary number.
10000112 is not binary number. (because it consists of 2)



Full Program/SourceCode/ Example to Find number is binary or not in java>
package level1;
/** Copyright (c), AnkitMittal www.JavaMadeSoEasy.com */
public class BinaryNumberOrNotExample {
  
   public static void main(String a[]){
         
          int n=11001011;
          System.out.println(isBinaryNumber(n)? n+" is binary number." : n+" is not binary number.");
          n=11001110;  
          System.out.println(isBinaryNumber(n)? n+" is binary number." : n+" is not binary number.");
          n=10000112;  
          System.out.println(isBinaryNumber(n)? n+" is binary number." : n+" is not binary number.");
          n=11005110;   
          System.out.println(isBinaryNumber(n)? n+" is binary number." : n+" is not binary number.");
   }
  
   /**
   * returns true if number is binary.
   */
   public static boolean isBinaryNumber(int n){     
       while(n != 0){
        if(n%10 > 1){
            return false; //number containing any digit greater than 1 means its not binary.
        }
        n = n/10;   
       }
       return true;
   }
   
  
}
/*OUTPUT
11001011 is binary number.
11001110 is binary number.
10000112 is not binary number.
11005110 is not binary number.
*/


So, In this core java programming tutorial we wrote a program to Find number is binary or not in java.

Previous program                                                                  Next program


Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.



RELATED LINKS>


eEdit
Must read for you :