Tutor HuntResourcesJava Resources

Java

Java Wrapper Classes

2 min read

A Java wrapper class, also known as a wrapper, is a class that encapsulates the primitive data types in Java within an object. This allows these primitive data types to be treated as objects, which can be helpful when working with Java’s object-oriented programming concepts. The primary purpose of wrapper classes is to provide a way to convert between primitive data types and objects, enabling them to be used in situations that require objects, such as collections, generics, and method overloading.

Java provides a set of predefined wrapper classes for each of its primitive data types:

Byte: Represents a byte value (8-bit signed integer).Short: Represents a short value (16-bit signed integer).Integer: Represents an integer value (32-bit signed integer).Long: Represents a long value (64-bit signed integer).Float: Represents a floating-point value (single-precision 32-bit IEEE 754 floating-point).Double: Represents a double value (double-precision 64-bit IEEE 754 floating-point).Character: Represents a character value (16-bit Unicode character).Boolean: Represents a boolean value (true or false).Here is an example:public class WrapperExample { public static void main(String[] args) { Integer intWrapper = new Integer(42) // Wrapping an int int intValue = intWrapper.intValue() // Unwrapping to get int value System.out.println("Wrapped Integer value: " + intWrapper) System.out.println("Unwrapped int value: " + intValue) // Auto-boxing and auto-unboxing (Java automatically converts between primitive and wrapper) Integer autoBoxed = 99 // Auto-boxing: int to Integer int autoUnboxed = autoBoxed // Auto-unboxing: Integer to int System.out.println("Auto-boxed Integer value: " + autoBoxed) System.out.println("Auto-unboxed int value: " + autoUnboxed) } }

Looking for a tutor?

Search by subject and postcode to compare online and local tutors.

  • Enhanced DBS checked tutors
  • Online or in-person lessons
Find a tutor