Remember when we learned about primitive types? We also have something called wrapper classes, which basically allow you to treat primitives as objects. There are a couple benefits to this; for example, you can call methods on these objects that you otherwise wouldn’t be able to do on a primitive. Additionally, certain data structures such as ArrayLists* (which are basically more advanced arrays) can only store objects, so if you wanted to store an integer, you would need to use the
Integerwrapper class. (Notice that since it’s a class, the name is capitalized.)
Here’s a list of some wrapper classes you can use:
So when should you use wrapper classes? Usually we stick to using primitives unless some type of conversion needs to happen or we’re using generics*, where objects must be used. For now, let’s focus on the conversion aspect. There is something called autoboxing and autounboxing which allows you to convert effortlessly from the wrapper class to the primitive type and vice versa. For example:
// auto-boxing (int to Integer) Integer intObject = 2; // the above is equivalent to: // Integer intObject = new Integer(2); // auto-unboxing (Integer to int) int x = intObject; }
In this code, we can see that a variable of type
intObjectis being initialized. Notice that the value that
intObjectis being assigned to is 2, which is a primitive (
int). We can do this because of autoboxing, which automatically converts the 2 into an
Similarly, if we declare a variable
intand assign it to an
Integerobject will be automatically unboxed into a primitive type (
We’ll learn more about ArrayLists and Generics in Ch. 16: Generics, the JCF, and Maps.
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact firstname.lastname@example.org for inquiries.