Difference between final and static keywords in Java

In Java, the final and static keywords serve different purposes. Here's a concise comparison of their roles and behaviors.

final Keyword

  1. Purpose: Used to define constants, prevent method overriding, and prevent inheritance.
  2. Usage:
  3. Final Variables: Once assigned, cannot be changed. Example: final int MAX_SIZE = 100;
  4. Final Methods: Cannot be overridden by subclasses. Example: public final void display() { }
  5. Final Classes: Cannot be subclassed. Example: public final class UtilityClass { }

static Keyword

  1. Purpose: Used to define class-level variables and methods, shared across all instances.
  2. Usage:
  3. Static Variables: Shared among all instances of the class. Example: public static int count = 0;
  4. Static Methods: Belong to the class and can be called without creating an instance. Example: public static void displayCount() { }
  5. Static Blocks: Used for static initialization. Example: static { // initialization code }

Summary of Differences

  • final:
  • Variables: Immutable after initialization.
  • Methods: Cannot be overridden.
  • Classes: Cannot be subclassed.
  • static:
  • Variables: Shared among all instances.
  • Methods: Can be called without an instance.
  • Blocks: Initialize static members when the class is loaded.

Follow-up Questions

  1. Can a final variable be static?
  2. Yes, making a variable both final and static creates a constant that is shared among all instances of the class.
  3. Can you override a static method?
  4. No, static methods belong to the class, not instances, and therefore cannot be overridden.
  5. What happens if you access a static variable using an object instance?
  6. It works, but it’s misleading. It’s better to access static variables using the class name.