Static and Non-Static Variables in Java

Published: (January 13, 2026 at 10:45 AM EST)
1 min read
Source: Dev.to

Source: Dev.to

Non-Static (Instance) Variables

In Java, a non‑static variable is declared inside a class but outside any method, without using the static keyword. Each object of the class gets its own separate copy of the variable.

Key Points

  • Created when an object is created
  • Each object has a different value
  • Stored in heap memory
  • Accessed using an object reference

Example

class Student {
    int marks;
}

public class Main {
    public static void main(String[] args) {
        Student s1 = new Student();
        Student s2 = new Student();

        s1.marks = 80;
        s2.marks = 90;

        System.out.println(s1.marks); // 80
        System.out.println(s2.marks); // 90
    }
}

Here, marks is a non‑static variable, so each Student object has its own value.

Static Variables

Static variables belong to the class rather than any individual object.

Key Points

  • Created once when the class is loaded
  • Shared among all objects
  • Stored in the method area
  • Accessed using the class name (recommended)

Example

public class Employee {
    String name;
    int salary;
    static String company_name = "TCS";

    public static void main(String[] args) {
        Employee mukesh = new Employee();
        mukesh.name = "Mukesh kumar";
        mukesh.salary = 10000;

        Employee hari = new Employee();
        hari.name = "Hari krishnan";
        hari.salary = 20000;
    }
}
Back to Blog

Related posts

Read more »

Java Variables

What is a Variable in Java? A variable is a container used to store data values. Types of Variables in Java Local Variables Example: java class Test { void dis...

Interface vs Abstract class

Interface or Abstract Class? They are very similar, and therefore it can be confusing to know when to use each one. I’m going to answer this question in this a...