Command Palette

Search for a command to run...

Back to the lesson: Topic 4.6 — static Fields, Methods and Blocks
Core Java · Example 4 of 4

Static factory methods with names

Integer.valueOf caches -128..127 by default; 1000 may differ if the JVM is run with -XX:AutoBoxCacheMax.

static means "belongs to the class itself, not to any one object". A static field has exactly one copy shared by everyone, a static method runs without an object, and a static block runs once when the class is first initialised.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write a utility class Stats (private constructor) with static methods max(int[] a) and average(int[] a). Use them on {4, 8, 15, 16, 23, 42}.

02

Write a class User that gives each new user an id from a static counter and has a static method count(). Create three users and print their ids and the count.

03

Write a class Colors whose static block fills a static String[] NAMES = new String[3] with "red", "green", "blue" and prints Colors ready. In main, print a line, then Colors.NAMES[1], then Colors.NAMES[2].

Explain it without notes

01

What is the difference between a static field and an instance field? Give an example where each is the right choice.

02

Why can't a static method use this or instance fields directly?

03

When does the JVM initialise a class, and what runs during initialisation?

04

What are the advantages of a static factory method over a constructor?

05

Why is mutable static state considered risky?

Static factory methods with names
Sign in to run this example in your browser.

Expected output

Rs 12.00
Rs 12.50
zero is cached: true
valueOf(100) same object:  true
valueOf(1000) same object: false