Variables and Data Types · Lesson 4 of 42
Variables in Java
A variable is a named place in memory that holds a value. In Java every variable has a type that is fixed when you declare it – an int stays an int for its whole life. That strictness feels slow at first, but it is the reason the compiler can catch so many mistakes before your program ever runs.
In this lesson
- Declaring, initialising and updating variables
- Naming rules and Java conventions
- Local type inference with
var - Constants with
finaland variable scope
Declare, initialise, use
public class Main {
public static void main(String[] args) {
int age; // declaration: type + name
age = 21; // initialisation
double cgpa = 8.4; // both in one line
String name = "Ananya";
boolean placed = false;
age = age + 1; // update
System.out.println(name + " is " + age + ", CGPA " + cgpa + ", placed: " + placed);
}
}
Ananya is 22, CGPA 8.4, placed: false
Each variable: a type, a name, a value
age22intcgpa8.4doublename"Ananya"String (a reference)placedfalseboolean
Common mistake: using a local variable before assigning it
int total; System.out.println(total); does not compile: variable total might not have been initialized. Local variables get no default value – you must assign one first. (Fields inside a class do get defaults, as you'll see in chapter 8.)
Naming rules and conventions
The compiler enforces the rules; your team enforces the conventions.
- Names may contain letters, digits,
_and$, but cannot start with a digit. - They are case-sensitive and cannot be keywords like
class,intornew.
| Kind | Convention | Example |
|---|---|---|
| Variables and methods | camelCase | totalMarks, calculateTax() |
| Classes and interfaces | PascalCase | StudentRecord |
| Constants | UPPER_SNAKE_CASE | MAX_ATTEMPTS |
| Packages | all lowercase, reversed domain | com.learnfrenzy.app |
Choose names that explain meaning: daysUntilExam beats d. Reviewers in real projects will ask you to rename vague variables.
var: let the compiler infer the type
Since Java 10, local variables can be declared with var. The type is still fixed – the compiler simply works it out from the value on the right.
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
var city = "Hyderabad"; // String
var count = 42; // int
var price = 199.99; // double
var skills = new ArrayList<String>(); // ArrayList<String>
skills.add("Java");
System.out.println(city + " " + count + " " + price + " " + skills);
}
}
Hyderabad 42 199.99 [Java]
varworks only for local variables with an initial value – not for fields, method parameters or return types.var x = 5; x = "five";is still an error:xis anint.- Use it when the type is obvious from the right-hand side; write the type out when it helps readability.
Constants with final
public class Main {
static final double GST_RATE = 0.18; // class constant
public static void main(String[] args) {
final int maxLogins = 3; // local constant
double price = 1000;
System.out.println("With GST: " + price * (1 + GST_RATE));
System.out.println("Max logins: " + maxLogins);
// maxLogins = 5; → error: cannot assign a value to final variable maxLogins
}
}
With GST: 1180.0 Max logins: 3
Scope: where a variable lives
A variable exists only inside the block { } where it is declared. Once the block ends, the name is gone.
public class Main {
public static void main(String[] args) {
int total = 0; // visible in the whole main method
for (int i = 1; i <= 3; i++) { // i lives only inside the loop
int square = i * i; // square too
total += square;
}
System.out.println("Total: " + total);
// System.out.println(i); → error: cannot find symbol
}
}
Total: 14
Nested scopes
- Classfields such as GST_RATE – visible to all methods
- Methodtotal – visible from its declaration to the end of main
- Block (loop / if)i and square – gone when the block ends
Java also forbids declaring a second local variable with the same name inside a nested block – a safety rule that prevents confusing "shadowing" bugs.
Practice
Try it yourself
Store a product name, price and quantity, then print the total bill.
Show solution
public class Main { public static void main(String[] args) { String product = "Notebook"; double price = 45.5; int quantity = 4; System.out.println(product + " total: " + price * quantity); } }Notebook total: 182.0
Swap two int variables using a temporary variable.
Show solution
public class Main { public static void main(String[] args) { int a = 5, b = 9; int temp = a; a = b; b = temp; System.out.println(a + " " + b); } }9 5
Quick check
Can you write var total; without a value?
No. var needs an initial value so the compiler can infer the type.
What does final do on a variable?
It can be assigned only once; later assignments are compile errors.
Do local variables get a default value?
No. They must be assigned before use. Only fields get defaults (0, false, null).
Summary
- Variables have a fixed type:
type name = value; - Use camelCase for variables, PascalCase for classes, UPPER_CASE for constants.
varinfers local types;finalmakes constants; scope ends at the closing brace.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.