Blog about Programming Languages & Coding

Blog about Programming Languages & Coding
Contents for Computer Science, IT, B.Sc. CS & IT, M.Sc. CS & IT, MCA, BE CS & IT, ME CS & IT , Interview Questions, Books and Online Course Recommendations from Udemy, Coursera, etc

Wrapper Classes in Java

 Wrapper Classes in Java

What are Wrapper classes?

As the name says, a wrapper class wraps (encloses) around a data type and gives it an object appearance. Wherever, the data type is required as an object, this object can be used. Wrapper classes include methods to unwrap the object and give back the data type. It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.

The primitive data types are not objects; they do not belong to any class; they are defined in the language itself. Sometimes, it is required to convert data types into objects in Java language.  A data type is to be converted into an object and then added to a Stack or Vector etc. For this conversion, the designers introduced wrapper classes.

Wrapper Class

Observe the following conversion.

int i = 100;
Integer i1 = new Integer(i);

The int data type i is converted into an object, i1 using Integer class. The i1 object can be used in Java programming wherever i is required an object.

The following code can be used to unwrap (getting back int from Integer object) the object i1.

int m = i1.intValue();
System.out.println(m*m); // prints 10000

intValue() is a method of Integer class that returns an int data type.

 

Importance of Wrapper classes

There are mainly two uses with wrapper classes.

1.       To convert simple data types into objects, that is, to give object form to a data type; here constructors are used.

2.       To convert strings into data types (known as parsing operations), here methods of type parseXXX() are used.

 

Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double, etc.

Example

int i = 5000;
float gpa = 13.65;
double mask = 0xaf;

However, in development, we come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper classes.

All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class Number.

number_classes.jpg

The object of the wrapper class contains or wraps its respective primitive data type. Converting primitive data types into object is called boxing, and this is taken care by the compiler. Therefore, while using a wrapper class you just need to pass the value of the primitive data type to the constructor of the Wrapper class.

And the Wrapper object will be converted back to a primitive data type, and this process is called unboxing. The Number class is part of the java.lang package.

Following is an example of boxing and unboxing −

Example

public class Test {
   public static void main(String args[]) {
      Integer x = 5; // boxes int to an Integer object
      x =  x + 10;   // unboxes the Integer to a int
      System.out.println(x); 
   }}

This will produce the following result −

15

When x is assigned an integer value, the compiler boxes the integer because x is integer object. Later, x is unboxed so that they can be added as an integer.

Autoboxing and Unboxing

Autoboxing: Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc.

 

Unboxing: It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double etc.

 

public class WrappingUnwrapping

{

  public static void main(String args[])

  {                                                     //  data types

    byte grade = 2;

    int marks = 50;

    float price = 8.6f;                             // observe a suffix of <strong>f</strong> for float

    double rate = 50.5;

   

// data types to objects               

    Byte g1 = new Byte(grade);                    // wrapping  

    Integer m1 = new Integer(marks);

    Float f1 = new Float(price);

    Double r1 = new Double(rate);

     // let us print the values from objects 

    System.out.println("Values of Wrapper objects (printing as objects)");

    System.out.println("Byte object g1:  " + g1);

    System.out.println("Integer object m1:  " + m1);

    System.out.println("Float object f1:  " + f1);

    System.out.println("Double object r1:  " + r1);

 

// objects to data types (retrieving data types from objects)

    byte bv = g1.byteValue();                 // unwrapping

    int iv = m1.intValue();

    float fv = f1.floatValue();

    double dv = r1.doubleValue();

 

// let us print the values from data types  

    System.out.println("Unwrapped values (printing as data types)");

    System.out.println("byte value, bv: " + bv);

    System.out.println("int value, iv: " + iv);

    System.out.println("float value, fv: " + fv);

    System.out.println("double value, dv: " + dv);

  }

}

Number Methods:

Following is the list of the instance methods that all the subclasses of the Number class implements −

Sr.No.

Method & Description

1

xxxValue()

Converts the value of this Number object to the xxx data type and returns it. Here is a separate method for each primitive data type −

byte byteValue()
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()

 

public class Test { 
   public static void main(String args[]) {
      Integer x = 5;
      
      // Returns byte primitive data type
      System.out.println( x.byteValue() );
 
      // Returns double primitive data type
      System.out.println(x.doubleValue());
 
      // Returns long primitive data type
      System.out.println( x.longValue() );      
   }}

2

compareTo()

Compares this Number object to the argument.

3

equals()

Determines whether this number object is equal to the argument.

4

valueOf()

Returns an Integer object holding the value of the specified primitive.

public class Test { 
 
   public static void main(String args[]) {
      Integer x =Integer.valueOf(9);
      Double c = Double.valueOf(5);
      Float a = Float.valueOf("80");               
       System.out.println(x); 
      System.out.println(c);
      System.out.println(a);
    }}

5

toString()

Returns a String object representing the value of a specified int or Integer.

6

parseInt()

This method is used to get the primitive data type of a certain String.

7

abs()

Returns the absolute value of the argument.

8

ceil()

Returns the smallest integer that is greater than or equal to the argument. Returned as a double.

9

floor()

Returns the largest integer that is less than or equal to the argument. Returned as a double.

10

rint()

Returns the integer that is closest in value to the argument. Returned as a double.

11

round()

Returns the closest long or int, as indicated by the method's return type to the argument.

12

min()

Returns the smaller of the two arguments.

13

max()

Returns the larger of the two arguments.

14

exp()

Returns the base of the natural logarithms, e, to the power of the argument.

15

log()

Returns the natural logarithm of the argument.

16

pow()

Returns the value of the first argument raised to the power of the second argument.

17

sqrt()

Returns the square root of the argument.

18

sin()

Returns the sine of the specified double value.

19

cos()

Returns the cosine of the specified double value.

20

tan()

Returns the tangent of the specified double value.

21

asin()

Returns the arcsine of the specified double value.

22

acos()

Returns the arccosine of the specified double value.

23

atan()

Returns the arctangent of the specified double value.

24

atan2()

Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta.

25

toDegrees()

Converts the argument to degrees.

26

toRadians()

Converts the argument to radians.

27

random()

Returns a random number.

Character Wrapper Class:

Normally, when we work with characters, we use primitive data types char.

Example

char ch = 'a';
 
// Unicode for uppercase Greek omega character
char uniChar = '\u039A'; 
 
// an array of chars
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' }; 

However in development, we come across situations where we need to use objects instead of primitive data types. In order to achieve this, Java provides wrapper class Character for primitive data type char.

The Character class offers a number of useful class (i.e., static) methods for manipulating characters. You can create a Character object with the Character constructor −

Character ch = new Character('a');

The Java compiler will also create a Character object for you under some circumstances. For example, if you pass a primitive char into a method that expects an object, the compiler automatically converts the char to a Character for you. This feature is called autoboxing or unboxing, if the conversion goes the other way.

Example

// Here following primitive char 'a'
// is boxed into the Character object ch
Character ch = 'a';
 
// Here primitive 'x' is boxed for method test,
// return is unboxed to char 'c'
char c = test('x');

Character Methods

Following is the list of the important instance methods that all the subclasses of the Character class implement −

Sr.No.

Method & Description

1

isLetter()

Determines whether the specified char value is a letter.

public class Test {
   public static void main(String args[]) {
      System.out.println(Character.isLetter('c'));
      System.out.println(Character.isLetter('5'));
   }
}

2

isDigit()

Determines whether the specified char value is a digit.

3

isWhitespace()

Determines whether the specified char value is white space.

4

isUpperCase()

Determines whether the specified char value is uppercase.

5

isLowerCase()

Determines whether the specified char value is lowercase.

6

toUpperCase()

Returns the uppercase form of the specified char value.

7

toLowerCase()

Returns the lowercase form of the specified char value.

8

toString()

Returns a String object representing the specified character value that is, a one-character string.

 

Boolean wrapper class is used to wrap primitive data type boolean value in an object.  An object of type Boolean contains a single field whose type is boolean.

In addition, this class provides many methods for converting a boolean to a String and a String to a boolean, as well as other constants and methods useful when dealing with a boolean.

Example 1 : Convert Boolean Object to boolean data type

public class BooleanToboolean

{

          public static void main(String[] args) 

          {

                    Boolean bObj = new Boolean("true"); 

                   boolean b = bObj.booleanValue();

                   System.out.println(b);

          }} 

 

Output

true

 

This example show how a Boolean object can be converted to a boolean data type.

Example 2 : Convert String Object to Boolean Object

public class StringToBoolean 

{

          public static void main(String[] args) 

          {

                   String str = "true";

                    Boolean bObj1 = new Boolean(str);

                   System.out.println(bObj1); 

                   Boolean bObj2 = Boolean.valueOf("false");

                   System.out.println(bObj2);

          }  

}

Output

true

false

 

This example shows how to convert String object to a Boolean object.

  

 

Wrapper Classes in Java Wrapper Classes in Java Reviewed by Asst. Prof. Sunita Rai, Computer Sci.. Dept., G.N. Khalsa College, Mumbai on January 13, 2022 Rating: 5

No comments:

Powered by Blogger.