In this post, we will write a program on how to check whether given number is binary or not in java. Let start by knowing the Binary number and then see the example with an explanation.
What is a Binary Number?
A binary number is a number expressed in the base-2 numeral system that is the number that contains 2 symbols to represent all the numbers. The symbols are 0 and 1.
For example: 101011, 110011110, 10001111 are binary numbers.
Let’s see an explanation to find out whether the given number is binary or not in java:
There are many ways we can find the binary number in java, In this one, we will create a separate function and pass the number that needed to be check and print the result.
First, take the user input with the Scanner class and pass that number to the numBinaryOrNot() function as an argument. Then declare a boolean variable (isBinary). After that execute while loop until the passed number is not equal to zero (
copyNum != 0).
Inside while loop, take the remainder and check if the remainder is greater than 1 or not. If it is greater then change the boolean value to false and break else divide the number by 10. The loop continues till all the numbers are checked.
At last, check if the boolean value is still true then the number is binary number print the result else it is not a binary number.
Java Program to Check Whether the Given Number Is Binary or Not
public class CheckForBinary
static void numBinaryOrNot(int num)
boolean isBinary = true;
int copyNum = num;
while (copyNum != 0)
int temp = copyNum%10;
if(temp > 1)
isBinary = false;
copyNum = copyNum/10;
System.out.println(num+" is a binary number");
System.out.println(num+" is not a binary number");
public static void main(String args)
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
int num = sc.nextInt();
The output to check for the binary number in java: