Introduction to Java · Lesson 9 of 150
Variables
A variable is a named container used to store a value that your program can use and change while it runs. Every variable in Java has a specific data type that decides what kind of value it can hold.
01What is a Variable?
A variable is a named container used to store a value that your program can use and change while it runs. Every variable in Java has a specific data type that decides what kind of value it can hold.
02Why is it used?
Variables let programs remember and reuse information instead of typing the same value repeatedly. For example, a variable can hold a user's age once, and that value can be used again anywhere in the program.
03Real-Life Example
A variable is like a labelled box in your room. You might have a box labelled "books" and another labelled "clothes." You can look inside, take something out, or replace what's inside — the label (variable name) stays the same, but its contents (value) can change.
04Syntax
javadataType variableName = value;
05Example Program
javapublic class VariableDemo { public static void main(String[] args) { int age = 20; String city = "Pune"; System.out.println("Age: " + age + ", City: " + city); } }
Output:
Age: 20, City: Pune06Key Points to Remember
- A variable must be declared with a data type before use.
- Variable names are case-sensitive (
ageandAgeare different). - A variable's value can change during program execution, but its type cannot.