Lesson 2 • Beginner
Variables and Data Types
Variables are how your program remembers things. Learn how Java stores numbers, text, and true/false values — and why types matter.
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.
Without variables:
System.out.println(25); // What does 25 mean? Age? Score? Quantity?
With variables:
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 holds
Examples:
int 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 character
Why 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 later
3️⃣ 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:
int ⭐
Whole numbers (no decimals)
int age = 25; int score = 100; int temperature = -5;
Range: about -2 billion to +2 billion
double ⭐
Decimal numbers
double price = 19.99; double pi = 3.14159; double weight = 72.5;
Up to 15 digits of precision
String ⭐
Text (any words or sentences)
String name = "Alice"; String city = "London"; String message = "Hello!";
Always use double quotes " "
boolean ⭐
True or false (yes or no)
boolean isStudent = true; boolean isRaining = false; boolean hasAccess = true;
Only two possible values
🧠 Tip:
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.
Try It: Create Your Own Variables
Practice declaring different variable types and printing them. Try changing the values!
// 💡 Try modifying this code and see what happens!
// === EXERCISE: Create variables about yourself! ===
console.log("=== Java Variables — The 4 Main Types ===");
console.log("");
// In Java: int age = 25;
let age = 25;
console.log("int age = " + age);
// In Java: double height = 1.75;
let height = 1.75;
console.log("double height = " + height);
// In Java: String name = "Alice";
let name = "Alice";
console.log('String name = "' + name + '"');
// In Java: boolean isStudent = true;
let isSt
...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) |
🧠 Rule of thumb:
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"
==. Use .equals() instead.== checks if two variables point to the same object in memory..equals() checks if the text content is the same.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 PI
🧠 Naming convention:
Constants 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:
✅ Widening (Safe — Automatic)
Small type → big type. No data lost.
int num = 42; double d = num; // 42 → 42.0 // Java does this automatically!
⚠️ Narrowing (Risky — Manual)
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 → doubleTry It: Types, Casting, and String Operations
See how different types work, what happens when you cast, and how to join strings with numbers.
// 💡 Try modifying this code and see what happens!
console.log("=== Java Data Types in Action ===");
console.log("");
// The 4 main types
console.log("1️⃣ THE FOUR MAIN TYPES:");
let myAge = 25; // int
let myHeight = 1.75; // double
let myName = "Alice"; // String
let isHappy = true; // boolean
console.log(" int age = " + myAge);
console.log(" double height = " + myHeight);
console.log(' String name = "' + myName + '"');
console.log(" boolean isHappy = " + isHappy);
...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,publicare reserved - Names are case-sensitive:
age,Age, andAGEare 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 |
❌ Bad names:
int x = 25; String s = "London"; double tp = 19.99;
Meaningless — what is x, s, tp?
✅ Good names:
int age = 25; String city = "London"; double totalPrice = 19.99;
Clear and descriptive.
Try It: Build a Mini Shopping Calculator
Use variables to calculate a shopping total with tax and discount — a real-world use of everything you've learned!
// 💡 Try modifying this code and see what happens!
// === MINI PROJECT: Shopping Calculator ===
console.log("╔══════════════════════════════════╗");
console.log("║ SHOPPING CALCULATOR ║");
console.log("╚══════════════════════════════════╝");
console.log("");
// Step 1: Define your items (variables!)
// In Java: double shirtPrice = 29.99;
let shirtPrice = 29.99;
let pantsPrice = 49.99;
let shoesPrice = 89.99;
let quantity = 1; // one of each
console.log("📦 Your Cart:");
console
...Common Beginner Mistakes
- ❌ Integer division surprise:
int result = 7 / 2;gives3, not3.5. To get decimals, use7.0 / 2or cast:(double) 7 / 2 - ❌ Comparing Strings with ==:
"hello" == "hello"sometimes works by luck, butnew String("hello") == new String("hello")isfalse. 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. Use3000000000L - ❌ Missing f for float:
float f = 3.14;fails because3.14is treated as double. Use3.14f - ❌ Using single quotes for Strings:
String name = 'Alice';is wrong. Single quotes are only forchar:'A'
💡 Pro Tips
- 💡 Use meaningful names:
studentAgeis better thansa. 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 than1000000.
📋 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.
Next up: Operators — learn arithmetic, comparison, and logical operations to make your programs calculate, compare, and decide.
Sign up for free to track which lessons you've completed and get learning reminders.