-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path6. wrapper classes in java.txt
More file actions
40 lines (34 loc) · 2.23 KB
/
6. wrapper classes in java.txt
File metadata and controls
40 lines (34 loc) · 2.23 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
Java provides wrapper classes for each of its primitive data types
using these classes, we can treat the primitive data types as objects
int primitiveInt = 10; //primitive integer 10
Integer wrapperInt = Integer.valueOf(10); //wrapper integer 10
key features:
since these are classes, there are methods and states which can be accessed by the objects of these wrapper classes
these methods can convert types, parse types, and much more
unlike the primitives, these types can be null since they are references to the objects of the wrapper classes
instances of wrapper classes are immutable
manual conversions between the wrapper class and corresponding primitives:
-Integer wrapperInt = Integer.valueOf(primitiveInt) // primitive -> wrapper
-int primitiveInt = wrapperInt.intValue(); // wrapper -> primitive
automatic conversion between the wrapper class and corresponding primitives:
-this is done by the compiler
-Autoboxing:
-conversion of primitive type to wrapper
-it happes when we:
-assign a primitive type to a wrapper class variable
-pass a primitive as a parameter to the function which expects the wrapper class variable
-adding primitives to collections that stores objects
-unboxing:
-conversion of wrapper class instance to primitive data type
-it happes when we:
-assign a wrapper class variable to a primitive type
-pass a wrapper class instance as a parameter to the function which expects the primitive type variable
-adding wrapper class objects to collections that stores primitives
applications:
-collections and generics can work only with objects and therefore in order to store primitives, we need the
wrapper classes and the autoboxing and unboxing sort of concepts
-plays important role in method overloading by accepting both the primitives and wrapper classes
important considerations:
-Performance: Frequent boxing and unboxing can lead to performance overhead due to object creation and garbage collection.
-Null Values: Unboxing a null wrapper object results in a NullPointerException.
-Equality Checks: Be cautious when comparing wrapper objects using == and equals() since the == operator checks for reference equality, while equals() checks for value equality.