Command Palette

Search for a command to run...

Back to the lesson: Topic 1.14 — Constants, final and Literals
Core Java · Example 5 of 5

Compile-time constants are folded and pooled

This shows what the compiler does; it is not a reason to compare Strings with ==. Use equals (Topic 1.10).

A literal is a value written directly in code, such as 42, 0xFF, 3.5f, 'A', true, "hi" or null, and its exact spelling decides its type. Marking a variable final means it can be assigned only once; a static final field with a fixed value is a constant, named in UPPER_SNAKE_CASE.

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

Define constants SECONDS_PER_MINUTE, MINUTES_PER_HOUR and HOURS_PER_DAY, compute SECONDS_PER_WEEK from them as another constant, and print it.

02

Print the number 100 written as a decimal, hex (0x64), octal (0144) and binary (0b110_0100) literal, and check all four are equal with ==.

03

Using a final blank variable grade, assign 'A' if marks >= 90, 'B' if marks >= 75, otherwise 'C', for marks = 82, and print it.

Explain it without notes

01

What does final mean for a local variable, a static field and a reference to an object?

02

Why do teams replace magic numbers with named constants? Give an example.

03

What are the types of 42, 42L, 4.2, 4.2f, '4' and "4", and why does 010 print 8?

04

What is a compile-time constant, and what surprising effect can it have when another class uses it?

Compile-time constants are folded and pooled
Sign in to run this example in your browser.

Expected output

seconds per day: 86400
constant + literal pooled? true
variable + literal pooled? false