Java: Variables and Types
⏱ 15 min read
A variable is a named container that stores a value. Java is a statically-typed language — you must declare what type of data a variable holds before you use it.
The 4 Most Important Primitive Types:
int — stores whole numbers (-2 billion to 2 billion)
Example: int age = 25;
double — stores decimal numbers (15 digits precision)
Example: double price = 9.99;
boolean — stores only true or false
Example: boolean isStudent = true;
char — stores a single character (use single quotes)
Example: char grade = 'A';
Other Primitive Types:
long — very large whole numbers, add L suffix. Example: long big = 9876543210L;
float — smaller decimal numbers, add f suffix. Example: float pi = 3.14f;
byte — tiny whole numbers (-128 to 127)
short — small whole numbers (-32768 to 32767)
The String Type:
String is not a primitive — it is a class. It stores text. Use double quotes.
Example: String name = "Alice";
Useful methods: name.length(), name.toUpperCase(), name.contains("li")
Constants with final:
Add the final keyword to make a variable unchangeable. Use ALL_CAPS names by convention.
Example: final double PI = 3.14159;
Naming Rules:
Variable names must start with a letter, $ or _. They cannot contain spaces or be Java keywords. Use camelCase: firstName, totalScore, isActive.
The 4 Most Important Primitive Types:
int — stores whole numbers (-2 billion to 2 billion)
Example: int age = 25;
double — stores decimal numbers (15 digits precision)
Example: double price = 9.99;
boolean — stores only true or false
Example: boolean isStudent = true;
char — stores a single character (use single quotes)
Example: char grade = 'A';
Other Primitive Types:
long — very large whole numbers, add L suffix. Example: long big = 9876543210L;
float — smaller decimal numbers, add f suffix. Example: float pi = 3.14f;
byte — tiny whole numbers (-128 to 127)
short — small whole numbers (-32768 to 32767)
The String Type:
String is not a primitive — it is a class. It stores text. Use double quotes.
Example: String name = "Alice";
Useful methods: name.length(), name.toUpperCase(), name.contains("li")
Constants with final:
Add the final keyword to make a variable unchangeable. Use ALL_CAPS names by convention.
Example: final double PI = 3.14159;
Naming Rules:
Variable names must start with a letter, $ or _. They cannot contain spaces or be Java keywords. Use camelCase: firstName, totalScore, isActive.
Log in to track your progress and earn badges as you complete lessons.
Log In to Track Progress