🔁 What is a Static Variable?
A static variable belongs to the class, not to any specific object of that class. That means all objects share the same static variable. It’s like having one copy of a variable that everyone uses.
Static variables Can be accessed from any part of the program.
When a variable is declared as static, then a single copy of the variable is created and shared among all objects at a class level.
✅We can create static variables at class level only.Static variables can be accessed by static and non static methods.
They are class specified.
🏫 Non-Static Variable
A non-static variable (also called an instance variable) belongs to an object. Every time you create a new object, it gets its own copy of that variable.
✅Non static variables can be accessed using instance (object) of a class.In non Static variable Memory is allocated each time an instance of the class is created.They are object specific.
class Student {
static String schoolName = "Green Valley High"; // shared by all students (static)
String studentName; // each student has their own name (non-static)
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.studentName = "Aarav";
s2.studentName = "Diya";
System.out.println("Student 1:");
System.out.println("Name: " + s1.studentName); // non-static
System.out.println("School: " + Student.schoolName); // static (accessed using class name)
System.out.println("\nStudent 2:");
System.out.println("Name: " + s2.studentName); // non-static
System.out.println("School: " + Student.schoolName); // static (same for all)
}
}