Java variables

A Java variable has a type and can hold a primitive value or a reference. Its declaration determines its scope and lifetime.

A simple example

Change a stored number

  1. Start with n starts at 2
  2. Do this Add 1 to n
  3. Result 3
After the assignment, reading the same variable gives its new value.
Main.java
class Main {
    public static void main(String[] args) throws Exception {
        int n = 2;
        n++;
        System.out.println(n);
    }
}
Output
3
Notebooks: 3 × 125¢ = 375¢. Delivery: 50¢. Amount to pay: 425¢.
Check a stationery order

A student buys three notebooks at 125 cents each. Add the 50-cent delivery charge once for the whole order. Keeping the arithmetic in cents makes the total easy to check against the receipt.

Types of Variable in Java

  1. Local Variable
  2. Instance Variable
    • Non-static Instance Variable
    • Static field
Random Access Memory (RAM)
Date Type: int
Name: age
6
Date Type: String
Name: str
Hello World
Date Type: boolean
Name: flag
true
Date Type: double
Name: diameter
15.63