Static variables hold a value shared by all objects of a class. They help save memory and keep common data in one place.
0
0
Static variables in Java
Introduction
When you want to count how many objects of a class have been created.
When you need a common setting or value shared by all objects, like a company name.
When you want to share a constant value across all instances.
When you want to keep track of a shared resource or status.
Syntax
Java
class ClassName { static DataType variableName; }
Static variables belong to the class, not to any single object.
You can access static variables using the class name, like ClassName.variableName.
Examples
line_end_arrow_notchThis declares a static variable numberOfCars shared by all Car objects.
Java
class Car { static int numberOfCars; }
line_end_arrow_notchAccessing and setting the static variable using the class name.
Java
Car.numberOfCars = 5;line_end_arrow_notchA static variable holding a company name shared by all Example objects.
Java
class Example { static String company = "TechCorp"; }
Sample Program
This program creates three Counter objects. Each time a Counter is made, the static count variable increases by 1. The showCount method prints the total count shared by all objects.
Java
class Counter { static int count = 0; Counter() { count++; } static void showCount() { System.out.println("Count: " + count); } } public class Main { public static void main(String[] args) { Counter c1 = new Counter(); Counter c2 = new Counter(); Counter c3 = new Counter(); Counter.showCount(); } }
OutputSuccess
Important Notes
line_end_arrow_notch
Static variables keep their value as long as the program runs.
line_end_arrow_notch
They are initialized only once when the class is loaded.
line_end_arrow_notch
Use static variables carefully to avoid unwanted shared changes.
Summary
Static variables belong to the class, not individual objects.
They share the same value across all objects of that class.
Useful for counting objects or storing common data.
