JavaData Types

Java Data Types

What Are Data Types in Java?

In Java, data types define the kind of data a variable can hold. They help the compiler understand:

  • What type of value is being stored

  • How much memory to allocate

  • What operations are allowed on that data

Java is a statically typed language, which means every variable must be declared with a data type before use.

Categories of Java Data Types

Category

Description

Primitive Data Types

Basic types that store simple values directly

Non-Primitive Data Types

Reference types that store memory addresses of objects

1. Primitive Data Types

Java supports 8 primitive data types, each with a specific size and range.

Data Type

Size

Default Value

Description

byte

1 byte

0

Whole numbers from -128 to 127

short

2 bytes

0

Whole numbers from -32,768 to 32,767

int

4 bytes

0

Whole numbers from -2,147,483,648 to 2,147,483,647

long

8 bytes

0L

Large whole numbers

float

4 bytes

0.0f

Decimal numbers with single precision

double

8 bytes

0.0d

Decimal numbers with double precision

char

2 bytes

\u0000

Single Unicode character

boolean

1 bit

false

True or false values

Example: Using Primitive Data Types

Java
public class DataTypeDemo {
    public static void main(String[] args) {
        byte b = 100;
        short s = 30000;
        int i = 100000;
        long l = 123456789L;
        float f = 5.75f;
        double d = 19.99;
        char c = 'A';
        boolean isJavaFun = true;

        System.out.println("Byte: " + b);
        System.out.println("Short: " + s);
        System.out.println("Int: " + i);
        System.out.println("Long: " + l);
        System.out.println("Float: " + f);
        System.out.println("Double: " + d);
        System.out.println("Char: " + c);
        System.out.println("Boolean: " + isJavaFun);
    }
}
2. Non-Primitive (Reference) Data Types

These types refer to objects and include:

  • String

  • Arrays

  • Classes

  • Interfaces

They store references (memory addresses) rather than actual values.

Example: Using Non-Primitive Types

Java
public class ReferenceTypeDemo {
    public static void main(String[] args) {
        String message = "Welcome to Java!";
        int[] numbers = {10, 20, 30};

        System.out.println("Message: " + message);
        System.out.println("First number: " + numbers[0]);
    }
}
Key Differences Between Primitive and Non-Primitive Types

Feature

Primitive Types

Non-Primitive Types

Stores actual value

Yes

No (stores reference)

Memory efficient

Yes

Depends on object

Built-in operations

Supported

Requires methods

Default values

Yes

Yes (null for objects)

Best Practices
Tip
Use the most memory-efficient type (byte, short) when possible. Prefer int and double for general-purpose calculations. Use boolean for flags and conditions. Use String for textual data. Always initialize variables before use.