Object superclass, Object Wrappers and Autoboxing

Filter Course


Object superclass, Object Wrappers and Autoboxing

Published by: Dikshya

Published date: 27 Jun 2023

Object superclass, Object Wrappers and Autoboxing

Object Superclass:

In Java, the Object class is the root class of all classes. It is at the top of the class hierarchy and serves as the superclass for all other classes. Every class in Java is implicitly or explicitly derived from the Object class. The Object class provides a set of methods that are available to all objects in Java, such as toString(), equals(), hashCode(), and others. These methods can be overridden in subclasses to provide custom behavior.

Object Wrappers and Autoboxing:

In Java, primitive types (e.g., int, char, boolean) are not objects, but sometimes it is necessary to treat them as objects. To bridge this gap, Java provides wrapper classes for each primitive type. These wrapper classes (e.g., Integer, Character, Boolean) are part of the Java API and wrap the corresponding primitive types, allowing them to be treated as objects.

Autoboxing is a feature introduced in Java 5 that automatically converts primitive types into their corresponding wrapper classes and vice versa. It eliminates the need for explicit conversion between primitives and their wrappers. For example, when you assign an  int to an Integer, autoboxing automatically converts the int to an Integer object. Similarly, when you assign an Integer to an int, autoboxing automatically extracts the int value from the Integer object.

  Autoboxing simplifies coding by allowing you to mix primitives and their wrapper classes without worrying about manual conversions. It is important to note that autoboxing and unboxing (converting wrapper objects back to their corresponding primitive types) incur a slight performance cost, so it's important to use them judiciously in performance-critical scenarios.