Skip to content
Ameen Abozaid
PublishedBEG-009-L04

Literals, constants, and naming

  • Lesson 4 of 7
  • 11 min read
  • Beginner
On This Lesson 11 topics

Lesson Overview

A box is only useful if you can put the right value into it and find it again by name. This lesson covers both ends of that sentence. The value side is literals: the way Java lets you write a value directly in code, such as 42, 3.14, 'A', "Hi", or true. The name side is naming: the rules the compiler enforces and the conventions every Java programmer follows.

We also add a new kind of box. Some values should never change while the program runs: a tax rate, a maximum number of login attempts, the value of pi. Marking a variable final turns it into a constant, a box that is sealed after the first value goes in.

Why this matters: programs are read far more often than they are written. A line such as total = x1 * 0.15; forces the reader to guess; total = subtotal * TAX_RATE; explains itself, and the rate can be changed in one place. Teams also rely on shared naming conventions so that any Java file looks familiar.

This lesson builds on Lessons 1 to 3 (variables, primitive types, and String). It only introduces final for local variables; constants shared by a whole class come when classes are taught.

Learning Objectives

By the end of this lesson you will be able to:

  • Write literals of each type, including long literals with L, float literals with f, and char literals in single quotes.
  • Use underscores to make large numeric literals readable.
  • Declare a constant with final and explain what the compiler does if you try to change it.
  • Apply Java naming conventions: camelCase for variables, UPPER_SNAKE_CASE for constants, PascalCase for classes.
  • Tell legal names (which the compiler requires) from conventional names (which people expect).
  • Rename an unclear name so that it explains itself.

Written Explanation

Literals

A literal is a value written directly in the source code. The form of the literal tells the compiler its type.

LiteralTypeNotes
42, -7, 0intThe default whole-number literal
5000000000LlongNeeds L; uppercase is clearer than lowercase l, which looks like 1
3.14, 0.15doubleThe default decimal literal
0.5ffloatNeeds f
'A', '7'charExactly one character, single quotes
"Hi", ""StringText, double quotes
true, falsebooleanLowercase
nullany reference typeNot a primitive literal (Lesson 3)

To make long numbers easier to read, Java lets you put underscores between digits: 1_000_000 is the same as 1000000. The underscores are only for people; the compiler ignores them. Use them for numbers with four or more digits.

Two rules cause most beginner errors:

  • A whole-number literal is an int unless it ends in L. Writing 5000000000 fails because the literal itself is too big for an int.
  • A decimal literal is a double unless it ends in f. So float f = 0.5; fails, because it tries to put a double into a float box. Write 0.5f.

Constants with final

By default a variable can be reassigned. Adding the keyword final in front of the type seals the box after the first value is stored:

java
final double TAX_RATE = 0.15;

After this line, TAX_RATE = 0.2; is a compile error. A final variable is called a constant when it holds a fixed value like this.

Why bother?

  • No magic numbers. The name TAX_RATE tells the reader what 0.15 means. A bare 0.15 buried in an expression is a "magic number".
  • One place to change. If the rate changes, you edit one line, not ten.
  • Safety. The compiler stops anyone, including you on a tired day, from changing a value that must not change.

A final variable may also be declared first and given its value later, but only once. In this course, give the value on the same line.

Names: what is required, and what is expected

There are two different layers.

Rules (the compiler enforces them). A name may contain letters, digits, _, and $. It cannot start with a digit, cannot contain spaces, cannot be a reserved word such as class or int, and is case sensitive. So 2nd and my item and class are illegal.

Conventions (people expect them). They are not enforced, but code that ignores them is hard for others to read. The Java tutorials recommend starting names with a letter and avoiding $. The common conventions are:

Kind of nameStyleExample
Variables (and methods, later)camelCase: lower-case first word, then each new word capitaliseditemCount, totalPrice
ConstantsUPPER_SNAKE_CASE: capitals, words separated by underscoresTAX_RATE, MAX_USERS
ClassesPascalCase: every word capitalisedCart, OrderService

Notice that underscores belong to constants. A variable called Total_Price breaks the convention twice: it starts with a capital and it uses an underscore.

Good names explain themselves

  • Use words: itemCount beats ic or x1.
  • Say what is inside, including the unit if it helps: priceCents, timeoutSeconds.
  • For a boolean, a question-like name reads well: isStudent, hasPaid.
  • Avoid names that only repeat the type (stringName) or that differ only in digits (value1, value2).
  • Keep names reasonably short, but never at the cost of clarity.

A quick test: cover the declaration and read only the line that uses the variable. If you can still tell what it is, the name is good.

Examples

Example 1: one literal of each kind (simple)

java
public class Literals {
    public static void main(String[] args) {
        int million = 1_000_000;
        long big = 5000000000L;
        float ratio = 0.5f;
        double rate = 0.15;
        char letter = 'A';
        String word = "A";
        System.out.println(million + " " + big + " " + ratio + " " + rate + " " + letter + " " + word);
    }
}

Output (JDK 21):

text
1000000 5000000000 0.5 0.15 A A

The output cannot show the underscores (they never existed for the program) or the quote style. But letter and word are different types: one char, one String.

Example 2: a constant and a self-explaining name (practical)

java
public class Tax {
    public static void main(String[] args) {
        final double TAX_RATE = 0.15;
        double subtotal = 200.0;
        System.out.println("Tax: " + subtotal * TAX_RATE);

        int itemCount = 5;
        System.out.println(itemCount);
    }
}

Output:

text
Tax: 30.0
5

If someone later writes TAX_RATE = 0.2;, the compiler stops them:

text
error: cannot assign a value to final variable TAX_RATE

(Here the example uses double to keep the arithmetic simple. For real money, Lesson 2 told you to prefer whole cents. A rate such as 0.15 is a ratio, not an amount, so a double is a reasonable choice for it.)

Example 3: renaming a messy program (realistic)

Before:

java
int x1 = 5;
double d = 19.99;
double Total_Price = x1 * d * 1.15;

The reader must guess what x1, d, and 1.15 mean, and Total_Price breaks the conventions. After:

java
final double SALES_MULTIPLIER = 1.15;   // price plus 15 percent tax
int itemCount = 5;
double unitPrice = 19.99;
double totalPrice = itemCount * unitPrice * SALES_MULTIPLIER;

The calculation is the same. The program now tells its own story, and the constant gives a name to the "magic" 1.15. (A real shop would keep money in whole cents; this example keeps double only to focus on naming.)

Backend Insight

Backend codebases are shared by many people for years, so naming is a working skill, not decoration.

  • Constants hold configuration-like values such as timeouts, retry limits, page sizes, and rates. When a requirement changes ("increase retries from 3 to 5"), you change one named constant. Later you will see how such values move out of code into configuration files.
  • Names appear in logs, errors, and APIs. A variable named userId becomes a field name in a JSON response or a column in a database. Consistent, meaningful names make debugging a production issue far faster.
  • Conventions are tool-friendly. Code reviews, IDEs, and style checkers all assume camelCase and PascalCase. A project that follows them is easier to read for every new team member.

Another practical habit: put the unit in the name when it is not obvious (delayMillis, fileSizeBytes). A large share of real-world bugs are one side assuming seconds and the other assuming milliseconds.

Common Mistakes

Mistake 1: Forgetting L or f

long big = 5000000000; gives integer number too large, and float f = 0.5; gives incompatible types: possible lossy conversion from double to float. Add L or f to the literal.

Mistake 2: Single quotes for text, double quotes for a character

'Ana' is invalid (a char holds one character), and char c = "A"; is a type error. One character: 'A'. Text: "Ana".

Mistake 3: Using a reserved word or a leading digit as a name

int class = 3; and int 2nd = 4; do not compile. The compiler's messages here are confusing (JDK 21 printed not a statement, ';' expected, and <identifier> expected for int class = 3;), because it tries to read class as the start of something else. If a declaration produces odd messages at the name, suspect the name.

Mistake 4: Changing a final variable

MAX_USERS = 200; after final int MAX_USERS = 100; fails with cannot assign a value to final variable MAX_USERS. If a value really must change, it is not a constant: drop final and rename it in camelCase.

Mistake 5: Writing names that break convention

Compilers accept Total_Price, TOTAL, and my_variable, but readers expect totalPrice. Use UPPER_SNAKE_CASE only for constants.

Exercises

Try each exercise yourself before opening the solutions.

Level A: Foundation

A1. Give the type of each literal: 100, 100L, 100.0, 100.0f, '1', "1".

Show solution A1

A1. int, long, double, float, char, String.

A2. Which of these are legal Java names: userName, 3rdPlace, final, max_speed, my score?

Show solution A2

A2. userName is legal. 3rdPlace is illegal (starts with a digit). final is illegal (reserved word). max_speed is legal but not conventional (use maxSpeed). my score is illegal (contains a space).

A3. Rewrite in Java style: a variable User_Name, a constant for the number of days in a week, and a class for a shopping cart.

Show solution A3

A3. userName; final int DAYS_PER_WEEK = 7;; ShoppingCart.

Level B: Application

B1. Fix each declaration so it compiles: long phone = 9876543210;, float temp = 36.6;, char grade = "A";.

Show solution B1

B1. long phone = 9876543210L; (also better stored as a String, since you never calculate with it). float temp = 36.6f; (or use double temp = 36.6;). char grade = 'A';.

B2. The code below has a magic number and a poor name. Rewrite it with a constant and clear names:

java
int n = 30;
int result = n * 24;

(The variable n is a number of days, and 24 is hours per day.)

Show solution B2

B2.

java
final int HOURS_PER_DAY = 24;
int days = 30;
int totalHours = days * HOURS_PER_DAY;

B3. Predict whether this compiles. If not, say what the message will be about.

java
final int limit = 10;
limit = limit + 1;
Show solution B3

B3. It does not compile: limit is final, so it cannot be assigned again. The message is of the form cannot assign a value to final variable limit.

Level C: Challenge

C1. Write a small program that declares a constant SECONDS_PER_MINUTE and a variable minutes set to 90, and prints how many seconds that is, in a sentence. Use 1_000-style underscores somewhere sensible if a large number appears.

Show solution C1

C1.

java
public class Seconds {
    public static void main(String[] args) {
        final int SECONDS_PER_MINUTE = 60;
        int minutes = 90;
        int seconds = minutes * SECONDS_PER_MINUTE;
        System.out.println(minutes + " minutes is " + seconds + " seconds");
    }
}

It prints 90 minutes is 5400 seconds. Underscores are not needed for 5400; they help with numbers such as 1_000_000.

C2. Your team's variables are named a, b, and c. Someone says "short names are faster to type, so they are better". Write three sentences that answer them, including one backend-related reason.

Show solution C2

C2. Typing time is a tiny part of programming; reading and fixing code takes much more, and names like a and b hide what the data means. In a backend service, a name often becomes a log message, a field in an API, or a column in a database, so a clear name saves time when diagnosing a production problem. Modern editors also complete names, so a longer meaningful name costs almost nothing to type.

Mini Challenge

You are writing a tiny program for a parking lot. Declare, with literals and good names: a constant for the hourly rate in cents (use 250), the number of hours parked, a boolean for whether the driver has a membership, the first letter of the lot's zone (a char), and the lot's full name (a String). Compute the fee in cents without a membership discount, and print one readable line.

Check your work: the constant is final and in UPPER_SNAKE_CASE; the other names are camelCase; the char uses single quotes and the String uses double quotes; there are no magic numbers in the calculation; the code compiles and prints the right fee.

Summary & Next Lesson

Key takeaways

  • A literal is a value written in code; its form decides its type: 42 is int, 42L is long, 4.2 is double, 4.2f is float, 'A' is char, "A" is String.
  • Underscores in numeric literals (1_000_000) help people read; the compiler ignores them.
  • final makes a constant: it can be given a value once and never changed.
  • Conventions: camelCase for variables, UPPER_SNAKE_CASE for constants, PascalCase for classes.
  • Good names say what a variable holds and, where useful, its unit.

Next lesson

You can now choose, write, and name values. The next lesson, "Type conversion and casting", looks at what happens when values of different types meet: an int meets a double, a big number is squeezed into a small box, and an int runs past its limit.

Self-check

  1. What does a long literal end with, and a float literal?
  2. What does final do to a variable?
  3. Which naming style is used for a constant?
  4. Is my_total a legal name? Is it conventional?
  5. Why is price * 1.15 worse than price * SALES_MULTIPLIER?
Show answers
  1. L for long, f for float.
  2. It allows a value to be stored once and rejects any later assignment.
  3. UPPER_SNAKE_CASE, such as MAX_USERS.
  4. It is legal, but not conventional; the convention is myTotal.
  5. The bare 1.15 is a magic number: it does not say what it means and must be changed in every place it appears.

References

  • Oracle, The Java Tutorials: Variables. It states the rules for legal names (letters, digits, _, $, no whitespace, not a keyword, case sensitive), recommends starting with a letter and avoiding $, and describes camelCase for variables and capital letters with underscores for constants.
  • Oracle, The Java Tutorials: Primitive Data Types. It describes the L, f, and d literal suffixes, recommends uppercase L, and says double is the default for decimals.
  • Compiler messages above were produced with JDK 21; other versions may word them differently. I did not fetch a source for underscores in numeric literals or for PascalCase class names; both are stated from general knowledge of Java, and the underscore case was exercised in the code run here. The reserved-word examples were also compiled, as noted in Mistake 3.

Practice

Apply this lesson with the module's lab, exercises and quiz.

Lab and exercises Quiz

Marking a lesson complete is optional and you can undo it any time. Your progress stays in this browser.

Continue to next lesson

Type to search levels, phases, modules and lessons.