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.
1. What 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.
2. Why 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.
3. Real-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.
4. Syntax
javadataType variableName = value;
5. Example 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: Pune6. Key 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.