Data Types in Java

Data types in Java define the type and size of data that can be stored in a variable. They are broadly classified into two categories: primitive and non-primitive. Data types help programmers create variables to store data efficiently and ensure the correct type of value is assigned.

Primitive Data Types

Primitive data types are basic types used to store single values. They are predefined in Java and have fixed sizes.

Overview Table of Primitive Data Types

Data Category Data Type Size (Bytes) Range Default Value Example
Integer byte 1 -128 to 127 0 byte b = 100;
short 2 -32,768 to 32,767 0 short s = 1000;
int 4 -2,147,483,648 to 2,147,483,647 0 int i = 50000;
long 8 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 0L long l = 12345678901L;
Floating-Point float 4 ±3.4E-38 to ±3.4E+38 (7 digits) 0.0f float f = 5.75f;
double 8 ±1.7E-308 to ±1.7E+308 (15 digits) 0.0d double d = 3.14159;
Character char 2 0 to 65,535 (Unicode) '\u0000' char c = 'A';
Boolean boolean 1 bit true or false false boolean flag = true;

Detailed Explanation of Primitive Data Types

  1. Byte

    Note: Ideal for saving memory when dealing with small numbers.

  2. Short

    Note: Less commonly used but helpful in specific scenarios like legacy systems.

  3. Int

    Note: Any integer literal (e.g., 42) is treated as an int by default.

  4. Long

    Note: Use the suffix L or l for literals exceeding int capacity (e.g., 12345678901L). If the value fits within int range, the suffix is optional, but L is preferred for clarity.

  5. Float

    Note: Requires the suffix f or F for literals (e.g., 5.75f). Integers stored in float are converted to decimals (e.g., 5 becomes 5.0). Precision is limited beyond 7 digits.

  6. Double

    Note: No suffix is needed for decimal literals, as double is the default. For large integers exceeding int or long ranges assigned to double, use L (e.g., 12345678901L), though this is rare.

  7. Char

    Note: Characters are enclosed in single quotes (' '). Java uses Unicode, but ASCII (0–127) is common (e.g., 'A' = 65, 'a' = 97, '0' = 48). The extra 8 bits support international characters.

  8. Boolean

    Note: Used for conditions and flags.


Non-Primitive Data Types

Non-primitive data types are derived from classes or interfaces and can store multiple values or complex data. They are created by the programmer or provided by Java.

Examples of Non-Primitive Data Types