Java Tutorial
🔍

Java Wrapper Classes - Complete Guide

Java Wrapper Classes

Wrapper classes convert Java primitives into objects. They "wrap" primitive values in an object so they can be used where objects are required.

What are Wrapper Classes?

A wrapper class wraps (encloses) a primitive type and provides an object representation of it.

public class WrapperIntro { public static void main(String[] args) { // Primitive type int primitiveInt = 10; // Wrapper class (Object) Integer wrapperInt = Integer.valueOf(10); System.out.println("Primitive: " + primitiveInt); // 10 System.out.println("Wrapper: " + wrapperInt); // 10 // Key difference: wrapper is an OBJECT System.out.println(primitiveInt instanceof Object); // Error! Can't use instanceof with primitive System.out.println(wrapperInt instanceof Object); // true } }

The 8 Wrapper Classes

Each primitive type has a corresponding wrapper class:

PrimitiveWrapper ClassPackage
byteBytejava.lang
shortShortjava.lang
intIntegerjava.lang
longLongjava.lang
floatFloatjava.lang
doubleDoublejava.lang
charCharacterjava.lang
booleanBooleanjava.lang

Note: All wrapper classes are in java.lang package (no import needed) and are immutable (cannot be changed after creation).

Why Do We Need Wrapper Classes?

Reason 1: Collections Require Objects

import java.util.ArrayList; public class CollectionExample { public static void main(String[] args) { // ❌ WRONG - ArrayList can't store primitives // ArrayList<int> numbers = new ArrayList<>(); // Compile error! // ✅ CORRECT - Use wrapper class ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(10); // Auto-boxing: int → Integer numbers.add(20); numbers.add(30); System.out.println(numbers); // [10, 20, 30] // Extract value int value = numbers.get(0); // Auto-unboxing: Integer → int System.out.println(value); // 10 } }

Reason 2: Null Values

public class NullExample { public static void main(String[] args) { // Primitives CANNOT be null // int x = null; // Compile error! // Wrapper classes CAN be null Integer y = null; // OK! System.out.println(y); // null // Useful for database fields that might be NULL Integer age = null; // Unknown age if (age == null) { System.out.println("Age not specified"); } } }

Reason 3: Utility Methods

public class UtilityMethods { public static void main(String[] args) { // Convert string to int String str = "123"; int num = Integer.parseInt(str); System.out.println(num + 10); // 133 // Convert int to string int value = 456; String text = Integer.toString(value); System.out.println(text + "789"); // "456789" // Min/Max values System.out.println("Max int: " + Integer.MAX_VALUE); // 2147483647 System.out.println("Min int: " + Integer.MIN_VALUE); // -2147483648 // Compare values Integer a = 100; Integer b = 200; System.out.println(a.compareTo(b)); // -1 (a < b) } }

Autoboxing and Unboxing

Autoboxing: Automatic conversion from primitive to wrapper
Unboxing: Automatic conversion from wrapper to primitive

public class AutoboxingExample { public static void main(String[] args) { // ========== AUTOBOXING ========== // Manual boxing (old way - Java 1.4 and earlier) Integer oldWay = Integer.valueOf(10); // Autoboxing (Java 5+) Integer newWay = 10; // Automatic: int → Integer // More examples Double d = 3.14; // double → Double Boolean b = true; // boolean → Boolean Character c = 'A'; // char → Character // ========== UNBOXING ========== Integer wrapper = 100; // Manual unboxing (old way) int oldPrimitive = wrapper.intValue(); // Auto-unboxing (Java 5+) int newPrimitive = wrapper; // Automatic: Integer → int // Use in arithmetic Integer x = 50; Integer y = 30; int sum = x + y; // Auto-unbox both, then add System.out.println(sum); // 80 // ========== MIXED OPERATIONS ========== Integer num1 = 10; int num2 = 20; // Automatic conversions during operation int result1 = num1 + num2; // num1 unboxed to int Integer result2 = num1 + num2; // sum auto-boxed to Integer System.out.println(result1); // 30 System.out.println(result2); // 30 } }

Important: While convenient, autoboxing/unboxing has performance overhead. For performance-critical code, prefer primitives.

Integer Wrapper Class

The most commonly used wrapper class.

Creating Integer Objects

public class IntegerCreation { public static void main(String[] args) { // Method 1: Autoboxing (most common) Integer num1 = 10; // Method 2: valueOf() - returns cached object for -128 to 127 Integer num2 = Integer.valueOf(10); Integer num3 = Integer.valueOf("123"); // From string // Method 3: Constructor (deprecated since Java 9) Integer num4 = new Integer(10); // Don't use! System.out.println(num1); // 10 System.out.println(num2); // 10 System.out.println(num3); // 123 } }

String Conversion Methods

public class IntegerConversion { public static void main(String[] args) { // ========== STRING TO INT ========== // parseInt() - returns primitive int int num1 = Integer.parseInt("123"); System.out.println(num1); // 123 System.out.println(num1 + 10); // 133 // parseInt() with radix (base) int binary = Integer.parseInt("1010", 2); // Binary to decimal int hex = Integer.parseInt("FF", 16); // Hex to decimal int octal = Integer.parseInt("77", 8); // Octal to decimal System.out.println("Binary 1010 = " + binary); // 10 System.out.println("Hex FF = " + hex); // 255 System.out.println("Octal 77 = " + octal); // 63 // valueOf() - returns Integer object Integer num2 = Integer.valueOf("456"); System.out.println(num2); // 456 // ========== INT TO STRING ========== // toString() - static method String str1 = Integer.toString(789); System.out.println(str1); // "789" System.out.println(str1 + "0"); // "7890" // toString() - instance method Integer num = 100; String str2 = num.toString(); System.out.println(str2); // "100" // Convert to different bases String bin = Integer.toBinaryString(10); // "1010" String oct = Integer.toOctalString(10); // "12" String hexStr = Integer.toHexString(255); // "ff" System.out.println("10 in binary: " + bin); System.out.println("10 in octal: " + oct); System.out.println("255 in hex: " + hexStr); } }

Useful Integer Methods

public class IntegerMethods { public static void main(String[] args) { // ========== CONSTANTS ========== System.out.println("MAX_VALUE: " + Integer.MAX_VALUE); // 2147483647 System.out.println("MIN_VALUE: " + Integer.MIN_VALUE); // -2147483648 System.out.println("SIZE: " + Integer.SIZE); // 32 (bits) System.out.println("BYTES: " + Integer.BYTES); // 4 // ========== COMPARISON ========== Integer a = 100; Integer b = 200; Integer c = 100; // compareTo() - returns -1, 0, or 1 System.out.println(a.compareTo(b)); // -1 (a < b) System.out.println(b.compareTo(a)); // 1 (b > a) System.out.println(a.compareTo(c)); // 0 (a == c) // compare() - static method System.out.println(Integer.compare(100, 200)); // -1 // equals() System.out.println(a.equals(c)); // true // ========== VALUE EXTRACTION ========== Integer num = 42; int intValue = num.intValue(); long longValue = num.longValue(); double doubleValue = num.doubleValue(); float floatValue = num.floatValue(); System.out.println(intValue); // 42 System.out.println(longValue); // 42 System.out.println(doubleValue); // 42.0 // ========== UTILITY METHODS ========== // Count bits int bitCount = Integer.bitCount(7); // How many 1s in binary System.out.println("Bit count of 7: " + bitCount); // 3 (binary: 111) // Reverse bits int reversed = Integer.reverse(1); // Reverse bit order // Sum (Java 8+) int sum = Integer.sum(10, 20); System.out.println("Sum: " + sum); // 30 // Max/Min (Java 8+) int max = Integer.max(10, 20); int min = Integer.min(10, 20); System.out.println("Max: " + max + ", Min: " + min); // 20, 10 } }

Double Wrapper Class

For floating-point numbers.

public class DoubleExample { public static void main(String[] args) { // ========== CREATION ========== Double d1 = 3.14; // Autoboxing Double d2 = Double.valueOf(2.718); Double d3 = Double.valueOf("1.414"); // ========== STRING CONVERSION ========== // String to double double num1 = Double.parseDouble("3.14159"); System.out.println(num1); // 3.14159 // Double to String String str = Double.toString(2.718); System.out.println(str); // "2.718" // ========== CONSTANTS ========== System.out.println("MAX_VALUE: " + Double.MAX_VALUE); System.out.println("MIN_VALUE: " + Double.MIN_VALUE); // Smallest positive value System.out.println("POSITIVE_INFINITY: " + Double.POSITIVE_INFINITY); System.out.println("NEGATIVE_INFINITY: " + Double.NEGATIVE_INFINITY); System.out.println("NaN: " + Double.NaN); // Not a Number // ========== SPECIAL CHECKS ========== double x = 10.0 / 0.0; // Infinity double y = 0.0 / 0.0; // NaN System.out.println("x is infinite: " + Double.isInfinite(x)); // true System.out.println("y is NaN: " + Double.isNaN(y)); // true System.out.println("3.14 is finite: " + Double.isFinite(3.14)); // true // ========== COMPARISON ========== Double a = 3.14; Double b = 2.71; System.out.println(a.compareTo(b)); // 1 (a > b) // Compare with tolerance (for floating-point precision) double val1 = 0.1 + 0.2; double val2 = 0.3; System.out.println(val1 == val2); // false! (precision issue) double epsilon = 0.00001; boolean equal = Math.abs(val1 - val2) < epsilon; System.out.println("Equal with tolerance: " + equal); // true // ========== UTILITY METHODS ========== Double num = 3.14159; System.out.println("int value: " + num.intValue()); // 3 System.out.println("long value: " + num.longValue()); // 3 // Sum, max, min (Java 8+) System.out.println("Sum: " + Double.sum(1.5, 2.5)); // 4.0 System.out.println("Max: " + Double.max(1.5, 2.5)); // 2.5 } }

Boolean Wrapper Class

public class BooleanExample { public static void main(String[] args) { // ========== CREATION ========== Boolean b1 = true; // Autoboxing Boolean b2 = Boolean.valueOf(false); Boolean b3 = Boolean.valueOf("true"); // From string Boolean b4 = Boolean.valueOf("false"); // ========== STRING CONVERSION ========== // String to boolean boolean val1 = Boolean.parseBoolean("true"); // true boolean val2 = Boolean.parseBoolean("false"); // false boolean val3 = Boolean.parseBoolean("yes"); // false! (only "true" is true) boolean val4 = Boolean.parseBoolean("TRUE"); // true (case-insensitive) System.out.println(val1); // true System.out.println(val2); // false System.out.println(val3); // false System.out.println(val4); // true // Boolean to String String str = Boolean.toString(true); System.out.println(str); // "true" // ========== CONSTANTS ========== System.out.println("TRUE: " + Boolean.TRUE); // true System.out.println("FALSE: " + Boolean.FALSE); // false // ========== COMPARISON ========== Boolean a = true; Boolean b = false; System.out.println(a.compareTo(b)); // 1 (true > false) System.out.println(a.equals(b)); // false // ========== LOGICAL OPERATIONS ========== boolean x = true; boolean y = false; System.out.println("AND: " + Boolean.logicalAnd(x, y)); // false System.out.println("OR: " + Boolean.logicalOr(x, y)); // true System.out.println("XOR: " + Boolean.logicalXor(x, y)); // true // ========== PRACTICAL EXAMPLE ========== String input = "yes"; boolean isYes = input.equalsIgnoreCase("yes") || input.equalsIgnoreCase("true") || input.equals("1"); Boolean result = Boolean.valueOf(isYes); System.out.println("User said yes: " + result); } }

Character Wrapper Class

public class CharacterExample { public static void main(String[] args) { // ========== CREATION ========== Character ch1 = 'A'; // Autoboxing Character ch2 = Character.valueOf('B'); // ========== CHARACTER CHECKS ========== char c = 'A'; System.out.println("Is letter: " + Character.isLetter(c)); // true System.out.println("Is digit: " + Character.isDigit(c)); // false System.out.println("Is uppercase: " + Character.isUpperCase(c)); // true System.out.println("Is lowercase: " + Character.isLowerCase(c)); // false System.out.println("Is whitespace: " + Character.isWhitespace(c)); // false // More checks System.out.println("Is alphanumeric: " + Character.isLetterOrDigit('5')); // true System.out.println("Is space: " + Character.isSpaceChar(' ')); // true // ========== CASE CONVERSION ========== char lower = 'a'; char upper = 'A'; System.out.println("To upper: " + Character.toUpperCase(lower)); // A System.out.println("To lower: " + Character.toLowerCase(upper)); // a // ========== ASCII VALUES ========== char letter = 'A'; int ascii = (int)letter; // Or: Character.getNumericValue() System.out.println("ASCII of A: " + ascii); // 65 char fromAscii = (char)65; System.out.println("Char from 65: " + fromAscii); // A // ========== COMPARISON ========== Character a = 'A'; Character b = 'B'; System.out.println(a.compareTo(b)); // -1 (A < B) // Static compare System.out.println(Character.compare('X', 'Y')); // -1 // ========== PRACTICAL EXAMPLES ========== // Count letters in string String text = "Hello123 World!"; int letterCount = 0; for (char ch : text.toCharArray()) { if (Character.isLetter(ch)) { letterCount++; } } System.out.println("Letters: " + letterCount); // 10 // Check if alphanumeric String password = "Pass123"; boolean isAlphaNum = true; for (char ch : password.toCharArray()) { if (!Character.isLetterOrDigit(ch)) { isAlphaNum = false; break; } } System.out.println("Is alphanumeric: " + isAlphaNum); // true } }

Other Wrapper Classes

Byte Wrapper Class

public class ByteExample { public static void main(String[] args) { // Byte range: -128 to 127 Byte b1 = 10; Byte b2 = Byte.valueOf("20"); // Constants System.out.println("MAX_VALUE: " + Byte.MAX_VALUE); // 127 System.out.println("MIN_VALUE: " + Byte.MIN_VALUE); // -128 System.out.println("SIZE: " + Byte.SIZE); // 8 bits // Conversion byte num = Byte.parseByte("50"); String str = Byte.toString((byte)100); System.out.println(num); // 50 System.out.println(str); // "100" } }

Short Wrapper Class

public class ShortExample { public static void main(String[] args) { // Short range: -32768 to 32767 Short s1 = 1000; Short s2 = Short.valueOf("2000"); // Constants System.out.println("MAX_VALUE: " + Short.MAX_VALUE); // 32767 System.out.println("MIN_VALUE: " + Short.MIN_VALUE); // -32768 // Conversion short num = Short.parseShort("5000"); String str = Short.toString((short)10000); System.out.println(num); // 5000 System.out.println(str); // "10000" } }

Long Wrapper Class

public class LongExample { public static void main(String[] args) { // Long for large numbers Long l1 = 1000000000L; Long l2 = Long.valueOf("9999999999"); // Constants System.out.println("MAX_VALUE: " + Long.MAX_VALUE); // 9223372036854775807 System.out.println("MIN_VALUE: " + Long.MIN_VALUE); // -9223372036854775808 // Conversion long num = Long.parseLong("123456789"); String str = Long.toString(987654321L); System.out.println(num); // 123456789 System.out.println(str); // "987654321" // Binary, Octal, Hex String binary = Long.toBinaryString(255L); System.out.println("255 in binary: " + binary); // 11111111 } }

Float Wrapper Class

public class FloatExample { public static void main(String[] args) { Float f1 = 3.14f; Float f2 = Float.valueOf("2.718"); // Constants System.out.println("MAX_VALUE: " + Float.MAX_VALUE); System.out.println("MIN_VALUE: " + Float.MIN_VALUE); // Smallest positive // Conversion float num = Float.parseFloat("1.414"); String str = Float.toString(2.5f); System.out.println(num); // 1.414 System.out.println(str); // "2.5" // Special values System.out.println(Float.isNaN(0.0f / 0.0f)); // true System.out.println(Float.isInfinite(1.0f / 0.0f)); // true } }

Wrapper Class Caching

Java caches certain wrapper objects for performance.

public class CachingExample { public static void main(String[] args) { // ========== INTEGER CACHING (-128 to 127) ========== Integer a = 100; Integer b = 100; System.out.println(a == b); // true (same cached object) Integer c = 1000; Integer d = 1000; System.out.println(c == d); // false (different objects) // Use equals() for value comparison System.out.println(c.equals(d)); // true // ========== WHY CACHING HAPPENS ========== // valueOf() uses cache Integer cached1 = Integer.valueOf(50); Integer cached2 = Integer.valueOf(50); System.out.println(cached1 == cached2); // true (same object) // new Integer() creates new object (deprecated) Integer notCached1 = new Integer(50); Integer notCached2 = new Integer(50); System.out.println(notCached1 == notCached2); // false // ========== OTHER CACHED WRAPPERS ========== // Boolean - both values cached Boolean bool1 = true; Boolean bool2 = true; System.out.println(bool1 == bool2); // true // Character - cached for 0 to 127 Character char1 = 'A'; // 65 Character char2 = 'A'; System.out.println(char1 == char2); // true // Byte - all values cached (-128 to 127) Byte byte1 = 10; Byte byte2 = 10; System.out.println(byte1 == byte2); // true } }

Rule: Always use .equals() for value comparison, not ==

Collections and Generics

Wrapper classes are essential for Java Collections.

import java.util.*; public class CollectionsExample { public static void main(String[] args) { // ========== ARRAYLIST ========== // Must use wrapper class ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(10); // Autoboxing numbers.add(20); numbers.add(30); // Retrieve int first = numbers.get(0); // Auto-unboxing System.out.println("First: " + first); // 10 // Iterate for (Integer num : numbers) { System.out.print(num + " "); // 10 20 30 } System.out.println(); // ========== HASHMAP ========== HashMap<String, Integer> scores = new HashMap<>(); scores.put("Alice", 95); scores.put("Bob", 87); scores.put("Carol", 92); int aliceScore = scores.get("Alice"); System.out.println("Alice's score: " + aliceScore); // 95 // ========== HASHSET ========== HashSet<Double> prices = new HashSet<>(); prices.add(19.99); prices.add(29.99); prices.add(19.99); // Duplicate - won't be added System.out.println("Unique prices: " + prices.size()); // 2 // ========== SORTING ========== ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 9)); Collections.sort(nums); System.out.println("Sorted: " + nums); // [1, 2, 5, 8, 9] // ========== MAX/MIN ========== int max = Collections.max(nums); int min = Collections.min(nums); System.out.println("Max: " + max); // 9 System.out.println("Min: " + min); // 1 } }

Null Handling

Wrapper classes can be null; primitives cannot.

public class NullHandling { public static void main(String[] args) { // ========== NULL ASSIGNMENT ========== Integer num = null; // OK // int x = null; // Compile error! System.out.println(num); // null // ========== NULL POINTER EXCEPTION ========== Integer value = null; try { int result = value + 10; // NullPointerException! // Auto-unboxing tries to call value.intValue() on null } catch (NullPointerException e) { System.out.println("Error: Cannot unbox null"); } // ========== SAFE NULL CHECKS ========== Integer score = null; // Method 1: Check before using if (score != null) { int total = score + 10; System.out.println(total); } else { System.out.println("Score is null"); } // Method 2: Use default value int finalScore = (score != null) ? score : 0; System.out.println("Final score: " + finalScore); // 0 // Method 3: Objects.requireNonNullElse() (Java 9+) // int safeScore = Objects.requireNonNullElse(score, 0); // ========== COLLECTIONS WITH NULL ========== ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(null); // Allowed in ArrayList numbers.add(20); System.out.println(numbers); // [10, null, 20] // Safe iteration for (Integer num : numbers) { if (num != null) { System.out.println(num * 2); } else { System.out.println("Null value"); } } } }

Practical Applications

1. Input Validation

import java.util.Scanner; public class InputValidation { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.print("Enter your age: "); String input = scanner.nextLine(); try { int age = Integer.parseInt(input); if (age >= 0 && age <= 150) { System.out.println("Valid age: " + age); } else { System.out.println("Age out of range"); } } catch (NumberFormatException e) { System.out.println("Invalid number format"); } scanner.close(); } }

2. Data Type Conversion

public class TypeConversion { public static void main(String[] args) { // ========== STRING TO NUMBERS ========== String strInt = "123"; String strDouble = "45.67"; String strBool = "true"; int num1 = Integer.parseInt(strInt); double num2 = Double.parseDouble(strDouble); boolean bool = Boolean.parseBoolean(strBool); System.out.println(num1); // 123 System.out.println(num2); // 45.67 System.out.println(bool); // true // ========== NUMBERS TO STRING ========== int age = 25; double price = 19.99; boolean active = true; String str1 = Integer.toString(age); String str2 = Double.toString(price); String str3 = Boolean.toString(active); System.out.println(str1); // "25" System.out.println(str2); // "19.99" System.out.println(str3); // "true" // ========== BETWEEN NUMBER TYPES ========== Integer intNum = 100; double doubleVal = intNum.doubleValue(); long longVal = intNum.longValue(); byte byteVal = intNum.byteValue(); System.out.println(doubleVal); // 100.0 System.out.println(longVal); // 100 System.out.println(byteVal); // 100 } }

3. Number System Conversions

public class NumberSystems { public static void main(String[] args) { int decimal = 255; // Decimal to other bases String binary = Integer.toBinaryString(decimal); String octal = Integer.toOctalString(decimal); String hex = Integer.toHexString(decimal); System.out.println("Decimal: " + decimal); System.out.println("Binary: " + binary); // 11111111 System.out.println("Octal: " + octal); // 377 System.out.println("Hex: " + hex); // ff // Other bases to decimal int fromBinary = Integer.parseInt("1010", 2); int fromOctal = Integer.parseInt("77", 8); int fromHex = Integer.parseInt("FF", 16); System.out.println("\nBinary 1010 = " + fromBinary); // 10 System.out.println("Octal 77 = " + fromOctal); // 63 System.out.println("Hex FF = " + fromHex); // 255 } }

4. Statistics Calculator

import java.util.ArrayList; public class Statistics { public static void main(String[] args) { ArrayList<Integer> scores = new ArrayList<>(); scores.add(85); scores.add(92); scores.add(78); scores.add(95); scores.add(88); // Calculate average int sum = 0; for (Integer score : scores) { sum += score; // Auto-unboxing } double average = (double)sum / scores.size(); // Find max and min Integer max = scores.get(0); Integer min = scores.get(0); for (Integer score : scores) { if (score > max) max = score; if (score < min) min = score; } System.out.println("Scores: " + scores); System.out.printf("Average: %.2f\n", average); System.out.println("Highest: " + max); System.out.println("Lowest: " + min); System.out.println("Range: " + (max - min)); // Output: // Scores: [85, 92, 78, 95, 88] // Average: 87.60 // Highest: 95 // Lowest: 78 // Range: 17 } }

5. Configuration Parser

import java.util.HashMap; public class ConfigParser { public static void main(String[] args) { // Simulate config file HashMap<String, String> config = new HashMap<>(); config.put("port", "8080"); config.put("timeout", "30"); config.put("debug", "true"); config.put("maxConnections", "100"); // Parse values int port = Integer.parseInt(config.get("port")); int timeout = Integer.parseInt(config.get("timeout")); boolean debug = Boolean.parseBoolean(config.get("debug")); int maxConn = Integer.parseInt(config.get("maxConnections")); System.out.println("Port: " + port); System.out.println("Timeout: " + timeout + " seconds"); System.out.println("Debug mode: " + debug); System.out.println("Max connections: " + maxConn); // With defaults for missing values int retries = Integer.parseInt( config.getOrDefault("retries", "3") ); System.out.println("Retries: " + retries); // 3 (default) } }

Common Mistakes

Mistake 1: Using == Instead of equals()

// ❌ WRONG Integer a = 1000; Integer b = 1000; if (a == b) { // false! Different objects System.out.println("Equal"); } // ✅ CORRECT if (a.equals(b)) { // true! Same value System.out.println("Equal"); }

Mistake 2: Not Checking for Null

// ❌ WRONG Integer score = null; int total = score + 10; // NullPointerException! // ✅ CORRECT Integer score = null; if (score != null) { int total = score + 10; } else { System.out.println("Score is null"); }

Mistake 3: Incorrect String Parsing

// ❌ WRONG String str = "123abc"; int num = Integer.parseInt(str); // NumberFormatException! // ✅ CORRECT try { int num = Integer.parseInt(str); } catch (NumberFormatException e) { System.out.println("Invalid number: " + str); }

Mistake 4: Using Deprecated Constructor

// ❌ DEPRECATED (Java 9+) Integer num = new Integer(10); // ✅ CORRECT Integer num = Integer.valueOf(10); // or Integer num = 10; // Autoboxing

Wrapper Classes Summary

PrimitiveWrapperParse MethodValue Method
byteByteparseByte()byteValue()
shortShortparseShort()shortValue()
intIntegerparseInt()intValue()
longLongparseLong()longValue()
floatFloatparseFloat()floatValue()
doubleDoubleparseDouble()doubleValue()
charCharacter-charValue()
booleanBooleanparseBoolean()booleanValue()

Quick Reference Guide

// ========== CREATION ========== Integer num = 10; // Autoboxing Integer num = Integer.valueOf(10); // valueOf() Integer num = Integer.valueOf("10"); // From string // ========== CONVERSION ========== int primitive = Integer.parseInt("123"); // String → primitive Integer wrapper = Integer.valueOf("123"); // String → wrapper String str = Integer.toString(123); // Number → string String str = num.toString(); // Instance method // ========== COMPARISON ========== num1.equals(num2) // Value comparison num1.compareTo(num2) // Returns -1, 0, or 1 Integer.compare(a, b) // Static comparison // ========== CONSTANTS ========== Integer.MAX_VALUE // 2147483647 Integer.MIN_VALUE // -2147483648 Integer.SIZE // 32 (bits) Boolean.TRUE / FALSE // true / false // ========== SPECIAL ========== Double.isNaN(value) // Check if NaN Double.isInfinite(value) // Check if infinite Character.isLetter(ch) // Check if letter Character.isDigit(ch) // Check if digit

Practice Exercises

Exercise 1: Sum Calculator

Read numbers from user and calculate sum.

Solution
import java.util.ArrayList; import java.util.Scanner; public class SumCalculator { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); ArrayList<Integer> numbers = new ArrayList<>(); System.out.println("Enter numbers (type 'done' to finish):"); while (true) { String input = scanner.nextLine(); if (input.equalsIgnoreCase("done")) { break; } try { int num = Integer.parseInt(input); numbers.add(num); } catch (NumberFormatException e) { System.out.println("Invalid number, try again"); } } int sum = 0; for (Integer num : numbers) { sum += num; } System.out.println("Numbers: " + numbers); System.out.println("Sum: " + sum); System.out.println("Average: " + (double)sum / numbers.size()); scanner.close(); } }

Exercise 2: Grade Converter

Convert numerical grades to letter grades.

Solution
public class GradeConverter { public static void main(String[] args) { Integer[] scores = {95, 87, 78, 92, 65, 58}; for (Integer score : scores) { String grade; if (score >= 90) grade = "A"; else if (score >= 80) grade = "B"; else if (score >= 70) grade = "C"; else if (score >= 60) grade = "D"; else grade = "F"; System.out.println("Score " + score + " = Grade " + grade); } } }

Exercise 3: Character Counter

Count letters, digits, and special characters.

Solution
public class CharacterCounter { public static void main(String[] args) { String text = "Hello123! How are you?"; int letters = 0; int digits = 0; int spaces = 0; int special = 0; for (char ch : text.toCharArray()) { if (Character.isLetter(ch)) { letters++; } else if (Character.isDigit(ch)) { digits++; } else if (Character.isWhitespace(ch)) { spaces++; } else { special++; } } System.out.println("Text: " + text); System.out.println("Letters: " + letters); System.out.println("Digits: " + digits); System.out.println("Spaces: " + spaces); System.out.println("Special: " + special); } }

Key Takeaways

Why Use Wrapper Classes:

  • ›Collections require objects (ArrayList)
  • ›Can represent null values
  • ›Provide utility methods (parseInt, toString)
  • ›Enable generics

Autoboxing/Unboxing:

  • ›Automatic conversion: primitive ↔ wrapper
  • ›Convenient but has performance cost
  • ›Watch for NullPointerException

Always Use equals():

  • ›Never use == for value comparison
  • ›== checks object reference, not value
  • ›Use .equals() for proper comparison

Common Methods:

  • ›parseInt() - String to primitive
  • ›valueOf() - String to wrapper
  • ›toString() - Number to string
  • ›xxxValue() - Wrapper to primitive

Null Safety:

  • ›Wrapper can be null, primitive cannot
  • ›Always check for null before unboxing
  • ›Use default values for safety

Master wrapper classes and handle data conversions like a pro! 🚀

What to Read Next

Practice Programs

Put this topic into practice — each program has full code, output and a step-by-step explanation you can run online.

Browse all Java programs →