Sobes.tech
Junior — Middle

How are static variables defined and what is their purpose in programming?

sobes.tech AI

Answer from AI

Static variables in programming are variables that belong to the class rather than to any specific object of the class. They are defined using the static keyword (for example, in Java).

Purpose of static variables:

  • To store data common to all instances of the class.
  • To allow access to the variable without creating an object of the class.
  • Used for implementing counters, caching, constants, and other shared resources.

Example in Java:

public class Counter {
    public static int count = 0; // static variable

    public Counter() {
        count++; // increment counter when an object is created
    }
}

// Usage:
Counter c1 = new Counter();
Counter c2 = new Counter();
System.out.println(Counter.count); // Will output 2

In this example, count is shared among all objects of the Counter class and stores the number of instances created.