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 TypeWrapper class
booleanBoolean
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble

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

Comments


  1. Thanks, this is generally helpful.
    Still, I followed step-by-step your method in this Java online training
    Java online course

    ReplyDelete

Post a Comment

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.