Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Sitemap

Member-only story

Class Variables vs Instance Variables in Java (With Examples)

Understand the key difference between class variables (static) and instance variables in Java. Learn when to use them with beginner-friendly examples.

3 min readApr 2, 2025

📌 Overview

In Java, variables declared inside a class can be:

  • Class Variables (also called static variables)
  • Instance Variables (also called non-static variables)

They look similar, but they behave very differently.

🧬 Instance Variables (Non-Static)

  • Declared inside a class, but outside any method
  • Belongs to each object (instance) of the class
  • Each object has its own copy

✅ Example:

public class Student {
String name; // instance variable

public Student(String name) {
this.name = name;
}
}
Student s1 = new Student("Amit");
Student s2 = new Student("Ravi");

System.out.println(s1.name); // Amit
System.out.println(s2.name); // Ravi

➡️ Changing s1.name will not affect s2.name.

🌐 Class Variables (Static)

  • Declared with the keyword static
  • Belongs to the class itself, not to objects

--

--

No responses yet