القيم الحرفية والثوابت والتسمية
في هذا الدرس 11 موضوعات
هذا الدرس متاح حاليًا باللغة الإنجليزية فقط، ولم تُنشر نسخته العربية بعد.
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
longliterals withL,floatliterals withf, andcharliterals in single quotes. - Use underscores to make large numeric literals readable.
- Declare a constant with
finaland 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.
| Literal | Type | Notes |
|---|---|---|
42, -7, 0 | int | The default whole-number literal |
5000000000L | long | Needs L; uppercase is clearer than lowercase l, which looks like 1 |
3.14, 0.15 | double | The default decimal literal |
0.5f | float | Needs f |
'A', '7' | char | Exactly one character, single quotes |
"Hi", "" | String | Text, double quotes |
true, false | boolean | Lowercase |
null | any reference type | Not 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
intunless it ends inL. Writing5000000000fails because the literal itself is too big for anint. - A decimal literal is a
doubleunless it ends inf. Sofloat f = 0.5;fails, because it tries to put adoubleinto afloatbox. Write0.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:
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_RATEtells the reader what0.15means. A bare0.15buried 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 name | Style | Example |
|---|---|---|
| Variables (and methods, later) | camelCase: lower-case first word, then each new word capitalised | itemCount, totalPrice |
| Constants | UPPER_SNAKE_CASE: capitals, words separated by underscores | TAX_RATE, MAX_USERS |
| Classes | PascalCase: every word capitalised | Cart, 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:
itemCountbeatsicorx1. - 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)
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):
1000000 5000000000 0.5 0.15 A AThe 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)
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:
Tax: 30.0
5If someone later writes TAX_RATE = 0.2;, the compiler stops them:
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:
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:
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
userIdbecomes 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".
أظهر الحل A1
A1. int, long, double, float, char, String.
A2. Which of these are legal Java names: userName, 3rdPlace, final, max_speed, my score?
أظهر الحل 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.
أظهر الحل 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";.
أظهر الحل 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:
int n = 30;
int result = n * 24;(The variable n is a number of days, and 24 is hours per day.)
أظهر الحل B2
B2.
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.
final int limit = 10;
limit = limit + 1;أظهر الحل 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.
أظهر الحل C1
C1.
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.
أظهر الحل 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:
42isint,42Lislong,4.2isdouble,4.2fisfloat,'A'ischar,"A"isString. - Underscores in numeric literals (
1_000_000) help people read; the compiler ignores them. finalmakes 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
- What does a
longliteral end with, and afloatliteral? - What does
finaldo to a variable? - Which naming style is used for a constant?
- Is
my_totala legal name? Is it conventional? - Why is
price * 1.15worse thanprice * SALES_MULTIPLIER?
أظهر الإجابات
Lforlong,fforfloat.- It allows a value to be stored once and rejects any later assignment.
- UPPER_SNAKE_CASE, such as
MAX_USERS. - It is legal, but not conventional; the convention is
myTotal. - The bare
1.15is 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, anddliteral suffixes, recommends uppercaseL, and saysdoubleis 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.
التطبيق
طبّق هذا الدرس بمختبر الوحدة وتمارينها واختبارها.
تعليم الدرس كمكتمل اختياري ويمكنك التراجع عنه في أي وقت. يبقى تقدمك محفوظًا في هذا المتصفح.