R
Rishtaara
Java Fundamentals
Lesson 3 of 36Article16 min

Variables & Data Types

A variable is a named box that holds a value. Declare the type first, then the name: int age = 20;

Variables — storing values

A variable is a named box that holds a value. Declare the type first, then the name: int age = 20;

Java variables must have a type. You cannot put a string into an int box without conversion.

Real-life example: A variable is a labeled jar in the kitchen. The label (type) says "only rice" or "only sugar" — you cannot mix them by accident.

Declaring variables
int age = 20;
double price = 99.50;
char grade = 'A';
boolean active = true;
String name = "Asha";

Data Types — primitives and String

Primitive types: byte, short, int, long, float, double, char, boolean. String is a class (reference type) for text.

int for whole numbers, double for decimals, boolean for true/false, char for one character.

Real-life example: Data types are different measuring cups — you use a cup for flour (int) and a jug for milk (double). Wrong cup = wrong recipe.

Common types
byte small = 127;
int count = 1000;
long big = 9_000_000_000L;
float ratio = 3.14f;
double pi = 3.14159;
char letter = 'Z';
boolean isStudent = true;
String city = "Mumbai";