allthingsare๐Ÿ…ฟ๏ธ.com Books โฌ…๏ธ Back allthingsare

โ€œWhat lies behind us and what lies before us are tiny matters compared to what lies within us.โ€
[Ralph Waldo Emerson (1803โ€“1882) โ€“ American essayist and philosopher]


Static Methods and Variables


11.1.1 What Does Static Mean?

In Java, the static keyword means โ€œthis member belongs to the class itself, not to any specific object.โ€
When you mark a field or method as static:

  • You do not need to create an instance to use it.

  • The field or method exists once per class, shared by all objects.

Key point:
Non-static members belong to each object, but static members belong to the class.


Where does this matter?

  • Static variables are used for data that must be shared across all instances โ€” like a counter that tracks how many objects exist.

  • Static methods are used for tasks that donโ€™t depend on any particular objectโ€™s state โ€” like utility functions (Math.sqrt()).


11.1.2 Static Fields: One Value Shared by All

A static field is a variable that all instances of a class share.

Example: counting how many objects have been created.

java
public class Counter { static int count = 0; // static field public Counter() { count++; // shared by all instances } public static void main(String[] args) { new Counter(); new Counter(); new Counter(); System.out.println("Number of Counter objects: " + Counter.count); } }

Key point:

  • count is declared static.

  • Every time you create a Counter object, it increases count.

  • The field is shared by all instances โ€” not duplicated.

Without static, each object would have its own separate count, which wouldnโ€™t work here.


11.1.3 Static Methods: No Object Needed

A static method can be called without creating an object.
You can think of it as a class-level tool.

Classic example: main() itself is static:

java
public static void main(String[] args) { ... }

Static methods are useful for:

  • Utility tasks (Math.max(), Math.abs()).

  • Factory methods that create instances.

  • Helper functions that donโ€™t need object data.

Example:

java
public class MathHelper { public static int square(int x) { return x * x; } public static void main(String[] args) { int result = MathHelper.square(5); System.out.println("Square: " + result); } }

Key points:

  • You call it like MathHelper.square(5), no object needed.

  • Static methods cannot access non-static fields directly โ€” because they donโ€™t belong to any specific object.