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.
1️⃣ Comments
| Kind | How to write it | Use it for |
| Single-line | // text | Short notes on one line |
| Multi-line | /* 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);
}
}
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 iis a useless comment.
/* ... */ 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.
2marks ✘ marks2 ✔
total-marks ✘ totalMarks ✔
my score ✘ myScore ✔
class ✘ className ✔
Figure 2: Four quick checks for a valid identifier.
| Name | Valid? | Reason |
| age | ✔ Yes | letters only |
| _count | ✔ Yes | may start with underscore |
| $price | ✔ Yes | may start with $ (rarely used) |
| totalMarks2 | ✔ Yes | digits allowed after the first character |
| 2marks | ✘ No | cannot start with a digit |
| total-marks | ✘ No | hyphen is the minus operator |
| my score | ✘ No | spaces not allowed |
| class | ✘ No | reserved keyword |
| Age and age | ✔ Yes | two 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);
}
}
age = 20, Age = 21
_count = 3, $price = 99
totalMarks2 = 450, var = 7
ageandAgeare two separate variables, because Java is case-sensitive.- Names starting with
_or$are legal, but beginners should use plain letters. varworks 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
| Thing | Style | Examples |
| Class | CamelCase, starts with a capital | StudentCard, BankAccount |
| Method | camelCase, starts with a verb | calculateTotal, printReport |
| Variable | camelCase, meaningful | totalMarks, studentName |
| Constant | UPPER_CASE with underscores | TAX_RATE, MAX_SIZE |
| Package | all lowercase | com.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);
}
}
Final price = 590.0
NamingStyleis a class name in CamelCase.TAX_RATEis a constant in UPPER_CASE, andfinalstops it from being changed.priceWithTax,basePriceandfinalPriceare camelCase, and each name says what it holds. Compare withx,yandz.- 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.
byteshortintlongfloatdoublecharbooleanvoidifelseswitchcasedefaultforwhiledobreakcontinuereturnclassinterfaceenumextendsimplementsnewthissuperinstanceofabstractfinalstaticpublicprivateprotectedpackageimporttrycatchfinallythrowthrowsassertnativesynchronizedtransientvolatilestrictfpconstgototrue, 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"));
}
}
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.
classis reserved, butClassis not, because keywords are all lowercase. Still, avoid names likeClassfor variables.constandgotoare 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;
}
}
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;
}
}
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;
}
}
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 - marksas subtraction, so it expects a semicolon aftertotal.
⚠️ Common Mistakes
| Mistake | Problem | Fix |
|---|---|---|
Naming a variable int, class, new | Reserved keyword | Use a different name, for example count |
1stYear | Starts with a digit | firstYear or year1 |
student name | Space not allowed | studentName |
Using Total and total by accident | Two different variables | Choose one style and stay with it |
| Single-letter names everywhere | Hard to read | Use meaningful names (except for loop counters like i) |
| Writing comments that repeat the code | Adds noise | Explain 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:
ageandAgeare different. - Use CamelCase for classes, camelCase for methods and variables, UPPER_CASE for constants.
- Java has 50 keywords, all in lowercase;
constandgotoare 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) Renamex,y,zin 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 isClassa legal name butclassis 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
- Lesson 1: What is Java? Features and Uses
- Lesson 2: Installing the JDK and Running Your First Program
- Lesson 3: JDK, JRE, JVM and WORA Explained
- Lesson 4: JVM Architecture and JIT Compilation
- Lesson 5: Hello World Program Explained Line by Line
Module 2 · Building Blocks
- Lesson 6: Comments, Identifiers and Keywords
- Lesson 7: Variables and Literals
- Lesson 8: Primitive Data Types in Java
- Lesson 9: Type Conversion and Casting
- Lesson 10: Taking Input with the Scanner Class
- Lesson 11: Escape Characters and Variable Scope in Java
Module 3 · Operators
- Lesson 12: Arithmetic Operators and Increment/Decrement in Java
- Lesson 13: Relational and Logical Operators in Java
- Lesson 14: Bitwise and Shift Operators in Java
- Lesson 15: Assignment, Ternary Operator and Operator Precedence in Java
Module 4 · Control Flow
- Lesson 16: if, if-else and else-if Ladder in Java
- Lesson 17: switch Statement in Java (Classic and Modern)
- Lesson 18: while and do-while Loops in Java
- Lesson 19: for Loop and Nested Loops (Patterns) in Java
- Lesson 20: break, continue and Labelled Loops in Java
Module 5 · Data and Methods
- Lesson 21: Arrays in Java (One-Dimensional)
- Lesson 22: Multidimensional Arrays in Java
- Lesson 23: Strings and the String Pool in Java
- Lesson 24: String Methods and StringBuilder in Java
- Lesson 25: Methods and Method Overloading in Java
- Lesson 26: Recursion Basics in Java
- Lesson 27: ArrayList and Wrapper Classes in Java
- Lesson 28: Exception Handling Basics in Java