Java Variables

Java Variables
In Java Variables is a container used to store data values. It allows us to reuse and manipulate data in a program.
Example:
Why Variables?
To store data (number, text, etc.)
To use the value later in the program
To perform calculations
Syntax of Variable
Examples:
Rules for Naming Variables
| Rule | Example |
|---|---|
| Can’t start with a number | 1age , age1 |
Only letters, numbers, _, $ allowed | totalAmount, _value, $data |
| Case-sensitive | Age and age are different |
| Must not use keywords | class, while, static |
Best Practice → Use camelCase:
studentNametotalMarks
Declaring & Assigning Variables
Declare and assign later:
Declare and assign together:
Updating Variables
Multiple Variable Declaration
Output:
Final Variables (Constants)
Use final keyword to create a constant value — it cannot be changed.
If you try to change it:
Variable Types
| Type | Example | Description |
|---|---|---|
| Local Variable | inside a method | Temporary, must be initialized |
| Instance Variable | inside a class, outside method | Non-static variable |
| Static Variable | declared with static keyword | Shared among all objects |
Example:
Example Program
Summary
| Feature | Example |
|---|---|
| Declare Variable | int x; |
| Assign Value | x = 10; |
| Declare + Assign | int x = 10; |
| Constant | final int PI = 3; |
| Naming | camelCase recommended |
