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.
1public class WrapperIntro {
2 public static void main(String[] args) {
3 // Primitive type
4 int primitiveInt = 10;
5
6 // Wrapper class (Object)
7 Integer wrapperInt = Integer.valueOf(10);
8
9 System.out.println("Primitive: " + primitiveInt); // 10
10 System.out.println("Wrapper: " + wrapperInt); // 10
11
12 // Key difference: wrapper is an OBJECT
13 System.out.println(primitiveInt instanceof Object); // Error! Can't use instanceof with primitive
14 System.out.println(wrapperInt instanceof Object); // true
15 }
16}The 8 Wrapper Classes
Each primitive type has a corresponding wrapper class:
| Primitive | Wrapper Class | Package |
|---|---|---|
byte | Byte | java.lang |
short | Short | java.lang |
int | Integer | java.lang |
long | Long | java.lang |
float | Float | java.lang |
double | Double | java.lang |
char | Character | java.lang |
boolean | Boolean | java.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
1import java.util.ArrayList;
2
3public class CollectionExample {
4 public static void main(String[] args) {
5 // ❌ WRONG - ArrayList can't store primitives
6 // ArrayList<int> numbers = new ArrayList<>(); // Compile error!
7
8 // ✅ CORRECT - Use wrapper class
9 ArrayList<Integer> numbers = new ArrayList<>();
10 numbers.add(10); // Auto-boxing: int → Integer
11 numbers.add(20);
12 numbers.add(30);
13
14 System.out.println(numbers); // [10, 20, 30]
15
16 // Extract value
17 int value = numbers.get(0); // Auto-unboxing: Integer → int
18 System.out.println(value); // 10
19 }
20}Reason 2: Null Values
1public class NullExample {
2 public static void main(String[] args) {
3 // Primitives CANNOT be null
4 // int x = null; // Compile error!
5
6 // Wrapper classes CAN be null
7 Integer y = null; // OK!
8
9 System.out.println(y); // null
10
11 // Useful for database fields that might be NULL
12 Integer age = null; // Unknown age
13 if (age == null) {
14 System.out.println("Age not specified");
15 }
16 }
17}Reason 3: Utility Methods
1public class UtilityMethods {
2 public static void main(String[] args) {
3 // Convert string to int
4 String str = "123";
5 int num = Integer.parseInt(str);
6 System.out.println(num + 10); // 133
7
8 // Convert int to string
9 int value = 456;
10 String text = Integer.toString(value);
11 System.out.println(text + "789"); // "456789"
12
13 // Min/Max values
14 System.out.println("Max int: " + Integer.MAX_VALUE); // 2147483647
15 System.out.println("Min int: " + Integer.MIN_VALUE); // -2147483648
16
17 // Compare values
18 Integer a = 100;
19 Integer b = 200;
20 System.out.println(a.compareTo(b)); // -1 (a < b)
21 }
22}Autoboxing and Unboxing
Autoboxing: Automatic conversion from primitive to wrapper
Unboxing: Automatic conversion from wrapper to primitive
1public class AutoboxingExample {
2 public static void main(String[] args) {
3 // ========== AUTOBOXING ==========
4 // Manual boxing (old way - Java 1.4 and earlier)
5 Integer oldWay = Integer.valueOf(10);
6
7 // Autoboxing (Java 5+)
8 Integer newWay = 10; // Automatic: int → Integer
9
10 // More examples
11 Double d = 3.14; // double → Double
12 Boolean b = true; // boolean → Boolean
13 Character c = 'A'; // char → Character
14
15 // ========== UNBOXING ==========
16 Integer wrapper = 100;
17
18 // Manual unboxing (old way)
19 int oldPrimitive = wrapper.intValue();
20
21 // Auto-unboxing (Java 5+)
22 int newPrimitive = wrapper; // Automatic: Integer → int
23
24 // Use in arithmetic
25 Integer x = 50;
26 Integer y = 30;
27 int sum = x + y; // Auto-unbox both, then add
28 System.out.println(sum); // 80
29
30 // ========== MIXED OPERATIONS ==========
31 Integer num1 = 10;
32 int num2 = 20;
33
34 // Automatic conversions during operation
35 int result1 = num1 + num2; // num1 unboxed to int
36 Integer result2 = num1 + num2; // sum auto-boxed to Integer
37
38 System.out.println(result1); // 30
39 System.out.println(result2); // 30
40 }
41}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
1public class IntegerCreation {
2 public static void main(String[] args) {
3 // Method 1: Autoboxing (most common)
4 Integer num1 = 10;
5
6 // Method 2: valueOf() - returns cached object for -128 to 127
7 Integer num2 = Integer.valueOf(10);
8 Integer num3 = Integer.valueOf("123"); // From string
9
10 // Method 3: Constructor (deprecated since Java 9)
11 Integer num4 = new Integer(10); // Don't use!
12
13 System.out.println(num1); // 10
14 System.out.println(num2); // 10
15 System.out.println(num3); // 123
16 }
17}String Conversion Methods
1public class IntegerConversion {
2 public static void main(String[] args) {
3 // ========== STRING TO INT ==========
4
5 // parseInt() - returns primitive int
6 int num1 = Integer.parseInt("123");
7 System.out.println(num1); // 123
8 System.out.println(num1 + 10); // 133
9
10 // parseInt() with radix (base)
11 int binary = Integer.parseInt("1010", 2); // Binary to decimal
12 int hex = Integer.parseInt("FF", 16); // Hex to decimal
13 int octal = Integer.parseInt("77", 8); // Octal to decimal
14
15 System.out.println("Binary 1010 = " + binary); // 10
16 System.out.println("Hex FF = " + hex); // 255
17 System.out.println("Octal 77 = " + octal); // 63
18
19 // valueOf() - returns Integer object
20 Integer num2 = Integer.valueOf("456");
21 System.out.println(num2); // 456
22
23 // ========== INT TO STRING ==========
24
25 // toString() - static method
26 String str1 = Integer.toString(789);
27 System.out.println(str1); // "789"
28 System.out.println(str1 + "0"); // "7890"
29
30 // toString() - instance method
31 Integer num = 100;
32 String str2 = num.toString();
33 System.out.println(str2); // "100"
34
35 // Convert to different bases
36 String bin = Integer.toBinaryString(10); // "1010"
37 String oct = Integer.toOctalString(10); // "12"
38 String hexStr = Integer.toHexString(255); // "ff"
39
40 System.out.println("10 in binary: " + bin);
41 System.out.println("10 in octal: " + oct);
42 System.out.println("255 in hex: " + hexStr);
43 }
44}Useful Integer Methods
1public class IntegerMethods {
2 public static void main(String[] args) {
3 // ========== CONSTANTS ==========
4 System.out.println("MAX_VALUE: " + Integer.MAX_VALUE); // 2147483647
5 System.out.println("MIN_VALUE: " + Integer.MIN_VALUE); // -2147483648
6 System.out.println("SIZE: " + Integer.SIZE); // 32 (bits)
7 System.out.println("BYTES: " + Integer.BYTES); // 4
8
9 // ========== COMPARISON ==========
10 Integer a = 100;
11 Integer b = 200;
12 Integer c = 100;
13
14 // compareTo() - returns -1, 0, or 1
15 System.out.println(a.compareTo(b)); // -1 (a < b)
16 System.out.println(b.compareTo(a)); // 1 (b > a)
17 System.out.println(a.compareTo(c)); // 0 (a == c)
18
19 // compare() - static method
20 System.out.println(Integer.compare(100, 200)); // -1
21
22 // equals()
23 System.out.println(a.equals(c)); // true
24
25 // ========== VALUE EXTRACTION ==========
26 Integer num = 42;
27
28 int intValue = num.intValue();
29 long longValue = num.longValue();
30 double doubleValue = num.doubleValue();
31 float floatValue = num.floatValue();
32
33 System.out.println(intValue); // 42
34 System.out.println(longValue); // 42
35 System.out.println(doubleValue); // 42.0
36
37 // ========== UTILITY METHODS ==========
38
39 // Count bits
40 int bitCount = Integer.bitCount(7); // How many 1s in binary
41 System.out.println("Bit count of 7: " + bitCount); // 3 (binary: 111)
42
43 // Reverse bits
44 int reversed = Integer.reverse(1); // Reverse bit order
45
46 // Sum (Java 8+)
47 int sum = Integer.sum(10, 20);
48 System.out.println("Sum: " + sum); // 30
49
50 // Max/Min (Java 8+)
51 int max = Integer.max(10, 20);
52 int min = Integer.min(10, 20);
53 System.out.println("Max: " + max + ", Min: " + min); // 20, 10
54 }
55}Double Wrapper Class
For floating-point numbers.
1public class DoubleExample {
2 public static void main(String[] args) {
3 // ========== CREATION ==========
4 Double d1 = 3.14; // Autoboxing
5 Double d2 = Double.valueOf(2.718);
6 Double d3 = Double.valueOf("1.414");
7
8 // ========== STRING CONVERSION ==========
9
10 // String to double
11 double num1 = Double.parseDouble("3.14159");
12 System.out.println(num1); // 3.14159
13
14 // Double to String
15 String str = Double.toString(2.718);
16 System.out.println(str); // "2.718"
17
18 // ========== CONSTANTS ==========
19 System.out.println("MAX_VALUE: " + Double.MAX_VALUE);
20 System.out.println("MIN_VALUE: " + Double.MIN_VALUE); // Smallest positive value
21 System.out.println("POSITIVE_INFINITY: " + Double.POSITIVE_INFINITY);
22 System.out.println("NEGATIVE_INFINITY: " + Double.NEGATIVE_INFINITY);
23 System.out.println("NaN: " + Double.NaN); // Not a Number
24
25 // ========== SPECIAL CHECKS ==========
26 double x = 10.0 / 0.0; // Infinity
27 double y = 0.0 / 0.0; // NaN
28
29 System.out.println("x is infinite: " + Double.isInfinite(x)); // true
30 System.out.println("y is NaN: " + Double.isNaN(y)); // true
31 System.out.println("3.14 is finite: " + Double.isFinite(3.14)); // true
32
33 // ========== COMPARISON ==========
34 Double a = 3.14;
35 Double b = 2.71;
36
37 System.out.println(a.compareTo(b)); // 1 (a > b)
38
39 // Compare with tolerance (for floating-point precision)
40 double val1 = 0.1 + 0.2;
41 double val2 = 0.3;
42 System.out.println(val1 == val2); // false! (precision issue)
43
44 double epsilon = 0.00001;
45 boolean equal = Math.abs(val1 - val2) < epsilon;
46 System.out.println("Equal with tolerance: " + equal); // true
47
48 // ========== UTILITY METHODS ==========
49 Double num = 3.14159;
50
51 System.out.println("int value: " + num.intValue()); // 3
52 System.out.println("long value: " + num.longValue()); // 3
53
54 // Sum, max, min (Java 8+)
55 System.out.println("Sum: " + Double.sum(1.5, 2.5)); // 4.0
56 System.out.println("Max: " + Double.max(1.5, 2.5)); // 2.5
57 }
58}Boolean Wrapper Class
1public class BooleanExample {
2 public static void main(String[] args) {
3 // ========== CREATION ==========
4 Boolean b1 = true; // Autoboxing
5 Boolean b2 = Boolean.valueOf(false);
6 Boolean b3 = Boolean.valueOf("true"); // From string
7 Boolean b4 = Boolean.valueOf("false");
8
9 // ========== STRING CONVERSION ==========
10
11 // String to boolean
12 boolean val1 = Boolean.parseBoolean("true"); // true
13 boolean val2 = Boolean.parseBoolean("false"); // false
14 boolean val3 = Boolean.parseBoolean("yes"); // false! (only "true" is true)
15 boolean val4 = Boolean.parseBoolean("TRUE"); // true (case-insensitive)
16
17 System.out.println(val1); // true
18 System.out.println(val2); // false
19 System.out.println(val3); // false
20 System.out.println(val4); // true
21
22 // Boolean to String
23 String str = Boolean.toString(true);
24 System.out.println(str); // "true"
25
26 // ========== CONSTANTS ==========
27 System.out.println("TRUE: " + Boolean.TRUE); // true
28 System.out.println("FALSE: " + Boolean.FALSE); // false
29
30 // ========== COMPARISON ==========
31 Boolean a = true;
32 Boolean b = false;
33
34 System.out.println(a.compareTo(b)); // 1 (true > false)
35 System.out.println(a.equals(b)); // false
36
37 // ========== LOGICAL OPERATIONS ==========
38 boolean x = true;
39 boolean y = false;
40
41 System.out.println("AND: " + Boolean.logicalAnd(x, y)); // false
42 System.out.println("OR: " + Boolean.logicalOr(x, y)); // true
43 System.out.println("XOR: " + Boolean.logicalXor(x, y)); // true
44
45 // ========== PRACTICAL EXAMPLE ==========
46 String input = "yes";
47 boolean isYes = input.equalsIgnoreCase("yes") ||
48 input.equalsIgnoreCase("true") ||
49 input.equals("1");
50
51 Boolean result = Boolean.valueOf(isYes);
52 System.out.println("User said yes: " + result);
53 }
54}Character Wrapper Class
1public class CharacterExample {
2 public static void main(String[] args) {
3 // ========== CREATION ==========
4 Character ch1 = 'A'; // Autoboxing
5 Character ch2 = Character.valueOf('B');
6
7 // ========== CHARACTER CHECKS ==========
8 char c = 'A';
9
10 System.out.println("Is letter: " + Character.isLetter(c)); // true
11 System.out.println("Is digit: " + Character.isDigit(c)); // false
12 System.out.println("Is uppercase: " + Character.isUpperCase(c)); // true
13 System.out.println("Is lowercase: " + Character.isLowerCase(c)); // false
14 System.out.println("Is whitespace: " + Character.isWhitespace(c)); // false
15
16 // More checks
17 System.out.println("Is alphanumeric: " + Character.isLetterOrDigit('5')); // true
18 System.out.println("Is space: " + Character.isSpaceChar(' ')); // true
19
20 // ========== CASE CONVERSION ==========
21 char lower = 'a';
22 char upper = 'A';
23
24 System.out.println("To upper: " + Character.toUpperCase(lower)); // A
25 System.out.println("To lower: " + Character.toLowerCase(upper)); // a
26
27 // ========== ASCII VALUES ==========
28 char letter = 'A';
29 int ascii = (int)letter; // Or: Character.getNumericValue()
30
31 System.out.println("ASCII of A: " + ascii); // 65
32
33 char fromAscii = (char)65;
34 System.out.println("Char from 65: " + fromAscii); // A
35
36 // ========== COMPARISON ==========
37 Character a = 'A';
38 Character b = 'B';
39
40 System.out.println(a.compareTo(b)); // -1 (A < B)
41
42 // Static compare
43 System.out.println(Character.compare('X', 'Y')); // -1
44
45 // ========== PRACTICAL EXAMPLES ==========
46
47 // Count letters in string
48 String text = "Hello123 World!";
49 int letterCount = 0;
50
51 for (char ch : text.toCharArray()) {
52 if (Character.isLetter(ch)) {
53 letterCount++;
54 }
55 }
56
57 System.out.println("Letters: " + letterCount); // 10
58
59 // Check if alphanumeric
60 String password = "Pass123";
61 boolean isAlphaNum = true;
62
63 for (char ch : password.toCharArray()) {
64 if (!Character.isLetterOrDigit(ch)) {
65 isAlphaNum = false;
66 break;
67 }
68 }
69
70 System.out.println("Is alphanumeric: " + isAlphaNum); // true
71 }
72}Other Wrapper Classes
Byte Wrapper Class
1public class ByteExample {
2 public static void main(String[] args) {
3 // Byte range: -128 to 127
4 Byte b1 = 10;
5 Byte b2 = Byte.valueOf("20");
6
7 // Constants
8 System.out.println("MAX_VALUE: " + Byte.MAX_VALUE); // 127
9 System.out.println("MIN_VALUE: " + Byte.MIN_VALUE); // -128
10 System.out.println("SIZE: " + Byte.SIZE); // 8 bits
11
12 // Conversion
13 byte num = Byte.parseByte("50");
14 String str = Byte.toString((byte)100);
15
16 System.out.println(num); // 50
17 System.out.println(str); // "100"
18 }
19}Short Wrapper Class
1public class ShortExample {
2 public static void main(String[] args) {
3 // Short range: -32768 to 32767
4 Short s1 = 1000;
5 Short s2 = Short.valueOf("2000");
6
7 // Constants
8 System.out.println("MAX_VALUE: " + Short.MAX_VALUE); // 32767
9 System.out.println("MIN_VALUE: " + Short.MIN_VALUE); // -32768
10
11 // Conversion
12 short num = Short.parseShort("5000");
13 String str = Short.toString((short)10000);
14
15 System.out.println(num); // 5000
16 System.out.println(str); // "10000"
17 }
18}Long Wrapper Class
1public class LongExample {
2 public static void main(String[] args) {
3 // Long for large numbers
4 Long l1 = 1000000000L;
5 Long l2 = Long.valueOf("9999999999");
6
7 // Constants
8 System.out.println("MAX_VALUE: " + Long.MAX_VALUE);
9 // 9223372036854775807
10
11 System.out.println("MIN_VALUE: " + Long.MIN_VALUE);
12 // -9223372036854775808
13
14 // Conversion
15 long num = Long.parseLong("123456789");
16 String str = Long.toString(987654321L);
17
18 System.out.println(num); // 123456789
19 System.out.println(str); // "987654321"
20
21 // Binary, Octal, Hex
22 String binary = Long.toBinaryString(255L);
23 System.out.println("255 in binary: " + binary); // 11111111
24 }
25}Float Wrapper Class
1public class FloatExample {
2 public static void main(String[] args) {
3 Float f1 = 3.14f;
4 Float f2 = Float.valueOf("2.718");
5
6 // Constants
7 System.out.println("MAX_VALUE: " + Float.MAX_VALUE);
8 System.out.println("MIN_VALUE: " + Float.MIN_VALUE); // Smallest positive
9
10 // Conversion
11 float num = Float.parseFloat("1.414");
12 String str = Float.toString(2.5f);
13
14 System.out.println(num); // 1.414
15 System.out.println(str); // "2.5"
16
17 // Special values
18 System.out.println(Float.isNaN(0.0f / 0.0f)); // true
19 System.out.println(Float.isInfinite(1.0f / 0.0f)); // true
20 }
21}Wrapper Class Caching
Java caches certain wrapper objects for performance.
1public class CachingExample {
2 public static void main(String[] args) {
3 // ========== INTEGER CACHING (-128 to 127) ==========
4
5 Integer a = 100;
6 Integer b = 100;
7 System.out.println(a == b); // true (same cached object)
8
9 Integer c = 1000;
10 Integer d = 1000;
11 System.out.println(c == d); // false (different objects)
12
13 // Use equals() for value comparison
14 System.out.println(c.equals(d)); // true
15
16 // ========== WHY CACHING HAPPENS ==========
17
18 // valueOf() uses cache
19 Integer cached1 = Integer.valueOf(50);
20 Integer cached2 = Integer.valueOf(50);
21 System.out.println(cached1 == cached2); // true (same object)
22
23 // new Integer() creates new object (deprecated)
24 Integer notCached1 = new Integer(50);
25 Integer notCached2 = new Integer(50);
26 System.out.println(notCached1 == notCached2); // false
27
28 // ========== OTHER CACHED WRAPPERS ==========
29
30 // Boolean - both values cached
31 Boolean bool1 = true;
32 Boolean bool2 = true;
33 System.out.println(bool1 == bool2); // true
34
35 // Character - cached for 0 to 127
36 Character char1 = 'A'; // 65
37 Character char2 = 'A';
38 System.out.println(char1 == char2); // true
39
40 // Byte - all values cached (-128 to 127)
41 Byte byte1 = 10;
42 Byte byte2 = 10;
43 System.out.println(byte1 == byte2); // true
44 }
45}Rule: Always use .equals() for value comparison, not ==
Collections and Generics
Wrapper classes are essential for Java Collections.
1import java.util.*;
2
3public class CollectionsExample {
4 public static void main(String[] args) {
5 // ========== ARRAYLIST ==========
6
7 // Must use wrapper class
8 ArrayList<Integer> numbers = new ArrayList<>();
9
10 numbers.add(10); // Autoboxing
11 numbers.add(20);
12 numbers.add(30);
13
14 // Retrieve
15 int first = numbers.get(0); // Auto-unboxing
16 System.out.println("First: " + first); // 10
17
18 // Iterate
19 for (Integer num : numbers) {
20 System.out.print(num + " "); // 10 20 30
21 }
22 System.out.println();
23
24 // ========== HASHMAP ==========
25
26 HashMap<String, Integer> scores = new HashMap<>();
27
28 scores.put("Alice", 95);
29 scores.put("Bob", 87);
30 scores.put("Carol", 92);
31
32 int aliceScore = scores.get("Alice");
33 System.out.println("Alice's score: " + aliceScore); // 95
34
35 // ========== HASHSET ==========
36
37 HashSet<Double> prices = new HashSet<>();
38
39 prices.add(19.99);
40 prices.add(29.99);
41 prices.add(19.99); // Duplicate - won't be added
42
43 System.out.println("Unique prices: " + prices.size()); // 2
44
45 // ========== SORTING ==========
46
47 ArrayList<Integer> nums = new ArrayList<>(Arrays.asList(5, 2, 8, 1, 9));
48 Collections.sort(nums);
49
50 System.out.println("Sorted: " + nums); // [1, 2, 5, 8, 9]
51
52 // ========== MAX/MIN ==========
53
54 int max = Collections.max(nums);
55 int min = Collections.min(nums);
56
57 System.out.println("Max: " + max); // 9
58 System.out.println("Min: " + min); // 1
59 }
60}Null Handling
Wrapper classes can be null; primitives cannot.
1public class NullHandling {
2 public static void main(String[] args) {
3 // ========== NULL ASSIGNMENT ==========
4
5 Integer num = null; // OK
6 // int x = null; // Compile error!
7
8 System.out.println(num); // null
9
10 // ========== NULL POINTER EXCEPTION ==========
11
12 Integer value = null;
13
14 try {
15 int result = value + 10; // NullPointerException!
16 // Auto-unboxing tries to call value.intValue() on null
17 } catch (NullPointerException e) {
18 System.out.println("Error: Cannot unbox null");
19 }
20
21 // ========== SAFE NULL CHECKS ==========
22
23 Integer score = null;
24
25 // Method 1: Check before using
26 if (score != null) {
27 int total = score + 10;
28 System.out.println(total);
29 } else {
30 System.out.println("Score is null");
31 }
32
33 // Method 2: Use default value
34 int finalScore = (score != null) ? score : 0;
35 System.out.println("Final score: " + finalScore); // 0
36
37 // Method 3: Objects.requireNonNullElse() (Java 9+)
38 // int safeScore = Objects.requireNonNullElse(score, 0);
39
40 // ========== COLLECTIONS WITH NULL ==========
41
42 ArrayList<Integer> numbers = new ArrayList<>();
43 numbers.add(10);
44 numbers.add(null); // Allowed in ArrayList
45 numbers.add(20);
46
47 System.out.println(numbers); // [10, null, 20]
48
49 // Safe iteration
50 for (Integer num : numbers) {
51 if (num != null) {
52 System.out.println(num * 2);
53 } else {
54 System.out.println("Null value");
55 }
56 }
57 }
58}Practical Applications
1. Input Validation
1import java.util.Scanner;
2
3public class InputValidation {
4 public static void main(String[] args) {
5 Scanner scanner = new Scanner(System.in);
6
7 System.out.print("Enter your age: ");
8 String input = scanner.nextLine();
9
10 try {
11 int age = Integer.parseInt(input);
12
13 if (age >= 0 && age <= 150) {
14 System.out.println("Valid age: " + age);
15 } else {
16 System.out.println("Age out of range");
17 }
18
19 } catch (NumberFormatException e) {
20 System.out.println("Invalid number format");
21 }
22
23 scanner.close();
24 }
25}2. Data Type Conversion
1public class TypeConversion {
2 public static void main(String[] args) {
3 // ========== STRING TO NUMBERS ==========
4
5 String strInt = "123";
6 String strDouble = "45.67";
7 String strBool = "true";
8
9 int num1 = Integer.parseInt(strInt);
10 double num2 = Double.parseDouble(strDouble);
11 boolean bool = Boolean.parseBoolean(strBool);
12
13 System.out.println(num1); // 123
14 System.out.println(num2); // 45.67
15 System.out.println(bool); // true
16
17 // ========== NUMBERS TO STRING ==========
18
19 int age = 25;
20 double price = 19.99;
21 boolean active = true;
22
23 String str1 = Integer.toString(age);
24 String str2 = Double.toString(price);
25 String str3 = Boolean.toString(active);
26
27 System.out.println(str1); // "25"
28 System.out.println(str2); // "19.99"
29 System.out.println(str3); // "true"
30
31 // ========== BETWEEN NUMBER TYPES ==========
32
33 Integer intNum = 100;
34
35 double doubleVal = intNum.doubleValue();
36 long longVal = intNum.longValue();
37 byte byteVal = intNum.byteValue();
38
39 System.out.println(doubleVal); // 100.0
40 System.out.println(longVal); // 100
41 System.out.println(byteVal); // 100
42 }
43}3. Number System Conversions
1public class NumberSystems {
2 public static void main(String[] args) {
3 int decimal = 255;
4
5 // Decimal to other bases
6 String binary = Integer.toBinaryString(decimal);
7 String octal = Integer.toOctalString(decimal);
8 String hex = Integer.toHexString(decimal);
9
10 System.out.println("Decimal: " + decimal);
11 System.out.println("Binary: " + binary); // 11111111
12 System.out.println("Octal: " + octal); // 377
13 System.out.println("Hex: " + hex); // ff
14
15 // Other bases to decimal
16 int fromBinary = Integer.parseInt("1010", 2);
17 int fromOctal = Integer.parseInt("77", 8);
18 int fromHex = Integer.parseInt("FF", 16);
19
20 System.out.println("\nBinary 1010 = " + fromBinary); // 10
21 System.out.println("Octal 77 = " + fromOctal); // 63
22 System.out.println("Hex FF = " + fromHex); // 255
23 }
24}4. Statistics Calculator
1import java.util.ArrayList;
2
3public class Statistics {
4 public static void main(String[] args) {
5 ArrayList<Integer> scores = new ArrayList<>();
6 scores.add(85);
7 scores.add(92);
8 scores.add(78);
9 scores.add(95);
10 scores.add(88);
11
12 // Calculate average
13 int sum = 0;
14 for (Integer score : scores) {
15 sum += score; // Auto-unboxing
16 }
17 double average = (double)sum / scores.size();
18
19 // Find max and min
20 Integer max = scores.get(0);
21 Integer min = scores.get(0);
22
23 for (Integer score : scores) {
24 if (score > max) max = score;
25 if (score < min) min = score;
26 }
27
28 System.out.println("Scores: " + scores);
29 System.out.printf("Average: %.2f\n", average);
30 System.out.println("Highest: " + max);
31 System.out.println("Lowest: " + min);
32 System.out.println("Range: " + (max - min));
33
34 // Output:
35 // Scores: [85, 92, 78, 95, 88]
36 // Average: 87.60
37 // Highest: 95
38 // Lowest: 78
39 // Range: 17
40 }
41}5. Configuration Parser
1import java.util.HashMap;
2
3public class ConfigParser {
4 public static void main(String[] args) {
5 // Simulate config file
6 HashMap<String, String> config = new HashMap<>();
7 config.put("port", "8080");
8 config.put("timeout", "30");
9 config.put("debug", "true");
10 config.put("maxConnections", "100");
11
12 // Parse values
13 int port = Integer.parseInt(config.get("port"));
14 int timeout = Integer.parseInt(config.get("timeout"));
15 boolean debug = Boolean.parseBoolean(config.get("debug"));
16 int maxConn = Integer.parseInt(config.get("maxConnections"));
17
18 System.out.println("Port: " + port);
19 System.out.println("Timeout: " + timeout + " seconds");
20 System.out.println("Debug mode: " + debug);
21 System.out.println("Max connections: " + maxConn);
22
23 // With defaults for missing values
24 int retries = Integer.parseInt(
25 config.getOrDefault("retries", "3")
26 );
27 System.out.println("Retries: " + retries); // 3 (default)
28 }
29}Common Mistakes
Mistake 1: Using == Instead of equals()
1// ❌ WRONG
2Integer a = 1000;
3Integer b = 1000;
4if (a == b) { // false! Different objects
5 System.out.println("Equal");
6}
7
8// ✅ CORRECT
9if (a.equals(b)) { // true! Same value
10 System.out.println("Equal");
11}Mistake 2: Not Checking for Null
1// ❌ WRONG
2Integer score = null;
3int total = score + 10; // NullPointerException!
4
5// ✅ CORRECT
6Integer score = null;
7if (score != null) {
8 int total = score + 10;
9} else {
10 System.out.println("Score is null");
11}Mistake 3: Incorrect String Parsing
1// ❌ WRONG
2String str = "123abc";
3int num = Integer.parseInt(str); // NumberFormatException!
4
5// ✅ CORRECT
6try {
7 int num = Integer.parseInt(str);
8} catch (NumberFormatException e) {
9 System.out.println("Invalid number: " + str);
10}Mistake 4: Using Deprecated Constructor
1// ❌ DEPRECATED (Java 9+)
2Integer num = new Integer(10);
3
4// ✅ CORRECT
5Integer num = Integer.valueOf(10);
6// or
7Integer num = 10; // AutoboxingWrapper Classes Summary
| Primitive | Wrapper | Parse Method | Value Method |
|---|---|---|---|
| byte | Byte | parseByte() | byteValue() |
| short | Short | parseShort() | shortValue() |
| int | Integer | parseInt() | intValue() |
| long | Long | parseLong() | longValue() |
| float | Float | parseFloat() | floatValue() |
| double | Double | parseDouble() | doubleValue() |
| char | Character | - | charValue() |
| boolean | Boolean | parseBoolean() | booleanValue() |
Quick Reference Guide
1// ========== CREATION ==========
2Integer num = 10; // Autoboxing
3Integer num = Integer.valueOf(10); // valueOf()
4Integer num = Integer.valueOf("10"); // From string
5
6// ========== CONVERSION ==========
7int primitive = Integer.parseInt("123"); // String → primitive
8Integer wrapper = Integer.valueOf("123"); // String → wrapper
9String str = Integer.toString(123); // Number → string
10String str = num.toString(); // Instance method
11
12// ========== COMPARISON ==========
13num1.equals(num2) // Value comparison
14num1.compareTo(num2) // Returns -1, 0, or 1
15Integer.compare(a, b) // Static comparison
16
17// ========== CONSTANTS ==========
18Integer.MAX_VALUE // 2147483647
19Integer.MIN_VALUE // -2147483648
20Integer.SIZE // 32 (bits)
21Boolean.TRUE / FALSE // true / false
22
23// ========== SPECIAL ==========
24Double.isNaN(value) // Check if NaN
25Double.isInfinite(value) // Check if infinite
26Character.isLetter(ch) // Check if letter
27Character.isDigit(ch) // Check if digitPractice Exercises
Exercise 1: Sum Calculator
Read numbers from user and calculate sum.
Solution
1import java.util.ArrayList;
2import java.util.Scanner;
3
4public class SumCalculator {
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7 ArrayList<Integer> numbers = new ArrayList<>();
8
9 System.out.println("Enter numbers (type 'done' to finish):");
10
11 while (true) {
12 String input = scanner.nextLine();
13
14 if (input.equalsIgnoreCase("done")) {
15 break;
16 }
17
18 try {
19 int num = Integer.parseInt(input);
20 numbers.add(num);
21 } catch (NumberFormatException e) {
22 System.out.println("Invalid number, try again");
23 }
24 }
25
26 int sum = 0;
27 for (Integer num : numbers) {
28 sum += num;
29 }
30
31 System.out.println("Numbers: " + numbers);
32 System.out.println("Sum: " + sum);
33 System.out.println("Average: " + (double)sum / numbers.size());
34
35 scanner.close();
36 }
37}Exercise 2: Grade Converter
Convert numerical grades to letter grades.
Solution
1public class GradeConverter {
2 public static void main(String[] args) {
3 Integer[] scores = {95, 87, 78, 92, 65, 58};
4
5 for (Integer score : scores) {
6 String grade;
7
8 if (score >= 90) grade = "A";
9 else if (score >= 80) grade = "B";
10 else if (score >= 70) grade = "C";
11 else if (score >= 60) grade = "D";
12 else grade = "F";
13
14 System.out.println("Score " + score + " = Grade " + grade);
15 }
16 }
17}Exercise 3: Character Counter
Count letters, digits, and special characters.
Solution
1public class CharacterCounter {
2 public static void main(String[] args) {
3 String text = "Hello123! How are you?";
4
5 int letters = 0;
6 int digits = 0;
7 int spaces = 0;
8 int special = 0;
9
10 for (char ch : text.toCharArray()) {
11 if (Character.isLetter(ch)) {
12 letters++;
13 } else if (Character.isDigit(ch)) {
14 digits++;
15 } else if (Character.isWhitespace(ch)) {
16 spaces++;
17 } else {
18 special++;
19 }
20 }
21
22 System.out.println("Text: " + text);
23 System.out.println("Letters: " + letters);
24 System.out.println("Digits: " + digits);
25 System.out.println("Spaces: " + spaces);
26 System.out.println("Special: " + special);
27 }
28}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! 🚀