Comments, keywords and naming conventions

Code is read far more often than it is written. Good names and useful comments make a program easy to understand; bad ones make even correct code hard to work with. In this lesson you'll learn the three kinds of comments, which words Java reserves, the rules for naming things, and the conventions every Java team expects.

Module 2 · Language Basics⏱ 15 minBeginnerNo install needed8 practice problems
1 The story

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.

Before // important int doIt(int x1) { int tmp = x1 * 20; return tmp + tmp * 5 / 100; } ? After /** Bill for the given cups, incl. GST. */ int calculateBill(int cups) { int base = cups * CHAI_PRICE; return base + base * GST_PERCENT / 100; } ✓ myphatshala.in
Riya

Sir, the computer understood this code perfectly. Why was it so hard for me?

Arjun Sir

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.

Riya

So naming is part of the job, not decoration.

Arjun Sir

Exactly. Today: what javac sees, what it ignores, which words you're not allowed to use, and the naming style every Java team expects.

2 Definition

Comments, keywords and identifiers

Formal definition (write this in exams)

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.

In simple words

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

JavadocA /** */ comment that the javadoc tool turns into HTML documentation.
Reserved keywordNever allowed as a name: class, int, new, if…
Contextual keywordA keyword only in certain places, like var, record, yield.
PascalCaseEvery word capitalised: PaymentService.
camelCaseFirst word lowercase, then capitals: totalAmount.
UPPER_SNAKE_CASECapitals with underscores: MAX_RETRY_COUNT.

Java naming conventions

KindStyleGood examplesAvoid
Class / interface / enum / recordPascalCase nounStudent, PaymentService, Comparablestudent, payment_service
MethodcamelCase verbcalculateTotal(), isValid(), getName()Calculate_Total(), doIt()
Variable / parametercamelCase nounchaiCount, customerNamex1, tmp2, CustomerName
booleancamelCase questionisPaid, hasDiscount, canRetryflag, status2
Constant (static final)UPPER_SNAKE_CASEGST_PERCENT, MAX_UPI_LIMITgstPercent, maxlimit
Packageall lowercase, reverse domaincom.myphatshala.billingBilling, com.MyPhatshala
Type parametersingle capital letterT, E, K, VType1

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.

3 Types and ways to use it

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.

Most used

Multi-line /* */

Spans several lines. Useful for a longer explanation. Can't be nested: /* /* */ */ breaks.

Longer notes

Javadoc /** */

Above a class or method. Tags like @param, @return and @throws describe the method. The javadoc tool and IDEs read them.

API docs

Keyword groups (about 50 reserved words)

GroupKeywords
Primitive typesbyte short int long float double char boolean void
Control flowif else switch case default for while do break continue return
Classes and objectsclass interface enum extends implements new this super instanceof package import
Modifierspublic private protected static final abstract synchronized volatile transient native strictfp
Exceptionstry catch finally throw throws assert
Reserved but unusedgoto 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.

4 Step by step

How javac reads names and comments

  1. Unicode escapes are translated first

    Before anything else, javac turns \uXXXX sequences into characters, everywhere, even inside comments.

    That's why the famous trick // \u000a System.out.println("hi"); actually runs: \u000a becomes a newline, ending the comment early.
  2. 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.
  3. Each word is classified

    Is it a keyword, a literal (42, "hi", true), an operator, or an identifier?

    Reserved keywords always win. int new = 5; fails because new is read as the keyword, and the grammar then doesn't make sense.
  4. Identifiers are checked against the rules

    Must not start with a digit; may use letters from any language (int नाम = 7; is legal), _ and $.

    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.
  5. Conventions are checked by people and tools

    javac doesn't enforce PascalCase or camelCase. Code reviewers, IDE inspections and tools like Checkstyle do.

    The javadoc tool reads /** */ comments separately and generates HTML pages, like the official Java API documentation.
5 See it happen

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.

From readable source to tokens 6 steps
What you see // 3 cups of chaiint chaiCount = 3; /* cups */total = chaiCount * PRICE; int 2ndPlace = 5;int new = 10;int _rank = 1; // ok, but unusual var var = 5;int record = 3;int नाम = 7; /** * Returns the bill including GST. * @param cups number of cups * @return total in rupees */int calculateBill(int cups) package com.myphatshala.billing;class BillCalculator { static final int GST_PERCENT = 5; int calculateBill(int chaiCount) compiles ✓ error: not a statement / ';' expected error: <identifier> expected compiles ✓ (all three are legal names) javadoc → BillCalculator.html compiles ✓ and reads like English Code with two comments. What does javac do with the comments? A digit first, and a keyword as a name. Surprisingly legal names. A Javadoc comment with tags. Every name follows the convention. myphatshala.in
Behind the screen The lexer scans character by character // 3 cups of chai ⏎ int chaiCount = 3; /* cups */ … reading here Comments and spaces are thrown away int chaiCount = 3 ; keywordidentifierliteralsymbol “3 cups of chai” and “cups” never reach the parser. The .class file is identical with or without them. 2ndPlace: starts with a digit, so the lexer reads the number 2, then the word ndPlace. new is always the keyword for creating objects, so int new breaks the grammar. _rank is legal, but convention avoids leading _. var var: first var is a type position → keyword, second is a name position → identifier. record: special only when declaring a type. नाम: Java identifiers can use Unicode letters. Legal isn't the same as good: use English camelCase in teams. Class BillCalculator int calculateBill(int cups) Returns the bill including GST. Parameters: cups - number of cups Returns: total in rupees Generated by the javadoc tool; IDEs show it on hover. com.myphatshala.billing → package: lowercase BillCalculator → class: PascalCase noun GST_PERCENT → constant: UPPER_SNAKE calculateBill → method: camelCase verb chaiCount → variable: camelCase noun myphatshala.in
6 Real-world use

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.

Same code, readable names 6 steps
Animated example package in.college.fees; class fee { class FeeCalculator { static final int m = 3; static final int MAX_INSTALMENTS = 3; int a(int x) { int monthlyFee(int annualFee) { return x / 12; return annualFee / 12; } } // fee is split into 12 equal parts } Works, but what are fee, m, a and x? Classes: PascalCase nouns Constants: UPPER_SNAKE_CASE Methods and variables: camelCase Comments explain why, not what Packages: lowercase, reversed domain myphatshala.in

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.

Pull request→“Rename x1 to retryCount”→Merged

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.

git push→Checkstyle / Sonar→Naming warnings

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.

/** … */→mvn javadoc:javadoc→HTML docs site
// TODO: add retry// FIXME: rounding

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.

// TODO: add retry→IDE TODO list→Ticket in the backlog
com.company.payments

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.

myphatshala.in→com.myphatshala.billing→Unique names

Examples are simplified. Each team has its own style guide; many follow Google's or Oracle's Java conventions.

7 Run the code

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;
    }
}
Bill: Rs 63
  • /** Calculates a canteen bill. */A Javadoc comment for the class.
  • GST_PERCENTA static final constant, 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.
8 Line by line

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.

Example 1Payroll · readability

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.

Input
basic salary 30000
Expected output
old: 38400.0
new: 38400.0

Approach

  1. Name every value: basicSalary, HRA_RATE, PF_RATE.
  2. Use camelCase for variables and UPPER_SNAKE_CASE for constants.
  3. 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.

Example 2E-commerce · delivery

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.

Input
orders of Rs 350 and Rs 620
Expected output
Rs 350 order: fee Rs 40
Rs 620 order: fee Rs 0

Approach

  1. Constants DELIVERY_FEE and FREE_DELIVERY_FROM.
  2. A Javadoc comment above the method: what it returns and why.
  3. 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.

Example 3Utilities · billing

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.

Input
30 units, 180 units; Rs 6/unit; minimum Rs 250
Expected output
30 units: Rs 250
180 units: Rs 1080

Approach

  1. Name the constants.
  2. Use Math.max to apply the minimum.
  3. 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.

9 Quiz and revision

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/const unused; var, record, yield are 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.

P1Easy

Single-line and multi-line comments

Write a program with a // comment and a /* */ comment that prints "Comments are ignored".

Input
(none)
Expected output
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");
    }
}
Comments are ignored

How it works: the compiler skips comments completely; they don't exist in the bytecode.

P2Easy

camelCase names

Store the number of students in a class (42) in a well-named variable and print it.

Input
42
Expected output
Students: 42
Show solution and explanation
public class Main {
    public static void main(String[] args) {
        int studentsInClass = 42;
        System.out.println("Students: " + studentsInClass);
    }
}
Students: 42

How it works: variables use camelCase: first word lowercase, later words capitalised.

P3Easy

A named constant

Replace the magic number 0.05 with a constant SERVICE_CHARGE and print the charge on Rs 800.

Input
800
Expected output
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);
    }
}
Service charge: Rs 40.0

How it works: constants use UPPER_SNAKE_CASE and say what the number means.

P4Medium

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.

Input
60, 45
Expected output
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);
    }
}
Total teaching minutes: 2700

How it works: the same calculation, but now it explains itself.

P5Medium

Method name as a verb

Write a method calculateArea(double radius) and print the area for radius 2.

Input
2
Expected output
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));
    }
}
12.566370614359172

How it works: methods are named with verbs (calculate, print, find) in camelCase.

P6Business problem

Clear invoice calculation

Compute an invoice: unit price 250, quantity 6, discount 5%, GST 18%, with clear names and constants.

Input
250, 6
Expected output
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));
    }
}
Invoice total: Rs 1682

How it works: 1500 → 1425 → 1681.5 → rounded to 1682. Each step has a name you could show an accountant.

P7Business problem

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.

Input
14 days
Expected output
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);
    }
}
Late fee: Rs 100

How it works: Math.min applies the cap; the comment records the reason, which code alone can't show.

P8Business problem

Class and constant names

Create a class-level constant COMPANY_NAME and print it with a monthly target stored as monthlySalesTarget.

Input
(none)
Expected output
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);
    }
}
Shree Traders target: Rs 500000

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.

Tax software · bug investigationFresher

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.

Any company · code reviewFresher

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 log or 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.”

Enterprise · Java upgrade1–3 years

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.

Product company · internal library1–3 years

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 @return value 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 @Deprecated and point to the new one, rather than breaking callers suddenly.

Avoid saying: “They should read the source.”