In Java, variables are like containers where you can store data. Think of them as labeled boxes — you give them a name, put something inside, and later you can take it out or even replace it with something new.
What can you do with variables?
Store Data
You can keep values like numbers, text, or true/false in a variable.
int age = 25; // storing a number String name = "John"; // storing text
Change Data
Variables can hold different values during the program’s execution.
age = 26; // changing the value of 'age'
Reuse Data
Instead of typing the same value again, you can use the variable.
System.out.println("My age is " + age);
Perform Calculations
You can use variables in math operations.
int sum = age + 4;
Improve Readability
Using variables makes your code easier to understand.
double pi = 3.14159; // easier to read than typing the number everywhere
public class VariablesExample { public static void main(String[] args) { // Storing data int age = 25; String name = "John"; double height = 5.9; boolean isStudent = true; // Using variables System.out.println("Name: " + name); System.out.println("Age: " + age); System.out.println("Height: " + height); System.out.println("Student: " + isStudent); // Changing data age = 26; // updating value System.out.println("Updated Age: " + age); // Calculations int yearsToRetire = 60 - age; System.out.println("Years to retire: " + yearsToRetire); } }
Top comments (0)