Static and non-static help decide if something belongs to the whole class or just one object. This helps organize code and save memory.
Static vs non-static behavior in Java
class ClassName { static int sharedValue; // static variable int individualValue; // non-static variable static void staticMethod() { // code here } void nonStaticMethod() { // code here } }
Static means the item belongs to the class itself, not any object.
Non-static means the item belongs to each object separately.
class Example { static int count = 0; // shared by all objects int id; // unique for each object Example(int id) { this.id = id; count++; } static void showCount() { System.out.println("Total objects: " + count); } void showId() { System.out.println("Object id: " + id); } }
public class Test { public static void main(String[] args) { Example e1 = new Example(1); Example e2 = new Example(2); Example.showCount(); // call static method e1.showId(); // call non-static method e2.showId(); } }
This program creates two Car objects. It uses a static variable to count all cars made and non-static variables to store each car's model.
class Car { static int totalCars = 0; // shared by all cars String model; // unique for each car Car(String model) { this.model = model; totalCars++; } static void showTotalCars() { System.out.println("Total cars made: " + totalCars); } void showModel() { System.out.println("Car model: " + model); } } public class Main { public static void main(String[] args) { Car c1 = new Car("Toyota"); Car c2 = new Car("Honda"); Car.showTotalCars(); c1.showModel(); c2.showModel(); } }
Static methods cannot use non-static variables directly because non-static variables belong to objects, and static methods belong to the class.
You can call static methods and access static variables without creating an object.
Non-static methods can access both static and non-static variables.
Static means shared by the whole class, non-static means unique to each object.
Use static for common data or behavior, non-static for individual object data or behavior.
Static methods can be called without objects; non-static methods need objects.
