Wrapper Class in Java

What are Wrapper classes?

In Java, wrapper class is a type of class that serves as a container for primitive data types. Is primitive data type in Java has a corresponding wrapper class, and these wrapper classes are part of java.lang package

The main objective of wrapper classes are –

  • To wrap primitive data type into object form so that we can hadel it like object.
  • To define several utility methods which are required for primitives.

Wrapper Class Constructor

Almost all wrapper classes in Java contain two constructors. One can take the corresponding primitive as an argument and the other can take String as an argument.

Integer I = new Integer(100);
Integer I2 = new Integer("100");

If the String argument is not representing a number then we will get RunTimeException – “Exception in thread “main” java.lang.NumberFormatException”.

NumberFormatException in Java

Primitive Data Types and their Corresponding Wrapper Classes.

Wrapper ClassPrimitive Data Type
Bytebyte
Shortshort
Integerint
Longlong
Floatfloat
Doubledouble
Characterchar
Booleanboolean

Float Class

Float Class contains three constructors with float, double, and String arguments.

public class WrapperClassInJava {
    public static void main(String[] args) {
        Float f1 = new Float(1.5f);
        Float f2 = new Float(1.5);
        Float f3 = new Float("1.5");
        Float f4 = new Float("1.5f");
    }
}

Character Class

Character Class contains only one constructor which takes char as argument.

    public class WrapperClassInJava {
    public static void main(String[] args) {
        Character ch = new Character('a');
 // valid
        Character ch2 = new Character("a"); //Invalid
    }
}

Boolean Class

Boolean Class contains two constructors one takes primitive as argument and the other takes String argument.

  • If we pass a boolean primitive as an argument only allowed values are true and false where case and content are important.
public class WrapperClassInJava {
    public static void main(String[] args) {
       Boolean b = new Boolean(true);
 // true
       Boolean b1 = new Boolean(True); //Error
    }
}
  • If we pass a String as an argument, then the case and content are unimportant. If content is a case-insensitive String of “true, ” it is treated as true. Otherwise, it is treated as false.
public class WrapperClassInJava {
public static void main(String[] args) {
Boolean b = new Boolean("true"); // true
Boolean b1 = new Boolean("True"); //false
}
}

Note-

  • In all wrapper classes toString() is overridden to write content/value directly.
  • In all Wrapper class equals() is overridden for content/value comparison.

Similar Java Tutorials

Leave a Comment