Primitive and Wrapper types
In Java, primitive types are basic data types that are not
objects. They hold simple values directly, without referring to any other
memory location. On the other hand, wrapper types are classes that encapsulate
primitive types, allowing them to be treated as objects. Wrapper types provide
additional functionality and are commonly used in scenarios where objects are
required, such as collections or generics. Here's a brief overview of primitive
types and their corresponding wrapper types in Java:
Primitive Types:
byte: 8-bit integer (-128 to 127)
short: 16-bit integer (-32,768 to 32,767)
int: 32-bit integer (-2^31 to 2^31 - 1)
long: 64-bit integer (-2^63 to 2^63 - 1)
float: 32-bit floating-point number (IEEE 754)
double: 64-bit floating-point number (IEEE 754)
char: 16-bit Unicode character
boolean: Represents true or false
Wrapper Types:
Byte: Wrapper for byte
Short: Wrapper for short
Integer: Wrapper for int
Long: Wrapper for long
Float: Wrapper for float
Double: Wrapper for double
Character: Wrapper for char
Boolean: Wrapper for boolean
Wrapper types provide several advantages over primitive
types:
They allow primitive values to be used in contexts that
require objects, such as collections (e.g., List<Integer>).
They provide utility methods for converting between
primitive types and strings, parsing strings into primitive values, and
performing other operations.
They offer the ability to store null, which is not possible
with primitive types.
Here's an example demonstrating the usage of primitive types
and their corresponding wrapper types:
public class
PrimitiveVsWrapper {
public static void main(String[] args) {
// Primitive type
int primitiveInt = 10;
// Wrapper type
Integer wrapperInt =
Integer.valueOf(10);
// Autoboxing (converting primitive
type to wrapper type automatically)
Integer autoBoxedInt = 20;
// Unboxing (converting wrapper type to
primitive type automatically)
int unboxedInt = wrapperInt.intValue();
// Using wrapper types in collections
List<Integer> numbers = new
ArrayList<>();
numbers.add(30);
numbers.add(wrapperInt);
System.out.println("Primitive int:
" + primitiveInt);
System.out.println("Wrapper
Integer: " + wrapperInt);
System.out.println("AutoBoxed
Integer: " + autoBoxedInt);
System.out.println("Unboxed int:
" + unboxedInt);
System.out.println("Numbers list:
" + numbers);
}
}
Understanding the differences between primitive and wrapper
types is important for Java developers when working with various data
structures, APIs, and libraries.