Variables
Overview
Welcome to Java! Let's start with the most fundamental building block: Variables. Think of a variable as a labeled storage box in your computer's memory. When you play a video game, the game needs to remember your score, your health, and your player name. It stores these pieces of information in variables. Without variables, a program wouldn't be able to remember anything!
In Java, every variable must have a specific 'type' (like text or numbers) and a unique 'name' (the label on the box).
1. Declaring a Variable
Before you can use a box, you have to create it. You do this by telling Java what *type* of data the box will hold, followed by the box's *name*.
2. Initializing a Variable
Initializing just means putting a value inside the box for the very first time using the equals sign (`=`).
3. Constants (final)
Sometimes you want a box to be locked forever so nobody can change what's inside (like the value of Pi or a maximum score limit). In Java, we use the `final` keyword for this.
Syntax
To declare and initialize a variable, specify the DataType, then the variableName, and then assign it a value.
// Syntax: DataType variableName = value;
int playerHealth = 100; // A box holding an integer (whole number)
String playerName = "Hero"; // A box holding text (String)
double coinMultiplier = 1.5; // A box holding a decimal number
System.out.println(playerName + " has " + playerHealth + " health.");Adding 'final' locks the variable so it cannot be changed later.
final int MAX_LEVEL = 50;
// MAX_LEVEL = 51; // ❌ ERROR! You cannot change a final variable.Common Pitfalls
- Using an uninitialized variable. If you declare `int age;` but don't assign it a value, Java will refuse to run the code until you do.
- Naming variables confusingly (e.g., `int a = 10;`). Always use descriptive names like `int studentAge = 10;`.
Interview Tips
- In interviews, emphasize that Java is 'strongly typed'. You cannot put text into an integer box. The compiler will catch this error immediately.
Real-World Example
Variables are used everywhere. Imagine tracking a student's profile in a college portal.
public class StudentProfile {
public static void main(String[] args) {
String studentName = "Kartik Rai";
int currentSemester = 3;
double cgpa = 8.5;
boolean isEnrolled = true;
System.out.println("Student: " + studentName);
System.out.println("CGPA: " + cgpa);
}
}