DEV Community

Sathya7032
Sathya7032

Posted on

Understanding Variables in Java – The Basics Made Simple

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 
Enter fullscreen mode Exit fullscreen mode

Change Data
Variables can hold different values during the program’s execution.

age = 26; // changing the value of 'age' 
Enter fullscreen mode Exit fullscreen mode

Reuse Data
Instead of typing the same value again, you can use the variable.

System.out.println("My age is " + age); 
Enter fullscreen mode Exit fullscreen mode

Perform Calculations
You can use variables in math operations.

int sum = age + 4; 
Enter fullscreen mode Exit fullscreen mode

Improve Readability
Using variables makes your code easier to understand.

double pi = 3.14159; // easier to read than typing the number everywhere 
Enter fullscreen mode Exit fullscreen mode
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); } } 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)