KnowledgeBoat Logo
LoginJOIN NOW

Computer Applications

Why do you need to use static variables in Java?

Encapsulation & Inheritance in Java

3 Likes

Answer

Static variables in Java are used when we want to create a variable that is common to all objects of a class, rather than having a separate instance of the variable for each object. This is useful in situations where we need to keep track of information that applies to a class as a whole, rather than to individual objects.

Some common use cases for static variables include:

  1. Counter to keep track of the number of instances of a class that have been created.
  2. To store a constant value that is common to all objects of a class.
  3. To store configuration information that is common to all objects of a class.

Answered By

3 Likes


Related Questions