The document discusses Wrapper Classes in Java, which allow primitive data types to be treated as objects, enabling their use in Collections and APIs. It explains concepts like Autoboxing and Unboxing, providing examples and highlighting the advantages and disadvantages of using Wrapper Classes. Key utility methods and the importance of handling null values are also emphasized for effective Java programming.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0 ratings0% found this document useful (0 votes)
6 views12 pages
OOP WrapperClasses Java
The document discusses Wrapper Classes in Java, which allow primitive data types to be treated as objects, enabling their use in Collections and APIs. It explains concepts like Autoboxing and Unboxing, providing examples and highlighting the advantages and disadvantages of using Wrapper Classes. Key utility methods and the importance of handling null values are also emphasized for effective Java programming.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
{}
Subject: Object Oriented Programming
Faculty: J. M. Ramavat
Wrapper Classes in Java Autoboxing & Unboxing
Submitted By: Modi Yashvi Nitinkumar
Enrollment No.: 240170107081 Computer Engineering Introduction What is a Wrapper Class? Why Do We Need Them?
A Wrapper class wraps a primitive data type inside an Java Collections like ArrayList<Integer> only work with object — like putting a number in a box so Java can treat objects, not primitives. it as an object.
Think of it this way:
Primitive int → Object Integer Key Reasons: • Use primitives in Collections (ArrayList, HashMap) • Pass data to methods that expect Objects • Defined in [Link] package • Use utility methods like parseInt(), valueOf() • Available for all 8 primitive types • Store null values (primitives can't hold null) • Enables primitives to work with Collections, Generics & • Needed in Generics — e.g. List<Integer> not List<int> APIs • Auto-imported — no import needed Primitive vs Non-Primitive Primitive Types Wrapper Classes (Objects)
✓ Stored directly in stack memory ✓ Stored in heap memory
✓ Fast access and execution ✓ Can be used in Collections ✗ Cannot be used in Collections ✓ Can hold a null value ✗ Cannot hold a null → ✓ Utility methods: parseInt(), valueOf() value ✓ Works with Generics like List<Integer> ✗ No built-in utility methods ✗ Slightly slower than primitives ✗ Cannot use with Generics (e.g. List<int>) List of Wrapper Classes Primitive Type Size (bits) Wrapper Class Default Value Example
byte 8 Byte 0 Byte b = 127;
short 16 Short 0 Short s = 200;
int 32 Integer 0 Integer i = 42;
long 64 Long 0L Long l = 99L;
float 32 Float 0.0f Float f = 3.14f;
double 64 Double 0.0d Double d = 9.8;
char 16 Character '\u0000' Character c = 'A';
boolean 1-bit Boolean false Boolean flag = true;
Wrapper Class — Example Using the Integer class to wrap a primitive int Code Explanation public class Main { public static void main(String[] args) { new Integer(42) — Old way to box a // Manual boxing primitive int. Converts 42 into an Integer object. Integer num = new Integer(42); // Using valueOf() method [Link](95) — Preferred modern Integer score = [Link](95); way. Caches small values for efficiency.
// Unboxing: Object → primitive intValue() — Extracts the primitive int back
int plain = [Link](); from the Integer object. Called Unboxing. [Link]("Score: " + score); Output: [Link]("Plain int: " + plain); Score: 95 Plain int: 42 } } Autoboxing Java automatically converts primitive → object (since Java 5)
Definition: Autoboxing is the automatic conversion of a primitive type into its corresponding Wrapper class object by the Java compiler — without writing any extra code.
[Link] Key Points
// Without Autoboxing (manual)
Integer a = [Link](10); Introduced in Java 5 (JDK 1.5)
Compiler inserts [Link]() automatically
// With Autoboxing (automatic!) Integer b = 10; // Java does it for you Saves lines of code and reduces boilerplate
Works at compile time — no runtime penalty for
// In a method call conversion syntax List<Integer> list = new ArrayList<>(); Without it: [Link]([Link](55)) [Link](55); // int → Integer auto! Unboxing Java automatically converts object → primitive type
Definition: Unboxing is the reverse of autoboxing — converting a Wrapper class object back into its corresponding primitive type automatically.
[Link] Key Points // Without Unboxing (manual) Integer obj = [Link](25); Compiler calls intValue() behind the scenes int x = [Link](); Happens automatically in arithmetic, assignments, comparisons // With Unboxing (automatic!) Integer wrapper = 100; Watch out! If wrapper = null and unboxing is triggered, it int value = wrapper; // auto! throws NullPointerException
// Arithmetic triggers unboxing Always check for null before unboxing a wrapper object. int result = wrapper + 50; // = 150 Why Wrapper Classes are Important
Collections Framework APIs and Methods
Java Collections like Many Java APIs (like JDBC,
ArrayList, HashMap & HashSet JSON parsers, REST APIs) only store objects, not primitives. only work with Object types. Wrappers make primitives compatible. Wrappers let you pass values Example: ArrayList<Integer> without manual conversion.
Type Conversion Generics Support
Wrappers provide utility methods Java Generics only support
like parseInt(), parseDouble() reference (object) types. to convert Strings to primitives. List<Integer> works. Critical for reading user input List<int> does NOT compile. or processing data from files. Wrappers bridge this gap. Wrapper Classes with Collections Using ArrayList with Integer — a real-world Java example
[Link] What's Happening Here?
import [Link].*; List<Integer> — We can't write List<int>. Wrapper class Integer is required. public class WrapperDemo { public static void main(String[] args) { [Link](85) — 85 is a primitive int. Java auto- // List needs Integer, not int boxes it to Integer(85) before adding. List<Integer> marks = new ArrayList<>();
for (int m : marks) — When we read from the list,
// Autoboxing: int → Integer Java auto-unboxes each Integer back to int. [Link](85); [Link](92); [Link](78); Output: Mark: 85 // Unboxing: Integer → int Mark: 92 for (int m : marks) { Mark: 78 [Link]("Mark: " + m); } This pattern is used everywhere in Java — student records, e-commerce carts, banking } systems. } Common Methods of Wrapper Classes Built-in methods you'll use in every Java project
parseInt() valueOf() toString()
Converts a primitive or String to a Wrapper
Converts a String to a primitive int. Converts a number to its String representation. object.
int n = [Link]("42"); Integer obj = [Link](99); String s = [Link](25);
// n = 42 // obj is an Integer object // s = "25"
compareTo() MAX_VALUE / MIN_VALUE equals()
Compares two Wrapper objects. Returns 0, +ve,
Constants for the largest and smallest values. Compares the values of two Wrapper objects. or -ve.
[Link](b); // returns -1 // 2147483647 [Link](y); // true Advantages & Disadvantages Advantages Disadvantages Enables use in Collections Performance Overhead ArrayList<Integer>, HashMap<String, Integer> etc. work Wrapper objects need more memory than primitives and are seamlessly. slower to access.
NullPointerException Risk Provides Utility Methods Unboxing a null wrapper like (int) null throws parseInt(), valueOf(), toString() — essential for data handling. NullPointerException.
Supports Null Values More Memory Usage
Primitive int can't be null. Integer can — useful for optional Integer takes ~16 bytes; int takes just 4 bytes. 4x more memory fields. usage.
Works with Generics Slower Arithmetic
List<Integer> is valid; List<int> is not. Wrappers make generics Operations like addition on Integer involve unboxing, making it possible. slower than int.
Type Conversion Made Easy Immutability
Easily convert between String, int, double using wrapper Once created, the value of a wrapper object cannot be changed methods. (immutable). Conclusion Key Takeaways
Final Thought Wrapper classes wrap primitives into objects — enabling use in Collections, Generics and APIs. Wrapper classes are not just a Java feature — Autoboxing & Unboxing make conversions automatic — cleaner code, zero they are a bridge between the low-level world manual calls. of primitive values and the high-level world of Utility methods parseInt(), valueOf(), toString() are critical for real-world data Object Oriented Programming. handling. Mastering them is essential for writing efficient,
Avoid null unboxing — always check for null to prevent NullPointerException. real-world Java applications.
Use primitives for performance-critical code and wrapper classes when