Java Basics, Java Programming · December 2, 2026

Java for Beginners, Lesson 6: Comments, Identifiers and Keywords

Java for Beginners · Module 2: Building Blocks


🎯 Why Learn Comments, Identifiers and Keywords?

Every language has three basic things: notes for people, names for things, and reserved words with special meaning. In Java these are comments, identifiers and keywords. A good programmer uses all three with care, because clear names and short notes make code easy to read months later, even for you.

📌 Comments are ignored by the compiler. Identifiers are names you choose. Keywords are words Java has reserved for itself.

1️⃣ Comments

KindHow to write itUse it for
Single-line// textShort notes on one line
Multi-line/* text
more text */
Longer explanations, or switching off a block
Documentation (Javadoc)/** text */Describing classes and methods; tools turn it into web pages

Figure 1: The three kinds of comments in Java.

Program 1: The three kinds of comments

/**
 * CommentsDemo shows the three kinds of comments in Java.
 * This is a documentation comment (Javadoc).
 */
public class CommentsDemo {
    public static void main(String[] args) {
        // Single-line comment: explains the next line
        int price = 200;

        /* Multi-line comment:
           the compiler ignores everything between the markers */
        int quantity = 3;

        int total = price * quantity; // comment after code
        // System.out.println("This line is switched off");
        System.out.println("Total = " + total);
    }
}
🖥️ Output:
Total = 600
  • The compiler skips all comments, so they never change the output.
  • The line // System.out.println("This line is switched off"); does not run. Programmers “comment out” code to test without deleting it.
  • A comment after code on the same line is fine, as in int total = ...; // comment.
  • Good comments explain why, not what is obvious. i++ // add 1 to i is a useless comment.
⚠️ Careful: /* ... */ comments cannot be nested. A */ inside ends the comment early.

2️⃣ Identifiers

An identifier is the name you give to a class, method or variable. Java has strict rules.

Check 1: Does it start with a letter, underscore (_) or dollar sign ($)?
2marks ✘ marks2 ✔
⬇ yes: next check  |  no: invalid
Check 2: Does it use only letters, digits, _ and $?
total-marks ✘ totalMarks ✔
⬇ yes: next check  |  no: invalid
Check 3: Is it free of spaces?
my score ✘ myScore ✔
⬇ yes: next check  |  no: invalid
Check 4: Is it different from every keyword?
class ✘ className ✔
⬇ yes: next check  |  no: invalid
✅ Valid identifier

Figure 2: Four quick checks for a valid identifier.

NameValid?Reason
age✔ Yesletters only
_count✔ Yesmay start with underscore
$price✔ Yesmay start with $ (rarely used)
totalMarks2✔ Yesdigits allowed after the first character
2marks✘ Nocannot start with a digit
total-marks✘ Nohyphen is the minus operator
my score✘ Nospaces not allowed
class✘ Noreserved keyword
Age and age✔ Yestwo different names: Java is case-sensitive

Figure 3: Valid and invalid identifiers.

Program 2: Valid identifiers in action

public class IdentifierDemo {
    public static void main(String[] args) {
        int age = 20;
        int _count = 3;
        int $price = 99;
        int totalMarks2 = 450;
        int Age = 21;          // different from 'age': Java is case-sensitive
        int var = 7;           // legal: var is not a reserved word

        System.out.println("age = " + age + ", Age = " + Age);
        System.out.println("_count = " + _count + ", $price = " + $price);
        System.out.println("totalMarks2 = " + totalMarks2 + ", var = " + var);
    }
}
🖥️ Output:
age = 20, Age = 21
_count = 3, $price = 99
totalMarks2 = 450, var = 7
  • age and Age are two separate variables, because Java is case-sensitive.
  • Names starting with _ or $ are legal, but beginners should use plain letters.
  • var works as a name because it is only a special word in certain places, not a reserved keyword. It is better not to use it as a name.

3️⃣ Naming Conventions

ThingStyleExamples
ClassCamelCase, starts with a capitalStudentCard, BankAccount
MethodcamelCase, starts with a verbcalculateTotal, printReport
VariablecamelCase, meaningfultotalMarks, studentName
ConstantUPPER_CASE with underscoresTAX_RATE, MAX_SIZE
Packageall lowercasecom.example.shop

Figure 5: Java naming conventions. The compiler does not force them, but every Java programmer follows them.

Program 3: Good names make code read like a sentence

public class NamingStyle {
    static final double TAX_RATE = 0.18;

    static double priceWithTax(double basePrice) {
        return basePrice + basePrice * TAX_RATE;
    }

    public static void main(String[] args) {
        double basePrice = 500;
        double finalPrice = priceWithTax(basePrice);
        System.out.println("Final price = " + finalPrice);
    }
}
🖥️ Output:
Final price = 590.0
  • NamingStyle is a class name in CamelCase.
  • TAX_RATE is a constant in UPPER_CASE, and final stops it from being changed.
  • priceWithTax, basePrice and finalPrice are camelCase, and each name says what it holds. Compare with x, y and z.
  • 500 + 500 × 0.18 = 590.0, so the output is correct.

4️⃣ Keywords

A keyword is a word with a fixed meaning in Java, like class, int or if. You cannot use keywords as names.

Data types (9)
byte
short
int
long
float
double
char
boolean
void
Decisions and loops (11)
if
else
switch
case
default
for
while
do
break
continue
return
Classes and objects (12)
class
interface
enum
extends
implements
new
this
super
instanceof
abstract
final
static
Access (5)
public
private
protected
package
import
Errors (6)
try
catch
finally
throw
throws
assert
Special (5)
native
synchronized
transient
volatile
strictfp
Reserved, unused (2)
const
goto
Also reserved: the literals true, false and null.

Figure 4: The 50 keywords of Java, grouped by purpose. They cannot be used as names.

Program 4: Keywords are case-sensitive

import java.util.Arrays;
import java.util.List;

public class KeywordCount {
    public static void main(String[] args) {
        List<String> keywords = Arrays.asList(
            "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char",
            "class", "const", "continue", "default", "do", "double", "else", "enum",
            "extends", "final", "finally", "float", "for", "goto", "if", "implements",
            "import", "instanceof", "int", "interface", "long", "native", "new",
            "package", "private", "protected", "public", "return", "short", "static",
            "strictfp", "super", "switch", "synchronized", "this", "throw", "throws",
            "transient", "try", "void", "volatile", "while");

        System.out.println("Keywords listed: " + keywords.size());
        System.out.println("Is 'class' reserved? " + keywords.contains("class"));
        System.out.println("Is 'Class' reserved? " + keywords.contains("Class"));
        System.out.println("Is 'name' reserved?  " + keywords.contains("name"));
    }
}
🖥️ Output:
Keywords listed: 50
Is ‘class’ reserved? true
Is ‘Class’ reserved? false
Is ‘name’ reserved? false
  • The program stores all 50 keywords in a list and checks words against it. You will learn lists in Lesson 27.
  • class is reserved, but Class is not, because keywords are all lowercase. Still, avoid names like Class for variables.
  • const and goto are reserved but not used by Java.

5️⃣ What the Compiler Says About Bad Names

Using a keyword as a name

public class Bad1 {
    public static void main(String[] args) {
        int class = 5;
    }
}
🖥️ Compiler message:
Bad1.java:3: error: not a statement
int class = 5;
^
Bad1.java:3: error: ‘;’ expected
int class = 5;
^
Bad1.java:3: error: <identifier> expected
int class = 5;
^
3 errors

Starting a name with a digit

public class Bad2 {
    public static void main(String[] args) {
        int 2marks = 90;
    }
}
🖥️ Compiler message:
Bad2.java:3: error: not a statement
int 2marks = 90;
^
Bad2.java:3: error: ‘;’ expected
int 2marks = 90;
^
2 errors

A hyphen inside a name

public class Bad3 {
    public static void main(String[] args) {
        int total-marks = 90;
    }
}
🖥️ Compiler message:
Bad3.java:3: error: ‘;’ expected
int total-marks = 90;
^
1 error
  • One bad name can produce several messages. Fix the first error and compile again, because the later ones are often side effects.
  • In the hyphen case, Java reads total - marks as subtraction, so it expects a semicolon after total.

⚠️ Common Mistakes

MistakeProblemFix
Naming a variable int, class, newReserved keywordUse a different name, for example count
1stYearStarts with a digitfirstYear or year1
student nameSpace not allowedstudentName
Using Total and total by accidentTwo different variablesChoose one style and stay with it
Single-letter names everywhereHard to readUse meaningful names (except for loop counters like i)
Writing comments that repeat the codeAdds noiseExplain the reason, not the obvious

❓ Frequently Asked Questions

Q1. Is there a limit on identifier length?
No practical limit, but keep names short and clear.

Q2. Can identifiers contain non-English letters?
Yes, Java allows Unicode letters, but ordinary English names are the norm in shared code.

Q3. Are true, false and null keywords?
They are literals, but you also cannot use them as names.

Q4. Do comments slow the program?
No. The compiler removes them.

✅ Key Takeaways

  • Java has three comment types: //, /* */ and /** */.
  • Identifiers start with a letter, _ or $, may contain digits after that, and cannot be keywords.
  • Java is case-sensitive: age and Age are different.
  • Use CamelCase for classes, camelCase for methods and variables, UPPER_CASE for constants.
  • Java has 50 keywords, all in lowercase; const and goto are reserved but unused.
  • Fix the first compiler error first.
🎓 Practice questions: (1) Which of these are valid identifiers: _total, 9lives, first name, maxValue, float? (2) Rename x, y, z in a program that calculates a rectangle’s area so the code explains itself. (3) Add all three kinds of comments to Program 3. (4) Why is Class a legal name but class is not? (5) Write the correct convention for: a class that holds bank accounts, a method that finds the total, and a constant for the number of days in a week.
All 30 lessons in this series (open course page)

Module 1 · Getting Started

Module 2 · Building Blocks

Module 3 · Operators

Module 4 · Control Flow

Module 5 · Data and Methods

Module 6 · Objects and Revision