Explain Codes LogoExplain Codes Logo

Difference between Static and final?

java
singleton
best-practices
memory-management
Nikita BarsukovbyNikita Barsukov·Oct 25, 2024
TLDR

The static keyword represents class-level properties, which belong to the class, not its instances. Accessible via the class name, any instance shares these properties. The final keyword, however, indicates immutability. A final variable, once set, cannot be changed, and a final class does not allow subclassing. Let's visualize:

static example:

class RoboticArm { static int numOfArms = 0; // A general pollutant, quite armful! } int totalArms = RoboticArm.numOfArms; // Accessed Transformers style... Bumblebee reporting!

final example:

class Dollars { final int exchangeRate = 74; // As constant as Uncle Scrooge's vault. // exchangeRate = 75; // Error: Scrooge doesn't like change! }

Understand these keywords to master the flow and access mechanisms in Java programming. It's no less magical than the Elder Wand and Philosopher's Stone!

Deep dip into Static and Final: The real deal

Static: Once loaded, forever shared

The mighty static keyword enables shared state between objects and global access:

  • Static Fields: Property shared across instances; party till heap overflows!
    public class Planet { public static int earthGravity = 9; // Gravity, very down to Earth! } // Pulled in as Planet.earthGravity; Newton's favourite apple!
  • Static Initialization Blocks: Complex static initialization because simple is too mainstream.
    public class ComplexInit { public static List<String> complexList; static { complexList = new ArrayList<>(); // Some complex magic stuff goes here } }
  • Static methods: Utility functions sans object states; the hermit methods!
    public class MathWonders { public static int add(int penny, int nickel) { return penny + nickel; // Quite the penny-pincher method! } } // Invoke as MathWonders.add(1, 5); because MathWizards are rare!

Watch out for pesky race conditions in multithreaded environs and hidden bugs, Static's cunning accomplices!

Final: The Unchanging Sentinel

A final keyword is like carving in stone:

  • Final fields: Immutable values; unchanging since Big Bang!
    public class Constants { public final double PI = 3.1415; // PI is a sweet constant! } // Constants.PI; as constant as your diet for Pizza!
  • Final methods: Locked down, a method's integrity preserved across generations…inheritance, you see!
    public class Migration { public final void migrate() { // Off to greener pastures. } } // migrate: because running away from problems is a race you'll never win!

Final can turn tides by enforcing immutability. The compiler throws performance treats for its pet final.

Quickfire Examples: Duel of Static & Final

When to use static and final, now in practical examples:

  • Singleton pattern: combines static single instance with final to ensure it's the only one (There Can Be Only One! – Highlander)
  • Constants: They're static final fields. Global yet immovable. Ex: Math.PI
  • Utility classes like Math; No instantiation, just static methods playing by themselves.
  • Immutable objects final fields ensure once set, no regrets.

Beware, stubborn use of static leads to Memory Heartbreaks, overusing final gives birth to AgainstChangeException.