Skip to content
C

static Keyword

static marks a field or method as belonging to the class itself, rather than to any one specific object. This means a static member is shared across all objects of that class.


1. What is the static Keyword?

static marks a field or method as belonging to the class itself, rather than to any one specific object. This means a static member is shared across all objects of that class.

2. Why is it used?

Some data or behaviour naturally belongs to the whole class rather than to individual objects — like a counter that tracks how many objects have been created in total. static is used for exactly this kind of shared data.

3. Real-Life Example

Think of a school's name, which is the same for every student in that school, versus each student's own individual roll number, which is different for each one. The school name is like a static field — shared by all.

4. Syntax

java
static dataType fieldName; static returnType methodName() { }

5. Example Program

java
class Counter { static int count = 0; Counter() { count++; } } public class StaticDemo { public static void main(String[] args) { new Counter(); new Counter(); new Counter(); System.out.println("Total objects created: " + Counter.count); } }

Output:

Total objects created: 3

6. Key Points to Remember

  • Static members belong to the class and are shared by all objects, not duplicated for each one.
  • Static methods can be called directly using the class name, without creating an object.
  • A static method cannot directly access non-static (instance) fields or methods, since those belong to specific objects.