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

  1. Memory Efficiency: Stored in stack memory, primitives are lightweight and fast to access.

  2. Immutable: Values of primitive types cannot be changed after initialization.

  3. No Methods: Unlike objects, primitives do not have associated methods (e.g., int cannot call .toString()directly).

  4. 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, or double).

  • Example:

    int num = 100;
    double d = num; // Implicit widening

Explicit Conversion (Casting)

  • Larger types must be explicitly cast to smaller types, which may result in loss of precision.

  • Example:

    double d = 100.99;
    int num = (int) d; // Explicit narrowing

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

  1. Use primitives for performance-critical applications.

  2. Use wrapper classes when working with collections or requiring nullability.

  3. Choose the appropriate type based on memory and precision requirements.

Common Use Cases

  1. Counters and Indices: int is often used in loops.

  2. Flags: boolean variables for control flow.

  3. Numeric Calculations: float and double for mathematical operations.

Last updated

Was this helpful?