-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWrapperExample.java
More file actions
55 lines (45 loc) · 1.91 KB
/
WrapperExample.java
File metadata and controls
55 lines (45 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
public class WrapperExample {
public static void main(String[] args) {
// Wrapper Classes in Java
/**
* Wrapper classes are objects that wrap primitive data types.
* They allow primitives to be used in contexts that require objects
* (e.g., Collections like ArrayList, or when using generics).
*
* Each primitive type has a corresponding wrapper class:
* byte -> Byte
* short -> Short
* int -> Integer
* long -> Long
* float -> Float
* double -> Double
* char -> Character
* boolean -> Boolean
*
* Wrapper classes can be null and provide useful methods for conversion and comparison.
*/
// Primitive to Wrapper (Autoboxing)
int numInt = 42;
Integer wrappedInt = numInt; // Automatically converted to Integer object
// Wrapper to Primitive (Unboxing)
int unboxedInt = wrappedInt; // Automatically converted back to int
// Wrapper class examples
Byte numByte = 127;
Short numShort = 32_767;
Integer numInteger = 2_147_483_647;
Long numLong = 9_223_372_036_854_775_807L;
Float numFloat = 3.14F;
Double numDouble = 3.141592653589793;
Character letter = 'A';
Boolean bool = Boolean.TRUE;
// Useful Wrapper class methods
System.out.println("Integer to String: " + numInteger.toString());
System.out.println("String to Integer: " + Integer.parseInt("100"));
System.out.println("Compare Integers: " + Integer.compare(10, 20));
System.out.println("Character to Lowercase: " + Character.toLowerCase(letter));
System.out.println("Boolean value: " + bool);
// Nullability (Wrapper can be null, primitives cannot)
Integer nullableInt = null;
System.out.println("Nullable Integer: " + nullableInt);
}
}