Java Intermediate

0% completed

Previous
Next
Static Variables

What are Static Variables?

Static variables in Java are class-level variables that are shared among all instances of a class. Unlike instance variables, which are unique to each object, static variables maintain a single copy that is common to all objects. They are useful for defining properties or constants that should be consistent across all instances or for maintaining shared data.

  • Characteristics:
    • Shared Across Instances: All objects of the class share the same static variable. Changes made to the static variable by one object are reflected across all other objects.
    • Class-Level Access: Static variables can be accessed directly using the class name without needing to create an object.
    • Memory Efficiency: Since only one copy exists, static variables conserve memory when multiple objects need to share the same data.
    • Use Cases: Ideal for constants, configuration settings, counters, or any property that should remain consistent across all instances.

Syntax of Static Variables

class ClassName { static dataType variableName; }

Explanation:

  • static:
    The keyword that declares the variable as a static variable.

  • dataType:
    The type of data the variable holds (e.g., int, String, double).

  • variableName:
    The name of the static variable, following camelCase naming conventions.

Image

Problems Without Static Variables

Consider a scenario where we want to keep track of the number of objects created from a class. Without static variables, each object would have its own counter, making it impossible to maintain a global count.

Example Without Static Variable: Counting Objects

Java
Java

. . . .

Problem:
Each Counter object maintains its own count, preventing us from tracking the total number of objects created.

How Static Variables Solve the Problem

By declaring the count variable as static, all instances share the same counter, allowing us to accurately track the total number of objects created.

Example with Static Variable: Counting Objects

Java
Java

. . . .

Explanation:

  • static int count = 0;:
    Declares a static variable count that is shared across all Counter instances.

  • count++;:
    Increments the shared count each time a new Counter object is created.

  • Counter.count:
    Accessed directly using the class name, reflecting the total number of objects created.

Static variables are essential components in Java that belong to the class rather than any individual instance. They provide a way to maintain shared data across all objects of a class, making them ideal for constants, configuration settings, and counters that need to be consistent throughout the application's lifecycle.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next