Syntax & Comments

Java · Lesson 4 of 32 7 min read Updated

Every language has grammar rules. In English, a sentence ends with a full stop and starts with a capital letter. In Java, a statement ends with a semicolon and code is grouped with curly braces. The compiler is much stricter than an English teacher: one missing character and your program does not compile at all.

In this lesson you will learn the basic grammar of Java (its syntax), the naming rules and conventions that every Java programmer follows, and the three kinds of comments you can write.

Statements, blocks and semicolons

A statement is one complete instruction, such as "create this variable" or "print this value". Most statements end with a semicolon ;. A block is a group of statements inside curly braces { }. Classes, methods, if statements and loops all use blocks.

Java
// Canteen.java: prints today's bill for the college canteen
public class Canteen {
    public static void main(String[] args) {
        int samosaPrice = 15;   // price of one samosa in rupees
        int teaPrice = 10;

        /*
         * Kabir ordered 3 samosas and 2 cups of tea.
         * We multiply each price by its quantity and add them.
         */
        int total = samosaPrice * 3 + teaPrice * 2;

        System.out.println("Kabir's bill: Rs " + total);
        // System.out.println("Discount applied");   (switched off for now)
    }
}
Output
Kabir's bill: Rs 65

Notice the structure: the class block contains the main method block, which contains four statements. Every opening brace has a matching closing brace. Declarations of classes and methods do not need a semicolon after their closing brace.

Whitespace and indentation

Java ignores extra spaces, tabs and line breaks between words. This one-line program compiles and prints 20:

Java
public class Messy { public static void main(String[] args) { int a = 4; int b = 5; System.out.println(a * b); } }

It works, but nobody can read it. Java programmers follow a common style: one statement per line, 4 spaces of indentation for each level of nesting, and the opening brace at the end of the line, not on a line of its own. Your editor can format code for you (in IntelliJ IDEA, Code > Reformat Code), so you rarely need to fix spacing by hand.

Java is case-sensitive

score, Score and SCORE are three different names in Java. The same is true for everything: System is a class from the standard library, while system means nothing to the compiler.

Java
public class Score {
    public static void main(String[] args) {
        int score = 10;
        int Score = 20;
        System.out.println(score);
        System.out.println(Score);
    }
}
Output
10
20

This program is legal, but using two names that differ only in capitals is a terrible idea. Choose clearly different names instead.

Identifiers and keywords

An identifier is a name you choose for a class, variable or method. The rules:

  • It can contain letters, digits, _ and $.
  • It cannot start with a digit: 2ndPlace is illegal, secondPlace is fine.
  • It cannot be a keyword, a word that Java reserves for itself, such as class, int, if, for, while, return, new, static, public and void. The words true, false and null are also reserved.
  • It cannot contain spaces or symbols like - or @.

Some words, such as var, record, yield and sealed, are contextual keywords: they only have a special meaning in certain places. You can still have a variable called record, although it is better to avoid it.

Naming conventions

The compiler does not enforce these, but every Java team follows them, and breaking them makes your code look odd to other programmers:

Kind of nameStyleExamples
Class, record, interfacePascalCase (each word capitalised)BankAccount, TrainTicket
Variable, methodcamelCase (first word lowercase)totalMarks, calculateFare()
Constant (static final)UPPER\_SNAKE\_CASEMAX_SEATS, GST_RATE
Packageall lowercase, often a reversed domainin.college.library

Choose names that say what something is: studentCount is far better than sc or x.

Comments

Comments are notes for humans. The compiler skips them completely. Java has three kinds:

  • // starts a single-line comment. Everything after it on that line is ignored.
  • /* and */ surround a multi-line comment. These cannot be nested: a */ inside closes the whole comment.
  • /** and */ surround a documentation comment (Javadoc). It describes a class or method, and the javadoc tool turns these comments into HTML documentation pages.
Java
/**
 * Works out auto-rickshaw fares in Lucknow.
 */
public class Fare {
    static final int BASE_FARE = 30;
    static final int RATE_PER_KM = 12;

    /**
     * Returns the fare for a trip.
     *
     * @param km distance in whole kilometres
     * @return the fare in rupees
     */
    static int fareFor(int km) {
        return BASE_FARE + RATE_PER_KM * km;
    }

    public static void main(String[] args) {
        int tripKm = 6;
        System.out.println("Fare for " + tripKm + " km: Rs " + fareFor(tripKm));
    }
}
Output
Fare for 6 km: Rs 102

The tags @param and @return describe the method's input and result. IDEs show these comments when you hover over the method, and javadoc -d docs Fare.java generates a small documentation website in the docs folder.

Writing useful comments

A good comment explains why, not what. The code already says what it does.

  • Weak: total = total + 50; // add 50 to total
  • Useful: total = total + 50; // flat delivery charge for orders outside city limits

Programmers also "comment out" a line (put // in front of it) to switch it off while testing, as in the canteen example. Delete such lines before you share your code.

Common mistakes

  • Missing or extra braces. Every { needs a }. Good indentation makes a missing one easy to spot.
  • Starting a name with a digit. int 2ndPlace = 5; gives error: not a statement and error: ';' expected, which is confusing. The real problem is the name.
  • Using a keyword as a name. int class = 5; fails for the same reason. Pick another name, such as className or section.
  • Nesting multi-line comments. /* outer /* inner */ still outer */ ends at the first */, so the rest becomes broken code.
  • Comments that repeat the code. They add noise and go out of date. Explain the reason instead.

Key points

  • Statements end with ;, and blocks are grouped with { }.
  • Java ignores extra whitespace; use 4-space indentation and one statement per line for readability.
  • Java is case-sensitive: total and Total are different names.
  • Identifiers use letters, digits, _ and $, cannot start with a digit and cannot be keywords.
  • Use PascalCase for classes, camelCase for variables and methods, UPPER\_SNAKE\_CASE for constants.
  • // and /* */ are ordinary comments; /** */ (and /// since Java 23) are documentation comments.

Exercise

The program below has four problems: two compile errors and two style problems. Find and fix them all.

Java
public class shopBill {
    public static void main(String[] args) {
        int Price = 250
        int 3items = Price * 3;
        System.out.println("Total: Rs " + 3items);
    }
}
Show solution
Java
public class ShopBill {
    public static void main(String[] args) {
        int price = 250;
        int threeItems = price * 3;
        System.out.println("Total: Rs " + threeItems);
    }
}
Output
Total: Rs 750

The compile errors were the missing semicolon after 250 and the name 3items, which starts with a digit. The style problems were the class name shopBill (classes use PascalCase, so save the file as ShopBill.java) and the variable Price (variables use camelCase).

Quick Quiz

1. Which of these is a legal Java identifier?

2. Which comment style can the javadoc tool turn into documentation?

3. What is the conventional name for a constant holding the GST rate?

4. Are count and Count the same variable in Java?

Learn Java with a mentor

Free lessons get you started. Our Java, C & C++ Programming training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call