It is better to use the Primitive Class variable for the I/O operation unless there is a necessity of using the Wrapper Class. In this article, we can discuss briefly both wrapper class and primitive data type.
- A primitive data type focuses on variable values, without any additional methods.
- The Default value of Primitive class variables are given below,
Primitive Data types |
Default values |
---|---|
int |
0 |
byte |
0 |
short |
0 |
char |
\u0000 or null |
boolean |
false |
double |
0.0 |
float |
0.0 |
- The default value of the wrapper class is null as they are objects.
- Primitive classes are faster when compared to wrapper classes. However, the wrapper class allows null values but the primitive class does not allow any null values.
- Wrapper classes help the Java program be completely object-oriented whereas primitive data types help in the simple declaration of values with variables. They also help the code be serializable.
- For conversion of primitive data type to objects, wrapper class is used. We can see the conversion of the Primitive data type to objects using the code below,
Java
/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main(String[] args) { // primitive data type int n = 15 ; // Creating object from primitive data type Integer obj = Integer.valueOf(n); System.out.println(n + " " + obj); } } |
Output:
15 15
- If we have to serialize a primitive value, it must first be converted into objects using wrapper classes.
- Wrapper classes help in working with Collection variables.
Primitive data Type |
Wrapper Class |
---|---|
Even Large scale calculations can be made faster | When collections are used, a wrapper class is required |
Methods will return a value | Methods will return null |
mostly used when the variable should not be null or ‘\0’ | Used when the variable should be null |
- For knowing more about the usage of primitive data type to wrapper class, we need to focus on Autoboxing and Unboxing.
- We can convert a Wrapper Class into primitive data types is called Unboxing.
Java
/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main(String[] args) { // wrapper class to primitive datatype Integer a = new Integer( 6 ); // Unboxing int b = a; System.out.print(b); } } |
Output:
6
- We can also refer to the below-mentioned code of converting the primitive data type to wrapper class (Autoboxing).
Java
/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main(String[] args) { // converting primitive data type to wrapper class int a = 6 ; // Autoboxing Integer b = Integer.valueOf(a); System.out.println(b); } } |
Output:
6