Categories: Java

Wrapper Class in Java

A Wrapper class is one whose object contains or wraps primitive data types. When we create an object for a wrapper class, it has a field where we can store primitive data types. To put it another way, we can turn a primitive value into a wrapper class object.

Wrapper Classes Are Required :
  • They are responsible for converting primitive data types into objects. If we want to change the arguments passed into a method, we must use objects (because primitive types are passed by value).
  • Because of the classes in the java.util package only deals with objects, wrapper classes come in handy here as well.
  • The Collection framework’s data structures, such as ArrayList and Vector, only store objects (reference types) and not primitive types.
  • To support synchronization in multithreading, an object is required.
The following are the eight wrapper classes:
Primitive TypeWrapper class
booleanBoolean
charCharacter
byteByte
shortShort
intInteger
longLong
floatFloat
doubleDouble
Example:

Java program that converts all primitives into /wrapper objects and vice versa.


public class WrapperExample{  
public static void main(String args[]){  
byte b=20;  
short s=90;  
int i=76;  
long l=45;  
float f=50.0F;  
double d=69.0D;  
char c='r';  
boolean b2=true;  
  
//Autoboxing: Converting primitives into objects  
Byte byteobj=b;  
Short shortobj=s;  
Integer intobj=i;  
Long longobj=l;  
Float floatobj=f;  
Double doubleobj=d;  
Character charobj=c;  
Boolean boolobj=b2;  
  
//Printing objects  
System.out.println("---Printing object values---");  
System.out.println("Byte object: "+byteobj);  
System.out.println("Short object: "+shortobj);  
System.out.println("Integer object: "+intobj);  
System.out.println("Long object: "+longobj);  
System.out.println("Float object: "+floatobj);  
System.out.println("Double object: "+doubleobj);  
System.out.println("Character object: "+charobj);  
System.out.println("Boolean object: "+boolobj);  
  
//Unboxing: Converting Objects to Primitives  
byte bytevalue=byteobj;  
short shortvalue=shortobj;  
int intvalue=intobj;  
long longvalue=longobj;  
float floatvalue=floatobj;  
double doublevalue=doubleobj;  
char charvalue=charobj;  
boolean boolvalue=boolobj;  
  
//Printing primitives  
System.out.println("---Printing primitive values---");  
System.out.println("byte value: "+bytevalue);  
System.out.println("short value: "+shortvalue);  
System.out.println("int value: "+intvalue);  
System.out.println("long value: "+longvalue);  
System.out.println("float value: "+floatvalue);  
System.out.println("double value: "+doublevalue);  
System.out.println("char value: "+charvalue);  
System.out.println("boolean value: "+boolvalue);  
}}  
Output:
---Printing object values---
Byte object: 20
Short object: 90
Integer object: 76
Long object: 45
Float object: 50.0
Double object: 69.0
Character object: r
Boolean object: true
---Printing primitive values---
byte value: 20
short value: 90
int value: 76
long value: 45
float value: 50.0
double value: 69.0
char value: r
boolean value: true
Integer Class:

The Integer class is a wrapper class for the primitive type int that contains several methods for dealing with int values effectively, such as converting them to string representations and vice versa. An Integer class object can only hold one int value.

Methods of Integer class:
  1. toString(): This function returns the string that corresponds to the int value.

Syntax:

public String toString(int b)

2. toHexString(): Returns the string that corresponds to the int value in hexadecimal form, that is, a string that represents the int value in hex characters-[0-9]. [a-f]

Syntax:

public String toHexString(int b)
  1. toOctalString(): Returns the string that corresponds to the int value in octal form, that is, a string that represents the int value in octal characters-[0-7].

Syntax:

public String toOctalString(int b)
  1. toBinaryString(): Returns the string that corresponds to the int value in binary digits, that is, a string that represents the int value in hex characters-[0/1].

Syntax:

public String toBinaryString(int b)
  1. valueOf() :returns the Integer object that has been initialized with the given value.

Syntax:

public static Integer valueOf(int b)
  1. parseInt(): : returns int value by parsing the string in radix provided. Differs from valueOf() as it returns a primitive int value and valueOf() return Integer object.

Syntax:

public static int parseInt(String val, int radix)
throws NumberFormatException
  1. getInteger(): returns null if the specified system property does not exist or an Integer object expressing the value associated with it.

Syntax:

public static Integer getInteger(String prop)

8.decode(): returns an Integer object with the value of the decoded string. The supplied string must take the following form if not NumberFormatException will be thrown –

Decimal- (Sign)Decimal Number

Hex- (Sign)”0x”Hex Digits in Hex

Hex-(Sign) “0X”Hex Digits

Octal-(Sign) “0” Octal Digits

Syntax:

public static Integer decode(String s)
 throws NumberFormatException
  1. rotateLeft(): Returns a primitive int by rotating the bits to the left by the specified amount in the value’s complement form. The most significant bit is rotated to the right, or least significant position, while turning to the left; this is known as cyclic bit movement. Right rotation is indicated by a negative distance.

Syntax:

public static int rotateLeft(int val, int dist)
  1. rotateRight(): This function returns a primitive int by rotating the bits to the right by the specified amount, using the value’s twos complement. The least significant bit is rotated to the left, or most significant position, when turning to the right, creating a circular movement of bits. Left rotation is indicated by a negative distance.

Syntax:

public static int rotateRight(int val, int dist)
Example: program based on the various methods provided by Integer class
public class IntegerTest {
public static void main(String[] args)
{
 int x = 60; 
 String xx = "35"; 
 System.out.println("toString(x) = " + Integer.toString(x)); 
 
 Integer z = Integer.valueOf(x); 
 System.out.println("valueOf(x) = " + z); 
   z = Integer.valueOf(xx); 
 System.out.println("valueOf(xx) = " + z); 
 int zz = Integer.parseInt(xx); 
 System.out.println("parseInt(xx) = " + zz); 
 
// Call decode() method to decode the binary, hexa, octal and decimal.  
// string to corresponding int values. 
   String decimal = "20";
   String binary = "0100";
   String octal = "005"; 
   String hex = "0x0f"; 

 Integer dec = Integer.decode(decimal); 
 System.out.println("decode(45) = " + dec); 
 
 dec = Integer.decode(binary);
 System.out.println("decode(0100): " +dec);
 
 dec = Integer.decode(octal); 
 System.out.println("decode(005) = " + dec); 
 
 dec = Integer.decode(hex); 
 System.out.println("decode(0x0f) = " + dec);  
  }
}
Output:
toString(x) = 60
valueOf(x) = 60
valueOf(xx) = 35
parseInt(xx) = 35
decode(45) = 20
decode(0100): 64
decode(005) = 5
decode(0x0f) = 15
Example: convert integer number into other number systems, such as binary, hexadecimal, and octal format
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class IntegerTest {
public static void main(String[] args) throws IOException
{
// Accept an Integer number from keyboard.  
   InputStreamReader sr = new InputStreamReader(System.in);
   BufferedReader bf = new BufferedReader(sr);
 
   System.out.println("Enter an integer number:");
   String str = bf.readLine();
// Converting string into int type.
   int i = Integer.parseInt(str);
   System.out.println("In decimal format: " +i);
  
// Converting into other number systems.
   str = Integer.toBinaryString(i);
   System.out.println("In binary format: " +str);
   str = Integer.toHexString(i);
   System.out.println("In hexdecimal format: " +str);
    
    str = Integer.toOctalString(i);
    System.out.println("In octal format: " +str);
   }
}
Output:
Enter an integer number:
12
In decimal format: 12
In binary format: 1100
In hexdecimal format: c
In octal format: 14

Note: also read about the Java Swing Components and Containers -II

Follow Me

If you like my post, please follow me to read my latest post on programming and technology.

https://www.instagram.com/coderz.py/

https://www.facebook.com/coderz.py

Share
Published by
Rabecca Fatima

Recent Posts

Generate Parenthesis | Intuition + Code | Recursion Tree | Backtracking | Java

Problem Statement: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Example…

3 months ago

Square Root of Integer

Given an integer A. Compute and return the square root of A. If A is…

1 year ago

Build Array From Permutation

Given a zero-based permutation nums (0-indexed), build an array ans of the same length where…

1 year ago

DSA: Heap

A heap is a specialized tree-based data structure that satisfies the heap property. It is…

2 years ago

DSA: Trie

What is a Trie in DSA? A trie, often known as a prefix tree, is…

2 years ago

Trees: Lowest Common Ancestor

What is the Lowest Common Ancestor? In a tree, the lowest common ancestor (LCA) of…

2 years ago