Variables & Data Types
Variables are how your program remembers things. Learn how Java stores numbers, text, and true/false values — and why types matter.
Learn Variables & Data Types in our free Java course — a beginner-friendly interactive lesson with worked examples, a practice exercise and a quick reference.
Part of the free Java course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
What You'll Learn in This Lesson
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.
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:
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.
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:
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.
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
-32,768 to 32,767
Rarely used
long
Very large numbers
Timestamps, huge counts
float
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 Concatenation (joining text together):
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:
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:
💡 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.
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
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")
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.
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: Previous Lesson
- Next: Next Lesson