Primitive Data Types and Wrapper Classes
1. Primitive Data Types in Java
Java has 8 primitive data types, which are the most basic types of data built into the language. They are not objects and are stored directly in memory for performance.
Type | Size | Default Value | Description | Example |
---|---|---|---|---|
byte | 1 byte (8-bit) | 0 | Small integers (-128 to 127) | byte a = 10; |
short | 2 bytes | 0 | Larger than byte (-32,768 to 32,767) | short b = 1000; |
int | 4 bytes | 0 | Common for integers | int c = 12345; |
long | 8 bytes | 0L | Very large integers | long d = 100000L; |
float | 4 bytes | 0.0f | Single-precision decimal | float e = 3.14f; |
double | 8 bytes | 0.0d | Double-precision decimal (default) | double f = 3.14159; |
char | 2 bytes | '\u0000' | Single 16-bit Unicode character | char g = 'A'; |
boolean | 1 bit (virtual) | false | Logical true/false | boolean h = true; |
📦 2. Wrapper Classes in Java
Java provides wrapper classes in the java.lang
package for each primitive data type. These allow primitives to be treated as objects.
Primitive | Wrapper Class |
---|---|
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
char | Character |
boolean | Boolean |
🔍 Why Use Wrapper Classes?
-
Required when working with collections like
ArrayList
, which only store objects. -
Useful for type conversion, parsing from strings, and using object methods.
-
Enable null values (primitives cannot be null).
🔁 Autoboxing and Unboxing
Java automatically converts between primitives and wrappers:
Concept | Description | Example |
---|---|---|
Autoboxing | primitive ➝ object (wrapper class) | Integer x = 10; |
Unboxing | object ➝ primitive | int y = x; |
✅ Example Code
📝 Summary Table
Feature | Primitive Type | Wrapper Class |
---|---|---|
Memory Efficient | ✅ | ❌ |
Part of Object Hierarchy | ❌ | ✅ |
Works with Collections | ❌ | ✅ |
Can be null | ❌ | ✅ |
Autoboxed/Unboxed | — | ✅ |
Comments
Post a Comment