Skip to content

Module 5 · Classes and Objects — topic 3 of 4

static Fields, Methods and Blocks

Members that belong to the class rather than to objects: shared counters, constants, utility methods, static initialisation blocks, and the rules for accessing them.

Beginner 12 min read·Lesson 18 of 39 in Java Programming

Learning objectives

  • Decide when a member should be static
  • Use static fields for shared state and constants
  • Explain why static methods cannot access instance members directly

Definition

A static member belongs to the class itself rather than to any particular object. A static field has one copy shared by all instances; a static method runs without an object and cannot use this or instance fields directly.

Introduction

Some data and behaviour belong to the idea of a class, not to any one object: the number of accounts opened so far, the value of π, a helper that converts units. Java marks these with the keyword static. You have used static members since your first program — main, Math.sqrt and System.out are all static.

Why it matters

Constants such as Integer.MAX_VALUE and utility methods such as Math.max are static.

Misusing static — for example, storing per-object data in a static field — causes bugs where every object mysteriously shares one value.

Detailed explanation

Static fields exist once per class, created when the class is loaded. Every object sees the same value: incrementing a static counter in the constructor counts all objects ever created.

Constants are static final fields with UPPER_CASE names: static final double GST_RATE = 0.18;. They are computed once and shared.

Static methods are called on the class: MathUtil.square(5). They have no this, so they cannot use instance fields or call instance methods without an object reference. Instance methods, on the other hand, can freely use static members.

Utility classes (like Math, Arrays, Collections) contain only static methods and usually have a private constructor so nobody can create pointless instances.

Static initialisation blocks — static { ... } — run once when the class is loaded, useful for filling a lookup table.

Static nested classes are classes declared inside another class with static; they don't need an instance of the outer class. You'll see them in larger programs and in the Collections chapter.

Use static sparingly: global mutable state makes programs harder to test and unsafe in multithreaded code.

Syntax

Java
class Account {
static final double INTEREST = 0.04; // constant
private static int opened = 0; // shared counter
private final int number;
Account() { number = ++opened; }
static int openedSoFar() { return opened; } // no 'this' here
}
Account.openedSoFar(); // call on the class
  • Refer to static members through the class name, not through an object.
  • A static method can't use instance fields without an object.
  • static final primitives and Strings are compile-time constants when initialised with constant expressions.

Code examples

A shared counter and a constant

Java
public class Main {
public static void main(String[] args) {
Ticket t1 = new Ticket("Asha");
Ticket t2 = new Ticket("Ravi");
Ticket t3 = new Ticket("Meera");
System.out.println(t1 + "\n" + t2 + "\n" + t3);
System.out.println("Issued: " + Ticket.issued() + ", price each: " + Ticket.PRICE);
}
}
class Ticket {
static final int PRICE = 150;
private static int count = 0;
private final int number;
private final String holder;
Ticket(String holder) {
this.holder = holder;
this.number = ++count;
}
static int issued() { return count; }
@Override public String toString() { return "Ticket #" + number + " for " + holder; }
}
Output
Ticket #1 for Asha
Ticket #2 for Ravi
Ticket #3 for Meera
Issued: 3, price each: 150

A utility class

Java
public class Main {
public static void main(String[] args) {
System.out.println(Convert.celsiusToFahrenheit(37));
System.out.println(Convert.kmToMiles(42.195));
System.out.println(Math.max(3, 9) + " " + Math.abs(-4) + " " + Math.pow(2, 8));
}
}
final class Convert {
private Convert() { } // no instances
static double celsiusToFahrenheit(double c) { return c * 9 / 5 + 32; }
static double kmToMiles(double km) { return Math.round(km * 0.621371 * 100) / 100.0; }
}
Output
98.6
26.22
9 4 256.0

More examples

Static blocks, lookup tables and instance vs static access

Java
public class Main {
public static void main(String[] args) {
System.out.println(Roman.of(1994) + " " + Roman.of(2026) + " " + Roman.of(3999));
Product.setTaxRate(0.18);
Product pen = new Product("Pen", 20);
Product bag = new Product("Bag", 1200);
System.out.println(pen.priceWithTax() + " " + bag.priceWithTax());
Product.setTaxRate(0.05); // affects every product
System.out.println(pen.priceWithTax() + " " + bag.priceWithTax());
}
}
class Roman {
private static final int[] VALUES = new int[13];
private static final String[] SYMBOLS = new String[13];
static { // runs once, when the class is first used
String table = "1000 M 900 CM 500 D 400 CD 100 C 90 XC 50 L 40 XL 10 X 9 IX 5 V 4 IV 1 I";
String[] parts = table.split(" ");
for (int i = 0; i < 13; i++) {
VALUES[i] = Integer.parseInt(parts[2 * i]);
SYMBOLS[i] = parts[2 * i + 1];
}
}
static String of(int n) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < VALUES.length; i++)
while (n >= VALUES[i]) { sb.append(SYMBOLS[i]); n -= VALUES[i]; }
return sb.toString();
}
}
class Product {
private static double taxRate = 0;
private final String name;
private final double price;
Product(String name, double price) { this.name = name; this.price = price; }
static void setTaxRate(double rate) { taxRate = rate; } // can't use name or price here
double priceWithTax() { return Math.round(price * (1 + taxRate) * 100) / 100.0; } // instance method uses static field
}
Output
MCMXCIV MMXXVI MMMCMXCIX
23.6 1416.0
21.0 1260.0

Step-by-step explanation

  • The static { ... } block fills the two lookup arrays once, the first time Roman is used.
  • Roman.of is a static method: it only needs its parameter and the static tables, never an object.
  • taxRate is static, so Product.setTaxRate(0.05) changes the rate for every product at once.
  • setTaxRate is static and therefore has no this; it could not read name or price.
  • priceWithTax is an instance method: it combines the object's own price with the shared taxRate.

Expected output

Running “Static blocks, lookup tables and instance vs static access” prints exactly:

TextOutput
MCMXCIV MMXXVI MMMCMXCIX
23.6 1416.0
21.0 1260.0

Practical applications

  • Constants such as Integer.MAX_VALUE and configuration defaults
  • Utility classes like Math, Arrays, Collections and Objects
  • Factory methods such as List.of and Integer.valueOf
  • Counting created objects or generating unique ids

Best practices

  • Make constants static final with UPPER_SNAKE_CASE names.
  • Prefer instance state over mutable static state.
  • Give utility classes a private constructor and make them final.

Common mistakes

Accessing instance fields from static code

Avoid

class Counter {
int count;
static void reset() { count = 0; } // error
}

Prefer

class Counter {
int count;
void reset() { count = 0; }
}

A static method has no current object, so there is no count to reset. Make the method an instance method (or pass an object).

Storing per-object data in a static field

Avoid

class Student { static String name; }

Prefer

class Student { String name; }

A static field is shared, so setting one student's name would change every student's name.

Important notes

  • You can call a static method through an object reference (obj.staticMethod()), but it is misleading and compilers warn about it.
  • Static fields are shared across all threads; protect mutable static state when using threads (module 10).

Key takeaways

  • static members belong to the class, with one shared copy.
  • Static methods have no this and can't use instance members directly.
  • Use static for constants, counters, factories and utility methods.

Try it yourself

  1. 1
    Give a Student class an automatically increasing roll number using a static counter.
  2. 2
    Write a utility class Stats with static methods mean, median and mode for int arrays.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

5 questions test this exact topic. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhy can't a static method use an instance field directly?
  • ModerateWhat is printed?
Practise this topic