×

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The root node in this binary tree will be 1. We will append 0 and 1 to the end of the root node, respectively, to acquire the left and right nodes of the root node, and so on.

Steps in generating binary numbers

  1. Make a String-type Queue.
  2. Set the value of a variable, say n, to 0.
  3. As the root node, push number one into the queue.
  4. Repeat steps 6 and 7 until the sum is less than n.
  5. Print the root element by selecting it from the queue.
  6. Send the element's right child, as well as its left child, to the queue.
  7. Add one more to the variable total.

Program to generate binary numbers using queues

BinaryUsingQueues.java

import java.util.*; 
public class BinaryUsingQueues 
{  
private static void BinaryNumbersgenerator ( int n )   
{  
    // it returns 0 if number is equal to zero
if ( n == 0 )   
{  
return;  
}  
 // Creating queue of string datatype  
Queue < String > q = new LinkedList < > ( ) ;  
 // Adding a base number to the string
q . add ( " 1 " ) ;  
 // t variable to store the value
int t = 0;  
System.out.println("Binary number for "+n);
while (t < n)   
{  
String curr = q . poll ( ) ;  
System . out. print ( curr + " " ) ;  
q . add ( curr + "0" ) ;  
q . add ( curr + "1" ) ;  
t++;  
}  
System.out.println();  
}  
// Main section of the program where execution starts
public static void main(String args[])   
{  
int n1;
Scanner sc=new Scanner ( System . in ) ;
System.out.println("enter number");
n1 = sc . nextInt ( ) ;
BinaryNumbersgenerator ( n1 ) ;  
int n2 ;
System.out.println("enter number");
n2 = sc . nextInt ( ) ;
BinaryNumbersgenerator ( n2 ) ;  
}  
}  

Output

Java Program to generate binary numbers

Let’s see another approach for the same.

BinaryNumbers2.java

import java. util . * ;  
public class BinaryNumbers2  
{  
public static void main ( String args [ ] )   
{  
int n ;
Scanner sc=new Scanner ( System . in ) ;
System . out . println ( " Enter number " ) ;
n = sc . nextInt ( ) ;
Queue < String > que = new LinkedList <> ( ) ;  
que . add ( " 1 " ) ;  
while (n > 0)   
{  
String t = que . poll ( ) ;  
System . out . print ( t + " " ) ;  
que . add ( t + "0" ) ;  
que . add ( t + " 1 ") ;  
n-- ;  
}  
que . clear ( ) ;  
}  
}

Output

Java Program to generate binary numbers

Binary Numbers using the itoa() method

The function changes an integer into a string with a null termination. Even negative numbers can be converted.

Procedure using the itoa() method

1. Initialize the value up to which binary numbers should be generated.

2. Divide the amount by 2 after calculating the modulo and storing the residual in an array.

3. Till the amount is equal to or less than 0, repeat the previous step.

4. To obtain the equivalent binary numbers, print the array starting at the end.

import java . io . * ;
import java . util . * ;
public class BinaryNumberUsingitoa  
{  
static String itoa ( int x , int base )  
{  
boolean neg = false ;  
String s1 = "";  
if (x == 0)  
return "0";  
neg = (x < 0);  
if (neg)  
x = -1 * x;  
while (x != 0)  
{  
s1 = (x % base) + s1 ;  
x = x / base ;  
}  
if ( neg )  
s1 = "-" + s1 ;  
return s1 ;  
}  
static void Generator ( int n )  
{  
System . out . print ( " 0 " ) ;  
for (int j = 1; j <= n; j++)  
{  
String a1 = new String ( itoa ( j , 2 ) ) ;  
System . out . print ( a1 . substring ( 0 , a1 . length ( ) ) + " " ) ;  
}  
}  
public static void main ( String args [ ] )  
{
Scanner sc = new Scanner ( System. in ) ;
int n1 = sc . nextInt ( ) ;  
Generator ( n1 ) ;  
}  
}  

Output

Java Program to generate binary numbers

Related Topics

Decagonal Numbers in Java

This section explains what is a decagonal number and how to write Java programmes that compute decagonal numbers. Both academics and Java programmer interviews regularly question about the Decagonal number...

3 minutes read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.

Block Swap Algorithm for array rotation in Java

An array and r, the rotation factor by which the array must be rotated, are both provided to us. We must then return the rotated array. A well-known and popular method is...

4 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Java Swings

Swing is a Java Foundation Class library and an extension to the Abstract Window Toolkit (AWT) (JFC).As compared to AWT, Swing has significantly better functionality, new components, increased component features,...

9 minutes read.

Java Public Keyword

A Java access modifier is a public keyword. It can be applied to classes, constructors, methods, and variables. It is the type of access modifier that is least constrained. A...

4 minutes read.

Beautiful Array in Java

In this section, we will be acknowledged about the beautiful array in Java, its characteristics, how it is achieved. What are the types of approaches and what are the tools...

8 minutes read.

Differences between Set and List in Java

Set in Java: The Java. util package contains an interface called the set. The set interface expands the Collection interface. A collection interface is an unordered collection of List where duplicates...

6 minutes read.

Functional Interfaces in Java

Java has forever remained an Object-Oriented Programming language. By object-oriented programming language, we can declare that everything present in the Java programming language rotates throughout the Objects, except for some...

11 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.

How to Convert String to Object in Java

How to Convert String to Object in Java The Object is the super class of all classes. So you can assign a string to Object directly. There are two methods to...

3 minutes read.

Java Private keyword

A Java access modifier is a private keyword. It can be used to inner classes, methods, and variables. It is the type of access modifier that is most constrained. Privately declared...

4 minutes read.

Java File Extension

A computer file's suffix is called its file extension. It is easily recognized since it appears immediately after a period (.) in the file name. Consider the file Demo.java as an...

3 minutes read.

Java Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Java Thread class

Thread class The thread represents a part of the process. Every process can have multiple associated threads in which every thread may execute the same or different job. By default, each thread assigns...

16 minutes read.

How to convert double to String in Java

How to Convert double to String in Java It is used when we want to convert double primitive to String type. There are two methods to convert double to String. Using String.valueOf()...

2 minutes read.

Java Iterator

When iterating through, traversing, or retrieving the individual elements of a Collection or Flow object, a Java Cursor is leveraged as an iterator. In Java, there exist three types of...

4 minutes read.

What is string in Java why it's immutable

String in Java Strings are a series of characters commonly used in Java language, which are considered objects in the Java. To create and manipulate strings, java will provide the String...

4 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

How Many Ways to Create an Object in Java?

As you know, a class is a blueprint for an object, and you can create objects from it. There are several ways to create objects of classes in Java. This...

6 minutes read.