Primitive Types
About
Primitive types are the most basic data types in Java, directly supported by the language. They represent simple values rather than objects and are stored in stack memory for efficient access. Java provides eight primitive types, grouped based on the kind of data they represent.
Java's primitive types are categorized as follows:
Category
Type
Size
Default Value
Examples
Integer Types
byte
1 byte (8 bits)
0
-128
to 127
short
2 bytes (16 bits)
0
-32,768
to 32,767
int
4 bytes (32 bits)
0
-2^31
to (2^31)-1
long
8 bytes (64 bits)
0L
-2^63
to (2^63)-1
Floating Point
float
4 bytes (32 bits)
0.0f
3.40282347e+38
double
8 bytes (64 bits)
0.0
1.79769313486231570e+308
Character
char
2 bytes (16 bits)
'\u0000'
Unicode characters (e.g., 'A')
Boolean
boolean
1 bit
false
true
or false
Characteristics of Primitive Types
Memory Efficiency: Stored in stack memory, primitives are lightweight and fast to access.
Immutable: Values of primitive types cannot be changed after initialization.
No Methods: Unlike objects, primitives do not have associated methods (e.g.,
int
cannot call.toString()
directly).Default Values:
For instance variables, primitives are initialized to their default values.
For local variables, explicit initialization is required; otherwise, the compiler throws an error.
Type Conversion and Promotion
Implicit Conversion
Smaller types (e.g.,
byte
,short
) are automatically converted to larger types (int
,long
,float
, ordouble
).Example:
Explicit Conversion (Casting)
Larger types must be explicitly cast to smaller types, which may result in loss of precision.
Example:
Wrapper Classes
Each primitive type has a corresponding wrapper class in java.lang
to provide object-like behavior. Examples include:
int -> Integer
double -> Double
boolean -> Boolean
char -> Character
long -> Long
byte -> Byte
short -> Short
Wrapper classes are used in:
Collections (e.g.,
ArrayList<Integer>
)Autoboxing and Unboxing
Best Practices
Use primitives for performance-critical applications.
Use wrapper classes when working with collections or requiring nullability.
Choose the appropriate type based on memory and precision requirements.
Common Use Cases
Counters and Indices:
int
is often used in loops.Flags:
boolean
variables for control flow.Numeric Calculations:
float
anddouble
for mathematical operations.
Last updated
Was this helpful?