Variables
Overview
Think of a variable as a labeled container or a storage box in your computer's memory. When you create a program, you often need to store information—like a user's age, a bank balance, or a player's name. A variable gives this piece of memory a name, so you can easily store, retrieve, and modify data while the program is running. Without variables, every piece of data would be hardcoded and rigid, making your programs static and useless in the real world.
Syntax
To declare a variable in Java, you must specify its Data Type (like int or String) followed by a unique name (identifier). The equals sign (=) assigns a value to it.
1// Syntax: DataType variableName = value;
2int age = 25; // Integer variable
3String name = "Alice"; // Text variable
4double price = 19.99; // Decimal variable
5
6System.out.println(name + " is " + age + " years old.");You can declare multiple variables on a single line. Furthermore, using the 'final' keyword makes the variable a constant—meaning once a value is assigned, it can never be changed. This is highly useful for defining mathematical constants or configuration values.
1// Declaring multiple variables of the same type
2int x = 10, y = 20, z = 30;
3
4// Creating a constant (immutable) variable using 'final'
5final double PI = 3.14159;
6
7// PI = 3.14; // ERROR: Cannot reassign a value to a final variableCommon Pitfalls
- Using an uninitialized local variable will cause a compilation error in Java.
- Naming variables confusingly (e.g., int a, b). Always use descriptive names like 'totalPrice' or 'userAge'.
Interview Tips
- In interviews, emphasize the difference between how Primitives are stored on the Stack vs how Objects are stored in the Heap.
Real-World Example
Variables are essential in any business logic. For example, tracking a user's shopping cart total in an e-commerce backend.
1public class ShoppingCart {
2 // Instance variables: attached to the object
3 private int itemCount = 0;
4 private double totalCost = 0.0;
5
6 public void addItem(double itemPrice) {
7 // Local variable: temporary within this method
8 double taxRate = 0.08;
9
10 itemCount++;
11 totalCost += itemPrice + (itemPrice * taxRate);
12 System.out.println("Cart total is now: $" + totalCost);
13 }
14}