0
0
Javaprogramming~5 mins

Why variables are needed in Java

Choose your learning style9 modes available
Introduction

Variables help us store and remember information in a program. They let us use names to keep data so we can use or change it later.

When you want to save a user's name to greet them later.
When you need to keep track of a score in a game.
When you want to store a number to use in calculations.
When you want to remember a choice the user made.
When you want to update and reuse information multiple times.
Syntax
Java
type variableName = value;

type is the kind of data (like int for numbers, String for text).

variableName is the name you give to the storage spot.

Examples
This stores the number 25 in a variable named age.
Java
int age = 25;
This stores the text "Alice" in a variable named name.
Java
String name = "Alice";
This stores a decimal number in price.
Java
double price = 19.99;
Sample Program

This program shows how a variable score stores a number, prints it, then changes it and prints again.

Java
public class Main {
    public static void main(String[] args) {
        int score = 10; // store score
        System.out.println("Score is: " + score);
        score = score + 5; // update score
        System.out.println("New score is: " + score);
    }
}
OutputSuccess
Important Notes

Variables make programs flexible because you can change the stored data anytime.

Choosing clear variable names helps others understand your code.

Summary

Variables store information to use later in a program.

They let you save, update, and reuse data easily.

Using variables makes your code clearer and more flexible.