Command Palette

Search for a command to run...

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

Integer literals in every base

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?

Integer literals in every base
Sign in to run this example in your browser.

Expected output

255 four ways: 255 255 255 255
million: 1000000, people: 1428627663
0xFFFF_FFFF = -1
010 = 8
42 in binary: 101010
255 in hex:   ff