Wrapper Classes Part 02

Wrapper Classes Part 02

Table of contents

Introduction

  1. With the help of wrapper classes, we can wrap primitives to objects so that we can handle primitives just like objects.

    1. Constructor Summary

      1. Int- Integer(integer,string)

      2. byte- Byte(byte,string)

      3. Char- Character(character)

      4. boolean- Boolean(boolean,string)

      5. Double - Double(double,string)

      6. Float-Float(float,string)

      7. short-Short(short,string)

    2. In all wrapper classes tostring() method overrides to return the content

    3. The equals method is overridden in all wrapper classes to compare the content

## The usage of wrapper classes

1. Utility methods: Helper method/static methods

    1. valueof(): it is used wrapper object for the given primitive or string

        * we can create wrapper classes as

            ```java
            class HelloWorld {
                public static void main(String[] args) {
                   Integer i1 = new Integer(10);
                }
            }
            // this method of creating wrapper classes has been deprecated hence we have one more alternative of creating wrapper classes





            class HelloWorld {
                public static void main(String[] args) {
                   Integer i1= Integer.valueOf(10);// this is the use of value of to create new wrapper classes 
                   System.out.println(i1);
                }
            }

            ```

    2. XXXXvalue()

        * Used to convert objects to primitive

            ```java

            class HelloWorld {
                public static void main(String[] args) {
                   Integer i1= Integer.valueOf(10);
                   System.out.println(i1.intValue());
                   System.out.println(i1.floatValue());
                   System.out.println(i1.byteValue());
                   System.out.println(i1.shortValue());
                   System.out.println(i1.longValue());
                }
            }
            ```

    3. parseXXX()

        * used to convert string to primitive

    4. toString()

        * A `toString()` is an in-built method in Java that returns the value given to it in *string* format. Hence, any object that this method is applied on, will then be returned as a *string object*.


## Autoboxing & Unboxing

1. *Autoboxing* is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on.

2. If the conversion goes the other way, this is called *unboxing*.