Java Variables

A variable is a named memory location that stores a value. Its value can change while the program runs.

Java
int age = 21;          // declaration + initialization
String name = "Asha";
age = 22;              // value changed

Types of Variables

  1. Local variable: declared inside a method; exists only while the method runs.
  2. Instance variable: declared inside a class but outside methods; each object gets its own copy.
  3. Static variable: declared with static; one copy shared by all objects.
Java
class Student {
    static int count = 0;     // static variable
    String name;              // instance variable

    Student(String n) {
        name = n;
        count++;
    }

    public static void main(String[] args) {
        Student s1 = new Student("Meera");
        Student s2 = new Student("Ravi");
        int x = Student.count;   // local variable
        System.out.println("Count: " + x);
        System.out.println("Student: " + s2.name);
    }
}
Count: 2 Student: Ravi

Naming Rules

  • Can contain letters, digits, _ and $, but cannot start with a digit.
  • Cannot be a keyword (int, class, …).
  • Convention: camelCase such as totalMarks.
Track your progress through the Java course