12.10 Wrapper Classes

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 Integer wrapper class. (Notice that since it’s a class, the name is capitalized.)
Here’s a list of some wrapper classes you can use:
  • Boolean
  • Character
  • Integer
  • Double
  • Float
  • Long
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 Integer called intObject is being initialized. Notice that the value that intObject is being assigned to is 2, which is a primitive (int). We can do this because of autoboxing, which automatically converts the 2 into an Integer object.
Similarly, if we declare a variable x of type int and assign it to an Integer object, that Integer object will be automatically unboxed into a primitive type (int).
We’ll learn more about ArrayLists and Generics in Ch. 16: Generics, the JCF, and Maps.

Previous Section

Next Section

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 classes@code4tomorrow.org for inquiries.