Variables & Data Types
Reviewed & published by Brayan K
Variables are how your program remembers things. Learn how Java stores numbers, text, and true/false values — and why types matter.
Part of the free Java course at LearnCodingFast — hands-on lessons with worked examples and the output they print, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
- What a variable is and why you need them
- How to declare variables with specific data types
- All 8 primitive types and when to use each one
- Reference types: String, arrays, and null
- Constants with the final keyword
- Type casting — converting between types safely
1️⃣ What Is a Variable? (Plain English)
A variable is a named container that holds a value. Your program uses variables to remember information — like a person's name, their age, or whether they're a student.
💡 Analogy: Think of variables as labeled jars in a kitchen. Each jar has a label (the variable name) and a specific shape (the type). A jar shaped for cookies can't hold soup — similarly, an int variable can't hold text.
System.out.println(25); // What does 25 mean? Age? Score? Quantity?int age = 25;
System.out.println(age); // Clear! This is someone's age.Variables make your code readable and reusable. Instead of typing 25 everywhere, you type age — and if the age changes, you only update it in one place.
2️⃣ How to Create a Variable in Java
In Java, creating a variable has a strict format. You must tell Java three things:
type name = value;
↑ ↑ ↑ ↑
| | | └── The data you want to store
| | └─────── The equals sign means "assign this value"
| └──────────── The name you choose for the variable
└────────────────── What kind of data this variable holdsint age = 25; // A whole number
double price = 19.99; // A decimal number
String name = "Alice"; // Text
boolean isStudent = true; // True or false
char grade = 'A'; // A single characterWhy does Java need types?
In JavaScript or Python, you can put anything in any variable. In Java, you must declare the type upfront. This seems annoying at first, but it prevents bugs. If you accidentally try to store text in a number variable, the compiler catches it before your program runs.
❌ This fails in Java:
int age = "twenty-five";
// Error: incompatible types✅ JavaScript would allow it:
let age = "twenty-five";
// Works, but may cause bugs later3️⃣ The 4 Types You'll Use 95% of the Time
Java has many types, but you really only need to know four to get started:
Whole numbers (no decimals)
int age = 25;
int score = 100;
int temperature = -5;Range: about -2 billion to +2 billion
double price = 19.99;
double pi = 3.14159;
double weight = 72.5;Up to 15 digits of precision
Text (any words or sentences)
String name = "Alice";
String city = "London";
String message = "Hello!";Always use double quotes " "
True or false (yes or no)
boolean isStudent = true;
boolean isRaining = false;
boolean hasAccess = true;Only two possible values
Start with just these four types. You can build entire programs with int, double, String, and boolean. Learn the other types later when you actually need them.
public class Main {
public static void main(String[] args) {
// The 4 main types
int age = 25;
double height = 1.75;
String name = "Alice";
boolean isStudent = true;
System.out.println("int age = " + age);
System.out.println("double height = " + height);
System.out.println("String name = \"" + name + "\"");
System.out.println("boolean isStudent = " + isStudent);
// Using variables in expressions
int birthYear = 2024 - age;
System.out.println("Birth year: " + birthYear);
int nextAge = age + 1;
System.out.println("Next year you'll be: " + nextAge);
String greeting = "Hello, " + name + "!";
System.out.println(greeting);
System.out.println(name + " is a student: " + isStudent);
// Variables can change (but their TYPE cannot)
System.out.println("Age before birthday: " + age);
age = 26;
System.out.println("Age after birthday: " + age);
}
}4️⃣ All 8 Primitive Types (Complete Reference)
Java has exactly 8 primitive types. These store raw values directly in memory. You've already learned the main ones — here's the complete list:
| Type | Size | What It Stores | When to Use |
|---|---|---|---|
| int | 32 bits | -2.1B to 2.1B | ⭐ Default for whole numbers |
| double | 64 bits | Decimals (15 digits) | ⭐ Default for decimals |
| boolean | 1 bit | true / false | ⭐ Flags, conditions |
| char | 16 bits | One character | Single letters: 'A', '9', '!' |
| byte | 8 bits | -128 to 127 | File data, network bytes |
| short | 16 bits | -32,768 to 32,767 | Rarely used |
| long | 64 bits | Very large numbers | Timestamps, huge counts |
| float | 32 bits | Decimals (7 digits) | Graphics, games (saves memory) |
Use int for whole numbers. Use double for decimals. Use boolean for yes/no. Use String for text. That covers 95% of cases.
5️⃣ Strings — Working with Text
String is the most commonly used reference type. It represents text — any sequence of characters wrapped in double quotes.
String name = "Alice";
String empty = ""; // An empty string (valid!)
String number = "42"; // This is text, NOT a number!String Concatenation (joining text together):
String first = "John";
String last = "Doe";
String fullName = first + " " + last; // "John Doe"
// You can also join strings with numbers:
int age = 25;
String message = "I am " + age + " years old";
// Result: "I am 25 years old"String a = new String("hello");
String b = new String("hello");
a == b // false (different objects!)
a.equals(b) // true (same text content)6️⃣ Constants — Values That Never Change
Sometimes you have values that should never change — like the value of pi, tax rates, or maximum scores. Use the final keyword:
final double PI = 3.14159;
final int MAX_SCORE = 100;
final String APP_NAME = "MyApp";
// Try to change it?
PI = 3.14; // ❌ ERROR: cannot assign a value to final variable PIConstants use ALL_CAPS with underscores: MAX_USERS, TAX_RATE, DATABASE_URL. This makes them instantly recognizable in your code.
7️⃣ Type Casting — Converting Between Types
Sometimes you need to convert data from one type to another. Java has two kinds of casting:
Small type → big type. No data lost.
int num = 42;
double d = num; // 42 → 42.0
// Java does this automatically!Big type → small type. May lose data!
double price = 19.99;
int rounded = (int) price; // 19
// The .99 is GONE — not rounded!💡 Analogy: Widening is like pouring water from a small cup into a big bucket — nothing is lost. Narrowing is like pouring from a bucket into a small cup — the overflow is gone forever.
Converting String to number:
String ageText = "25";
int age = Integer.parseInt(ageText); // String → int
double price = Double.parseDouble("19.99"); // String → doublepublic class Main {
public static void main(String[] args) {
// Type casting: widening (safe, automatic)
int intNum = 42;
double asDouble = intNum; // 42 -> 42.0
System.out.println("Widening: int " + intNum + " -> double " + asDouble);
// Narrowing (manual, may lose data)
double pi = 3.99;
int asInt = (int) pi; // drops the .99
System.out.println("Narrowing: double " + pi + " -> int " + asInt);
// Integer division gotcha
System.out.println("7 / 2 = " + (7 / 2)); // 3, not 3.5
System.out.println("7.0 / 2 = " + (7.0 / 2)); // 3.5
// Constants
final int MAX_SCORE = 100;
final double TAX_RATE = 0.2;
System.out.println("final int MAX_SCORE = " + MAX_SCORE);
System.out.println("final double TAX_RATE = " + TAX_RATE);
// String to number
String priceText = "19.99";
double priceNum = Double.parseDouble(priceText);
double withTax = priceNum * (1 + TAX_RATE);
System.out.printf("With 20%% tax: £%.2f%n", withTax);
}
}8️⃣ Naming Your Variables — Rules and Conventions
Rules (Java will refuse to compile if you break these):
- Names can contain letters, digits, underscores _, and dollar signs $
- Names cannot start with a digit: 1stPlace ❌, firstPlace ✅
- Names cannot be Java keywords: int, class, public are reserved
- Names are case-sensitive: age, Age, and AGE are three different variables
Conventions (not enforced, but everyone follows them):
| Style | Used For | Examples |
|---|---|---|
| camelCase | Variables & methods | firstName, totalPrice, isActive |
| PascalCase | Classes | StudentRecord, BankAccount |
| ALL_CAPS | Constants | MAX_SIZE, PI, TAX_RATE |
int x = 25;
String s = "London";
double tp = 19.99;Meaningless — what is x, s, tp?
int age = 25;
String city = "London";
double totalPrice = 19.99;public class Main {
public static void main(String[] args) {
// Item prices
double shirtPrice = 29.99;
double pantsPrice = 49.99;
double shoesPrice = 89.99;
System.out.printf("Shirt: $%.2f%n", shirtPrice);
System.out.printf("Pants: $%.2f%n", pantsPrice);
System.out.printf("Shoes: $%.2f%n", shoesPrice);
// Subtotal
double subtotal = shirtPrice + pantsPrice + shoesPrice;
System.out.printf("Subtotal: $%.2f%n", subtotal);
// 10% discount (constant)
final double DISCOUNT_RATE = 0.10;
double discount = subtotal * DISCOUNT_RATE;
System.out.printf("Discount (10%%): -$%.2f%n", discount);
// 8% tax
final double TAX_RATE = 0.08;
double afterDiscount = subtotal - discount;
double tax = afterDiscount * TAX_RATE;
System.out.printf("Tax (8%%): +$%.2f%n", tax);
// Final total
double total = afterDiscount + tax;
System.out.printf("TOTAL: $%.2f%n", total);
// Boolean check
boolean canAfford = total < 200;
System.out.println("Can I afford it (budget $200)? " + canAfford);
}
}public class Main {
public static void main(String[] args) {
// 🎯 YOUR TURN — replace each ___ using the hint beside it.
// 1) Nights are counted, never split in half.
___ nights = 5; // 👉 replace ___ with int
// 2) A price with pence in it needs a decimal type.
___ pricePerNight = 74.50; // 👉 replace ___ with double
// 3) A city tax that must never be reassigned.
___ double CITY_TAX = 2.75; // 👉 replace ___ with final
// 4) One character, in single quotes — not a String.
char currency = ___; // 👉 replace ___ with '$'
double room = pricePerNight * nights;
double tax = CITY_TAX * nights;
double total = room + tax;
System.out.println("Nights: " + nights);
System.out.printf("Room: %c%.2f%n", currency, room);
System.out.printf("Tax: %c%.2f%n", currency, tax);
System.out.printf("Total: %c%.2f%n", currency, total);
// 5) A comparison gives back true or false.
boolean underBudget = total < ___; // 👉 replace ___ with 400
System.out.println("Under $400? " + underBudget);
}
}Common Beginner Mistakes
- ❌ Integer division surprise: int result = 7 / 2; gives 3, not 3.5. To get decimals, use 7.0 / 2 or cast: (double) 7 / 2
- ❌ Comparing Strings with ==: "hello" == "hello" sometimes works by luck, but new String("hello") == new String("hello") is false. Always use .equals()
- ❌ Uninitialized local variables: int x; System.out.println(x); is an error. Local variables must be assigned before use
- ❌ Missing L for long: long big = 3000000000; fails because Java treats the number as int first. Use 3000000000L
- ❌ Missing f for float: float f = 3.14; fails because 3.14 is treated as double. Use 3.14f
- ❌ Using single quotes for Strings: String name = 'Alice'; is wrong. Single quotes are only for char: 'A'
💡 Pro Tips
- 💡 Use meaningful names: studentAge is better than sa. Future-you will thank present-you.
- 💡 Declare variables close to where you use them: Don't put all declarations at the top — declare each variable right before you need it.
- 💡 Use var (Java 10+): var name = "Alice"; lets Java infer the type. Great for long type names, but use explicit types while learning.
- 💡 Use underscores in big numbers: int million = 1_000_000; is much more readable than 1000000.
📋 Quick Reference
| Action | Syntax | Example |
|---|---|---|
| Declare + assign | type name = value; | int age = 25; |
| Declare only | type name; | int age; |
| Constant | final type NAME = val; | final int MAX = 100; |
| Widen cast | double d = intVar; | Automatic, safe |
| Narrow cast | int i = (int) doubleVar; | Manual, may truncate |
| String → int | Integer.parseInt("123") | Throws error if not a number |
| String → double | Double.parseDouble("1.5") | Throws error if not a number |
| Compare Strings | str1.equals(str2) | Never use == for Strings! |
🎉 Lesson Complete!
Excellent work! You now understand Java's type system — the foundation of everything you'll build. You know the 4 essential types (int, double, String, boolean), how to declare constants, cast between types, and name variables like a professional.
Practice quiz
Which type would you use to store a whole number like someone's age?
- double
- String
- int
- boolean
Answer: int. int stores whole numbers; double is for decimals, String for text, boolean for true/false.
What does int result = 7 / 2; store?
- 3.5
- 3
- 4
- 3.0
Answer: 3. Dividing two ints performs integer division — the decimal part is dropped, giving 3.
Which keyword makes a variable a constant that can never be reassigned?
- const
- static
- final
- let
Answer: final. final marks a variable as a constant; reassigning it is a compile error.
How should you correctly compare the text content of two Strings?
- a == b
- a.equals(b)
- a = b
- a.compare(b)
Answer: a.equals(b). Use .equals() to compare String content; == compares object references, not text.
Which is a WIDENING conversion that Java does automatically?
- double d = intVar;
- int i = (int) doubleVar;
- int i = "5";
- char c = stringVar;
Answer: double d = intVar;. int to double is widening (safe, automatic). Narrowing double to int requires an explicit cast.
What does (int) 3.99 evaluate to?
- 4
- 3
- 3.99
- 0
Answer: 3. Casting a double to int truncates (drops) the decimal part — it does not round — giving 3.
Which variable name is INVALID in Java?
- firstPlace
- _count
- 1stPlace
- totalPrice
Answer: 1stPlace. Variable names cannot start with a digit, so 1stPlace is invalid.
How do you convert the String "25" into an int?
- Integer.parseInt("25")
- (int) "25"
- int.parse("25")
- "25".toInt()
Answer: Integer.parseInt("25"). Integer.parseInt("25") parses a String into an int.
How many primitive types does Java have?
- 4
- 6
- 8
- 10
Answer: 8. Java has exactly 8 primitive types: byte, short, int, long, float, double, char, boolean.
Which naming convention is used for variables and methods in Java?
- PascalCase
- ALL_CAPS
- snake_case
- camelCase
Answer: camelCase. Variables and methods use camelCase; PascalCase is for classes and ALL_CAPS for constants.
Continue this course
- Previous: Introduction to Java
- Next: Data Types (Primitives & Ranges) — All 8 primitive types, their ranges, and when to use each
- Quick reference: Java cheat sheet › Basics