Data Types

Data types define the type of data a variable can hold. They are essential for declaring variables and performing operations on data. Java has two main categories of data types:

  • Primitive Data Types – Simple values like numbers, characters, or true/false.
  • Non – Primitive / Reference Data Types – Complex types like Strings, Arrays, and Objects.

Primitive Data Types

Data Type Size Stores Example
byte 1 byte Small integers (-128 to 127) byte age = 25;
short 2 bytes Medium integers (-32,768 to 32,767) short year = 2025;
int 4 bytes Whole numbers int salary = 50000;
long 8 bytes Large numbers long distance = 123456789L;
float 4 bytes Decimal numbers float price = 19.99f;
double 8 bytes Precise decimals double pi = 3.14159;
char 2 bytes Single character char grade = 'A';
boolean 1 bit True/False boolean isJavaFun = true;

Reference Data Types

Data Type Description Example
String A sequence of characters String name = "Java";
Array A collection of similar types of elements int[] numbers = {1, 2, 3, 4};
Class A blueprint for creating objects class Dog { String breed = "Labrador"; }
Dog myDog = new Dog();
Object An instance of a class Dog pet = new Dog();
System.out.println(pet.breed);
Interface A contract that a class must follow interface Animal { void sound(); }

Differences Between Primitive & Non-Primitive Types

Each data type in Java has a specific use case, determining how much memory it consumes and the operations you can perform on it.

Feature Primitive Data Types Non-Primitive Data Types
Definition Stores simple values directly in memory. Stores references to objects in memory.
Examples int, char, float, boolean String, Array, Class, Object
Memory Usage Less memory, as values are stored directly. More memory, as it stores references.
Methods Cannot call methods directly. Has built-in methods (e.g., String.length()).
Null Value Cannot be null (except Boolean in wrappers). Can be null (e.g., String name = null;).
Performance Faster, as operations work directly on values. Slower, as objects need to be referenced.
Usage Best for simple values like numbers and characters. Best for complex data structures like objects and arrays.