Class Level Variables (Static Variables) in Java

Key Characteristics:

  • Shared Among Instances: All instances of the class share the same static variable. If one instance modifies the static variable, the change is visible to all other instances.
  • Declared with static Keyword: Static variables are declared using the static keyword.
  • Class-Level Scope: They can be accessed directly using the class name without creating an instance of the class.
  • Lifecycle: Static variables are initialized when the class is loaded and destroyed when the class is unloaded.
  • Scope: Class-level
  • Storage: Static variables are stored in the method area of memory.
  • Initialization: Static variables and static blocks are recognized and initialized at the time of loading the respective class byte code into memory (main memory).
  • Accessibility: Static variables can be accessed using the class name or any object reference.
  • Single Copy: A single copy of the static variable value is shared among all the objects of the respective class.
  • Use Case: Commonly used for constants or shared data among all instances.
  • Existence: Exists as long as the class is loaded in memory.
  • Restrictions: Static variables cannot be declared as local variables; doing so will result in a compiler error.

Static Methods in Java

Key Characteristics:

  • Belong to the Class: Static methods, like static variables, belong to the class itself and not to any particular instance of the class.
  • Access: Can be called using the class name without creating an instance of the class.
  • Utility Functions: Typically used to operate on static variables or provide utility functions.
  • No this Keyword: In static methods, the this keyword cannot be used.
  • Initialization: Static methods and static blocks are recognized and initialized at the time of loading the respective class byte code into memory (main memory).
Code Example
Output
Brand: Toyota
Model: Camry
Year: 2020

Brand: Honda
Model: Accord
Year: 2021

Total number of cars: 2