Tutorial 3: Literals, Constants, and Naming

Unit 1 · Java setup and first programs

Objectives

Make intent visible

A literal is a value written directly in source code, such as 42, 3.14, or "Java". A constant is a named value that should not change during execution. Java conventionally writes constant names in uppercase with underscores.

final int PASS_MARK = 50;
final double TAX_RATE = 0.05;

int mark = 72;
boolean passed = mark >= PASS_MARK;
System.out.printf("Mark: %d, passed: %b%n", mark, passed);

The final modifier prevents reassignment after initialization. Use names such as weeklyMinutes, not vague names such as x. Classes use PascalCase; variables and methods use camelCase.

String concatenation converts values to text, while printf gives controlled formatting. Be aware that "Total: " + 2 + 3 produces "Total: 23"; parentheses make the intended calculation clear.

Practice

  1. Refactor a program containing x, y, and magic numbers into named values.
  2. Declare constants for a course's pass mark and maximum mark.
  3. Format a decimal with one and two decimal places using printf.

Self-check

  1. What does final prevent?
  2. Why are constants useful beyond style?
  3. What does "A" + 1 + 2 evaluate to?

Mastery task: Build a formatted course summary whose output is readable without seeing the source code. Replace every unexplained literal with a named constant.

Self-Check Quiz

1. Which operator compares two primitive values?

Answer(B) == compares values; = assigns a value.

2. What modifier prevents reassignment?

Answerfinal prevents a variable from being assigned again after initialization.

3. What is "Total: " + 2 + 3?

Answer"Total: 23", because concatenation proceeds left to right after the String is encountered.

Exercises

Exercise 1: Remove Magic Numbers

Rewrite a pass check that uses mark >= 50 so the meaning of 50 is explicit.

Sample answer
final int PASS_MARK = 50;
boolean passed = mark >= PASS_MARK;
The name makes the rule easy to find and change.

Exercise 2: Predict the Output

Predict and then run: System.out.println("A" + 1 + 2); and System.out.println("A" + (1 + 2));.

AnswerThe outputs are A12 and A3. Parentheses force arithmetic before concatenation.

Homework

  1. Refactor a short Java program so every variable and method has a descriptive camelCase name.
  2. Create constants for a course pass mark, maximum mark, and weekly study target.
  3. Print a formatted report using printf with one decimal place for a rate.
Sample homework answer
final int PASS_MARK = 50;
final int MAX_MARK = 100;
final int WEEKLY_TARGET = 300;
double rate = 225.0 / WEEKLY_TARGET;
System.out.printf("Progress: %.1f%%%n", rate * 100);
A strong answer explains each constant and avoids names such as x or n when they do not communicate intent.