Program to accept number from user and convert it into binary by using wrapper class method
A variable of primitive data type is by default passed by value and not by reference. If you need to consider such variables of primitive data type as reference types then the solution is wrapper classes provided by Java. These classes are used to wrap the data in a new object which contains the value of that variable. Wrapper class in java provides the mechanism to convert primitive data type into object and object into primitive data type.
The list of eight wrapper classes are given below:
Primitive Type | Wrapper class |
---|---|
boolean | Boolean |
char | Character |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
For example, we wrap the number 34 in an Integer object in the following way:
Integer intObject = new Integer (34);
The Integer class is the wrapper class that has been provided for the int data type. Here we have used one of the method of Integer wrapper class toBinaryString(int) which returns a string representation of the integer argument as an unsigned integer in base 2.
PROGRAM
import java.util.Scanner;
public class BinaryUsingWrapper {
public static void main(String[] args) {
System.out.print("Enter the number :: ");
Scanner s = new Scanner(System.in);
Integer num = s.nextInt(); // Integer wrapper class
// Use toBinaryString( ) Method of Integer wrapper class
String binaryNumber = Integer.toBinaryString(num);
System.out.println("Binary number of " + num + " is :: "+binaryNumber);
}
}
OUTPUT
C:\>javac BinaryUsingWrapper.java C:\>java BinaryUsingWrapper Enter the number :: 45 Binary number of 45 is :: 101101