The code nobody could read
Riya's team project has a file written by a senior who has since graduated. It works, but it's full of names like x1, tmp and doIt(), with one comment that says // important. Riya spends two hours working out what it does. Arjun Sir uses it as a lesson.
Sir, the computer understood this code perfectly. Why was it so hard for me?
Because javac doesn't care about names or comments: it throws comments away and treats x1 exactly like cups. Names and comments exist only for humans, and the next human was you.
So naming is part of the job, not decoration.
Exactly. Today: what javac sees, what it ignores, which words you're not allowed to use, and the naming style every Java team expects.
Comments, keywords and identifiers
A comment is text in source code that the compiler ignores; Java has single-line (//), multi-line (/* */) and documentation (/** */) comments. A keyword is a word reserved by the language with a predefined meaning, which cannot be used as an identifier. An identifier is a name given to a class, interface, method, variable, constant or package; it must start with a letter, _ or $, may contain digits after that, is case-sensitive, and must not be a reserved keyword or the literals true, false or null.
Comments are notes for people. Keywords are Java's own words, like class and int, which you can't borrow as names. Identifiers are the names you choose, and conventions are the team habits for how those names should look.
Words you'll meet in this lesson
/** */ comment that the javadoc tool turns into HTML documentation.class, int, new, if…var, record, yield.PaymentService.totalAmount.MAX_RETRY_COUNT.Java naming conventions
| Kind | Style | Good examples | Avoid |
|---|---|---|---|
| Class / interface / enum / record | PascalCase noun | Student, PaymentService, Comparable | student, payment_service |
| Method | camelCase verb | calculateTotal(), isValid(), getName() | Calculate_Total(), doIt() |
| Variable / parameter | camelCase noun | chaiCount, customerName | x1, tmp2, CustomerName |
| boolean | camelCase question | isPaid, hasDiscount, canRetry | flag, status2 |
Constant (static final) | UPPER_SNAKE_CASE | GST_PERCENT, MAX_UPI_LIMIT | gstPercent, maxlimit |
| Package | all lowercase, reverse domain | com.myphatshala.billing | Billing, com.MyPhatshala |
| Type parameter | single capital letter | T, E, K, V | Type1 |
Exam tip: true, false and null are literals, not keywords, but you still can't use them as names. goto and const are reserved keywords that Java doesn't use. Identifiers are case-sensitive: total, Total and TOTAL are three different names.
Kinds of comments and keywords
Single-line //
From // to the end of the line. Best for short notes explaining why: // GST is added after the discount, as per policy.
Multi-line /* */
Spans several lines. Useful for a longer explanation. Can't be nested: /* /* */ */ breaks.
Javadoc /** */
Above a class or method. Tags like @param, @return and @throws describe the method. The javadoc tool and IDEs read them.
Keyword groups (about 50 reserved words)
| Group | Keywords |
|---|---|
| Primitive types | byte short int long float double char boolean void |
| Control flow | if else switch case default for while do break continue return |
| Classes and objects | class interface enum extends implements new this super instanceof package import |
| Modifiers | public private protected static final abstract synchronized volatile transient native strictfp |
| Exceptions | try catch finally throw throws assert |
| Reserved but unused | goto const, and _ (since Java 9) |
| Contextual (only special in some places) | var record yield sealed permits non-sealed module exports requires and a few more |
Why contextual keywords? When Java added var (Java 10) and record (Java 16), making them fully reserved would have broken old programs that used them as variable names. So int var = 5; still compiles, but a class can no longer be named record.
How javac reads names and comments
Unicode escapes are translated first
Before anything else, javac turns
That's why the famous trick\uXXXXsequences into characters, everywhere, even inside comments.// \u000a System.out.println("hi");actually runs:\u000abecomes a newline, ending the comment early.Comments and whitespace are removed
The lexer skips spaces, tabs, newlines and all three kinds of comments.
Nothing from a comment reaches the .class file. Comments cost nothing at run time, so there's no performance reason to avoid them.Each word is classified
Is it a keyword, a literal (
Reserved keywords always win.42,"hi",true), an operator, or an identifier?int new = 5;fails becausenewis read as the keyword, and the grammar then doesn't make sense.Identifiers are checked against the rules
Must not start with a digit; may use letters from any language (
Names are stored in the class file's constant pool (for classes, methods and fields), so renaming a public method changes the bytecode other classes link to.int नाम = 7;is legal),_and$.Conventions are checked by people and tools
javac doesn't enforce PascalCase or camelCase. Code reviewers, IDE inspections and tools like Checkstyle do.
Thejavadoctool reads/** */comments separately and generates HTML pages, like the official Java API documentation.
What javac keeps, and what it throws away: both views
Left: the source and the result. Right: how javac's lexer and the javadoc tool see it.
- A few lines of code with a single-line and a multi-line comment.
- It compiles. The comments make no difference to the program at all.
- Names can't start with a digit, and can't be a reserved keyword like
new. varandrecordare contextual keywords, so they work as variable names. Unicode letters are allowed too.- A Javadoc comment uses
@paramand@returntags. The javadoc tool turns it into a web page. - Following the conventions makes code read almost like a sentence.
- javac's lexer reads the source one character at a time.
- Comments and whitespace are discarded. The rest becomes tokens: keywords, identifiers, literals and symbols.
- A name starting with a digit splits into a number and a word; a reserved keyword can't be a name.
- Contextual keywords are only special in certain positions. Identifiers may use Unicode letters.
- The javadoc tool turns
/** */comments and their tags into HTML documentation. - Each kind of name has its own convention, so readers can tell what something is from its shape.
Names and comments in real teams
In companies, readable code is a requirement, not a preference. Here's how it's enforced and why.
Watch it with an example: a code review on a fee program
The code works but nobody can read it. Watch a reviewer fix one problem per step using Java's naming conventions.
- Before: this compiles and gives the right answer, but a teammate has to guess what
fee,m,aandxmean. - Class name: class names start with a capital letter and are nouns:
FeeCalculator. - Constant:
static finalvalues use capitals with underscores:MAX_INSTALMENTS. - Method and parameter: camelCase, and say what they are:
monthlyFee(int annualFee). - Comment: say why the code does something. The compiler throws comments away; they are only for humans.
- Package: lowercase, often a reversed domain such as
in.college.fees, so names never clash with other teams' classes. Tools like Checkstyle check these rules automatically in code review.
1. Code reviews
Every change is reviewed by teammates before merging. Unclear names and missing explanations for tricky logic are among the most common review comments.
2. Automated style checks
Tools like Checkstyle, SonarQube and IDE inspections flag naming violations and missing Javadoc automatically in the build, so humans can focus on logic.
3. Library and API documentation
The official Java API docs, and the docs of libraries like Spring, are generated from Javadoc comments. Companies publish internal API docs the same way.
4. TODO and FIXME markers
Developers mark unfinished work with // TODO and known problems with // FIXME. IDEs list them, and teams track them so they don't stay forever.
5. Package names that never clash
Using your organisation's domain in reverse (com.myphatshala…) keeps package names unique worldwide, so two libraries can both have a class called Utils without conflict.
Examples are simplified. Each team has its own style guide; many follow Google's or Oracle's Java conventions.
Riya's bill calculator, written properly
/**
* Calculates a canteen bill.
*/
public class Main {
static final int GST_PERCENT = 5; // constant: UPPER_SNAKE_CASE
public static void main(String[] args) {
int chaiCount = 3; // variable: camelCase
int billAmount = calculateBill(chaiCount);
System.out.println("Bill: Rs " + billAmount);
}
/** Returns the bill for the given number of cups, including GST. */
static int calculateBill(int cups) {
int base = cups * 20;
return base + base * GST_PERCENT / 100;
}
}/** Calculates a canteen bill. */A Javadoc comment for the class.GST_PERCENTAstatic finalconstant, so UPPER_SNAKE_CASE.chaiCount,billAmountVariables in camelCase that say what they hold.calculateBill(int cups)A method named with a verb, in camelCase.// constant: …Single-line comments. Real code should explain why, not repeat what; these are here for learning.
Comments vanish, names remain
Notice how the tracer never stops on a comment line: by the time the program runs, comments no longer exist.
Worked examples: real problems, solved and traced in memory
Good names and comments don't change what the program does; they change how fast the next person understands it. Each example is a real calculation written the way professional teams write it: clear names, constants in CAPITALS, and comments that explain why.
From x, y, z to names that explain themselves
Problem statement
A payroll snippet was written as double z = x * 1.4 - x * 0.12;. Rewrite it with meaningful names, constants and a short comment, and show it gives the same answer for a basic salary of Rs 30,000.
basic salary 30000
old: 38400.0 new: 38400.0
Approach
- Name every value:
basicSalary,HRA_RATE,PF_RATE. - Use camelCase for variables and UPPER_SNAKE_CASE for constants.
- Comment the business rule, not the obvious syntax.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
Constants and a Javadoc comment
Problem statement
An app's delivery fee is Rs 40, waived for orders of Rs 499 or more. Write a method with a Javadoc comment (/** … */) describing it, using named constants instead of magic numbers.
orders of Rs 350 and Rs 620
Rs 350 order: fee Rs 40 Rs 620 order: fee Rs 0
Approach
- Constants
DELIVERY_FEEandFREE_DELIVERY_FROM. - A Javadoc comment above the method: what it returns and why.
- Call it for two order values.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
Comments that explain why, not what
Problem statement
An electricity bill adds a minimum charge. Write it with two kinds of comments: a bad one that repeats the code and a good one that explains the business reason. Compute bills for 30 and 180 units.
30 units, 180 units; Rs 6/unit; minimum Rs 250
30 units: Rs 250 180 units: Rs 1080
Approach
- Name the constants.
- Use
Math.maxto apply the minimum. - Compare a useless comment with a useful one.
Solution: run it live
What happens in memory, step by step
Recorded from the real JVM: press Next to execute one line at a time. Watch method calls push and pop frames on the stack, and objects (numbered #1, #2 …) appear on the heap.
Check yourself
Quick revision
Lesson 2.7 in one screen
- Comments:
//single-line,/* */multi-line,/** */Javadoc (@param,@return,@throws). javac discards them. - About 50 reserved keywords;
goto/constunused;var,record,yieldare contextual. - Identifiers: letters, digits,
_,$; no digit first; no keywords or true/false/null; case-sensitive. - Conventions: PascalCase classes, camelCase methods and variables, UPPER_SNAKE_CASE constants, lowercase packages (reverse domain).
- Comment the why; let names explain the what.
Interview and viva questions
What are the types of comments in Java?
Single-line (//), multi-line (/* … */) and documentation comments (/** … */). Documentation comments are processed by the javadoc tool to generate HTML API documentation.
Is main a keyword?
No. main is an ordinary identifier; it's just the name the launcher looks for. You could even have a variable called main.
Why does Java reserve goto if it doesn't use it?
To prevent programmers coming from C and C++ from using it, and to keep the option open. Using goto in Java gives a compile error.
What makes a good comment?
It explains intent, reasons or non-obvious constraints (“rounding is done per line item, as required by the tax rules”) rather than repeating what the code says (“add 1 to i”). Outdated comments are worse than none, so update them with the code.
Can identifiers contain Unicode letters?
Yes. Java identifiers may use letters from any language, such as Devanagari or Chinese. Team code usually sticks to English ASCII names for readability and tooling.
Practice problems
Rewrite and write code with clear names, constants and helpful comments. The output stays the same; the code gets easier to read. The last three are business tasks.
Single-line and multi-line comments
Write a program with a // comment and a /* */ comment that prints "Comments are ignored".
(none)
Comments are ignored
Show solution and explanation
public class Main {
public static void main(String[] args) {
// this line is a single-line comment
/* this is a
multi-line comment */
System.out.println("Comments are ignored");
}
}How it works: the compiler skips comments completely; they don't exist in the bytecode.
camelCase names
Store the number of students in a class (42) in a well-named variable and print it.
42
Students: 42
Show solution and explanation
public class Main {
public static void main(String[] args) {
int studentsInClass = 42;
System.out.println("Students: " + studentsInClass);
}
}How it works: variables use camelCase: first word lowercase, later words capitalised.
A named constant
Replace the magic number 0.05 with a constant SERVICE_CHARGE and print the charge on Rs 800.
800
Service charge: Rs 40.0
Show solution and explanation
public class Main {
static final double SERVICE_CHARGE = 0.05;
public static void main(String[] args) {
System.out.println("Service charge: Rs " + 800 * SERVICE_CHARGE);
}
}How it works: constants use UPPER_SNAKE_CASE and say what the number means.
Rename for clarity
Rewrite int a = 60, b = 45; int c = a * b; (minutes per class × classes) with clear names and print the total minutes.
60, 45
Total teaching minutes: 2700
Show solution and explanation
public class Main {
public static void main(String[] args) {
int minutesPerClass = 60;
int classesPerTerm = 45;
int totalMinutes = minutesPerClass * classesPerTerm;
System.out.println("Total teaching minutes: " + totalMinutes);
}
}How it works: the same calculation, but now it explains itself.
Method name as a verb
Write a method calculateArea(double radius) and print the area for radius 2.
2
12.566370614359172
Show solution and explanation
public class Main {
static double calculateArea(double radius) {
return Math.PI * radius * radius;
}
public static void main(String[] args) {
System.out.println(calculateArea(2));
}
}How it works: methods are named with verbs (calculate, print, find) in camelCase.
Clear invoice calculation
Compute an invoice: unit price 250, quantity 6, discount 5%, GST 18%, with clear names and constants.
250, 6
Invoice total: Rs 1682
Show solution and explanation
public class Main {
static final double DISCOUNT_RATE = 0.05;
static final double GST_RATE = 0.18;
public static void main(String[] args) {
double unitPrice = 250;
int quantity = 6;
double subtotal = unitPrice * quantity;
double afterDiscount = subtotal * (1 - DISCOUNT_RATE);
double invoiceTotal = afterDiscount * (1 + GST_RATE);
System.out.println("Invoice total: Rs " + Math.round(invoiceTotal));
}
}How it works: 1500 → 1425 → 1681.5 → rounded to 1682. Each step has a name you could show an accountant.
Document a rule
Add a comment explaining why late fees are capped, and compute the fee: Rs 10/day, at most Rs 100, for 14 days late.
14 days
Late fee: Rs 100
Show solution and explanation
public class Main {
static final int FEE_PER_DAY = 10;
// Library rule: late fees are capped so students aren't charged more than a book's typical cost.
static final int MAX_LATE_FEE = 100;
public static void main(String[] args) {
int daysLate = 14;
int fee = Math.min(daysLate * FEE_PER_DAY, MAX_LATE_FEE);
System.out.println("Late fee: Rs " + fee);
}
}How it works: Math.min applies the cap; the comment records the reason, which code alone can't show.
Class and constant names
Create a class-level constant COMPANY_NAME and print it with a monthly target stored as monthlySalesTarget.
(none)
Shree Traders target: Rs 500000
Show solution and explanation
public class Main {
static final String COMPANY_NAME = "Shree Traders";
public static void main(String[] args) {
int monthlySalesTarget = 500000;
System.out.println(COMPANY_NAME + " target: Rs " + monthlySalesTarget);
}
}How it works: classes use PascalCase (Main), constants UPPER_SNAKE_CASE, variables camelCase.
Real-world scenario questions (asked in company interviews)
Readability problems are maintenance problems, and maintenance is most of a developer's job. Decide your answer first, then open the model answer.
The comment says 18%, the code says 12%
While fixing a bug, you find // apply 18% GST directly above amount * 0.12. Finance says the correct rate for this product is 12%. What does this tell you, and what would you do?
The interviewer is checking: do you understand that comments can go stale, and how to make code self-explaining?
Show a strong answer
The code was updated but the comment wasn't, so the comment is now actively misleading. javac never checks comments, so this happens easily.
- Confirm the correct behaviour with finance (here, the code is right).
- Replace the magic number and the comment with a named constant or configuration value, e.g.
GST_RATE_REDUCED, so the code explains itself. - Keep only comments that explain why (for example, the rule or notification behind the rate), and update comments in the same change as the code.
Avoid: “fixing” the code to match the comment without checking.
200 lines of commented-out code
A class contains large blocks of old code commented out “in case we need it later”. Your reviewer asks you to delete them. A teammate is nervous that the code will be lost. How do you respond?
The interviewer is checking: do you know that version control keeps history, and why dead code hurts?
Show a strong answer
- Git already keeps every old version. The code can be found with
git logor the IDE's history, so deleting it loses nothing. - Commented-out code confuses readers (is it important? is it a bug?), goes stale as the rest of the code changes, and clutters searches.
- If something might be needed, link the commit or create a ticket explaining why, instead of keeping the code inline.
Avoid saying: “Comments don't affect the program, so it's harmless.”
Old code stopped compiling after the upgrade
While upgrading a legacy project from Java 8 to Java 21, the build fails in a few files: one uses _ as a variable name, another has a class named record. The code was fine for years. Why, and how would you handle it?
The interviewer is checking: do you know that new Java versions add keywords, and how to fix this safely?
Show a strong answer
Newer Java versions reserved new words. _ became a keyword in Java 9 (and is now used for unnamed variables), and record became a restricted name for types in Java 16. Old code using them as names no longer compiles.
- Rename them with the IDE's Rename refactoring, so every usage is updated.
- If the class is part of a public API used by other systems, coordinate the rename with those teams.
- Compile with the target JDK early in the upgrade to find all such issues at once.
Avoid: staying on Java 8 just because of a few names.
Nobody uses your library correctly
You wrote a shared payment-validation library. Other teams keep calling validate(String s, int t) with the wrong arguments and asking you questions on chat. What would you improve?
The interviewer is checking: do you treat names and Javadoc as part of an API's design?
Show a strong answer
- Rename for clarity:
validateUpiId(String upiId, int maxLength), or better, use types that can't be mixed up. - Add Javadoc to every public method: what it does, each
@param, the@returnvalue and every@throws, with an example. - Publish the generated Javadoc (and a short README) so IDEs show it on hover.
- Deprecate the old method with
@Deprecatedand point to the new one, rather than breaking callers suddenly.
Avoid saying: “They should read the source.”