Õppetund 8/140
Kirjalik õppetund · 15 min

Java Syntax and Coding Conventions

Learn Java's syntax rules, keywords and identifiers, naming conventions, readable formatting and comments, and spot common syntax errors.

Eelvaade

Vaatad tasuta eelvaate õppetundi.

Lesson Overview

When writing Java code, you need to follow the language's specific syntax and naming rules. If the syntax is incorrect, the compiler cannot compile the code. Even when code is technically valid, inconsistent naming or formatting can make it difficult to read and maintain.

Code is read far more often than it is written: by you next week, by a teammate, by a reviewer. In this lesson, we separate the rules the compiler enforces (syntax, valid names) from the conventions Java developers follow so that everyone's code looks familiar, and we practise reading the compiler's error messages when a rule is broken.

Learning Objectives

After completing this lesson, you will be able to:

  • Explain what Java syntax is
  • Distinguish between keywords and identifiers
  • Identify valid and invalid identifiers
  • Follow naming conventions for classes, methods, variables, and constants
  • Understand the basic use of semicolons, braces, and parentheses
  • Format Java code in a readable way
  • Recognize single-line, multi-line, and Javadoc comments
  • Identify common syntax errors

What Is Java Syntax?

Syntax is the set of grammatical rules of a programming language. The Java compiler expects code to follow a specific structure. Valid:

java
int age = 30;

This line creates a variable named age. You will learn about variables in the next lesson. For now, focus only on how the line is written. Here are two invalid versions:

java
int age 30;
int age = 30

In the first, the assignment operator = is missing. In the second, the semicolon at the end of the statement is missing. The correct form is int age = 30;. Breaking the syntax rules of the language generally causes a compilation error.

Java Is Case-Sensitive

Java treats uppercase and lowercase letters as different, so Main, main and MAIN are three different identifiers. Similarly, age and Age are two different variables:

java
int age = 30;
int Age = 40;

However, you should avoid creating similar names that differ only by capitalization. This is valid but confusing:

java
int price = 100;
int Price = 200;

Lesson 1.07 showed the same rule for System and system, with the compiler message it produces.

Java Keywords

A keyword is a reserved word in the Java language with a predefined meaning. You have already seen public, class, static, void and int. Other common keywords include private, protected, boolean, if, else, for, while, return, new, final, interface, extends, implements, try and catch. Keywords cannot be used as programmer-defined identifiers. Invalid:

java
int class = 10;
boolean static = true;

true, false, and null are also special reserved literals, so they cannot be used as identifiers.

What Is an Identifier?

An identifier is a name provided by the programmer: the name of a class, method, variable, parameter, constant or package. In this example, the identifiers are Student, studentName, and age:

java
public class Student {

    String studentName;
    int age;
}

Identifier Naming Rules

Java identifiers have several mandatory rules:

  • Can start with a letter. Valid: age, studentName, coursePrice.
  • Can start with an underscore or dollar sign. _age and $generatedValue are technically valid. However, in normal application code, it is generally better to avoid leading _ or $ unless there is a project-specific reason.
  • Cannot start with a number. 1student and 2ndCourse are invalid; write student1 and secondCourse instead.
  • Cannot contain spaces. student age is invalid; write studentAge.
  • Cannot contain hyphens. course-price is invalid; write coursePrice.
  • Cannot use a keyword. class, public, and return are invalid, while classCount, publicCourse, and returnValue could be valid identifiers.

Valid and Invalid Identifiers

IdentifierValid?Note
studentNameYesRecommended style
course2YesValid
_totalYesValid, usually avoid leading _
$valueYesValid, uncommon in normal code
2studentNoStarts with a number
student nameNoContains a space
student-nameNoContains a hyphen
classNoJava keyword

A Valid Name and a Good Name Are Not the Same

Just because the compiler accepts an identifier does not mean it is a good name. This is technically valid, but the meaning is not clear:

java
int a = 20;
String n = "Sakib";

Better:

java
int studentAge = 20;
String studentName = "Sakib";

When reading code, the purpose of a value should be understandable from its name.

Java Naming Conventions

Naming conventions are not mandatory compiler rules. However, following consistent conventions is important in professional Java code. Common Java conventions include:

ElementConventionExample
ClassPascalCaseGradeCalculator
MethodcamelCasecalculateTotal()
VariablecamelCasestudentName
ParametercamelCasecoursePrice
ConstantUPPER_SNAKE_CASEMAXIMUM_ATTEMPTS
Packagelowercasecom.tarkev.course

Class Names: PascalCase

Class names are generally written in PascalCase: Student, BankAccount, GradeCalculator, CourseEnrollment. Avoid student, bank_account and gradecalculator. Class names should also be meaningful. public class GradeCalculator is a good name, while public class Data is less clear. A class name should give an idea of its responsibility or the concept it represents.

Variables and Methods: camelCase

In camelCase, the first word begins with a lowercase letter and each following word begins with a capital letter, as in studentName, totalPrice, and calculateAverage. Variables are named like studentAge, courseName and isAvailable; methods, which usually describe an action, like calculateTotal(), displayResult() and createAccount().

Boolean Names

A boolean variable should preferably have a name that clearly represents a true or false condition. Good:

java
boolean isActive;
boolean hasPermission;
boolean canEnroll;
boolean paymentCompleted;

Less clear:

java
boolean flag;
boolean value;
boolean status;

Constants: UPPER_SNAKE_CASE

A common Java convention for constants is UPPER_SNAKE_CASE:

java
static final int MAXIMUM_ATTEMPTS = 5;
static final int MINIMUM_AGE = 18;

We will learn about final and constants in detail in a later lesson. For now, simply recognize the naming convention.

Package Names

Package names are generally written in lowercase. Write package com.tarkev.foundation;, and avoid package Com.Tarkev.Foundation;.

Meaningful Names

As we saw with a and n above, single letters hide the purpose of a value. int totalMarks = mathematicsMark + englishMark; explains itself; int z = x + y; does not.

Avoid Unnecessary Abbreviations

Avoid:

java
int stdCnt;
String crsNm;

Better:

java
int studentCount;
String courseName;

Names should be concise, but they should not lose their meaning.

Semicolons, Braces, and Parentheses

Semicolon ;

Many simple Java statements end with a semicolon, and a missing semicolon causes a compilation error. Technically, multiple statements can be written on one line:

java
int age = 30; String name = "Sakib";

However, for readable code, they are generally written on separate lines, one statement per line:

java
int age = 30;
String name = "Sakib";

Curly Braces { }

Curly braces define code blocks. As lesson 1.07 showed, in our first program the outer braces define the class body and the inner braces define the method body. Each opening brace must have a matching closing brace.

Parentheses ( )

Parentheses are part of different Java syntax constructs, such as a method declaration and a method call:

java
public static void main(String[] args)
System.out.println("Hello");

In later lessons, you will also see parentheses used with conditions and expressions. Like braces, parentheses come in pairs, and a missing one causes a compilation error (see Common Mistakes).

Double Quotes and Single Quotes

Double quotes are used for text or String values, and single quotes are used for a single char value:

java
String language = "Java";
char grade = 'A';

Wrong:

java
String language = 'Java';

Correct:

java
String language = "Java";

We will learn about String and char in detail in the data type lesson.

Whitespace

Whitespace means spaces, tabs and new lines. The Java compiler ignores much of the extra whitespace: int age = 30; compiles the same as int age = 30;, but is much more readable.

Whitespace Inside a String Is Different

Here, the spaces inside the quotation marks are part of the output:

java
System.out.println("Hello     Java");

Output:

text
Hello     Java

Indentation and Blank Lines

Indentation makes the structure of nested code visually clear. Lesson 1.07 compared our first program with an unindented copy that compiles but is hard to read. In Java code, four spaces are commonly used for each nested level.

Blank Lines

Blank lines help separate logical sections. For example:

java
public class Main {

    public static void main(String[] args) {
        String courseName = "Java Foundation";
        int durationInWeeks = 8;

        System.out.println(courseName);
        System.out.println(durationInWeeks);
    }
}

Blank lines improve readability, but too many blank lines can unnecessarily spread out the code.

Comments

A comment is explanatory text written for developers. The compiler does not execute comments. Three common types of comments are used in Java:

  1. Single-line comments
  2. Multi-line comments
  3. Javadoc comments

Single-Line Comment

A single-line comment begins with //. Everything after // on that line is part of the comment:

java
// Display the course name
System.out.println("Java Foundation");

Multi-Line Comment

A multi-line comment can be used for explanations or temporary notes spanning multiple lines:

java
/*
 * This program demonstrates
 * basic Java syntax.
 */

Javadoc Comment

A Javadoc comment begins with /** and ends with */:

java
/**
 * Represents a course.
 */
public class Course {
}

In addition to being a comment, Javadoc can be used for documentation generation. We will look at advanced Javadoc tags and documentation practices later when needed.

Good Comments

Comments should provide information that is not already obvious from the code. Poor:

java
// Set age to 30
int age = 30;

The comment simply repeats what the code already says. Meaningful naming removes the need for many unnecessary comments. Better code:

java
int studentAge = 30;

Do Not Use Comments to Hide Bad Naming

Poor:

java
int x = 4990; // Course price

Better:

java
int coursePrice = 4990;

Code should be as readable as possible by itself.

Code Formatting

Formatting keeps the visual structure of code consistent. This program compiles and runs, but it is hard to read and harder to change:

java
public class Main{public static void main(String[]args){String courseName="Java Foundation";System.out.println(courseName);}}

Formatted like the Blank Lines example above, with one statement per line and indentation for each level, it does exactly the same and is much easier to maintain (Practice Exercise 5 asks you to do it).

Formatting Code With IntelliJ IDEA

IntelliJ IDEA can automatically reformat code from the menu:

text
Code
→ Reformat Code

The common shortcut is Ctrl + Alt + L. On the macOS keymap, it is generally Option + Command + L. The shortcut may differ depending on your keymap.

Consistency

Follow the same naming and formatting style throughout a project. Avoid:

java
int student_age;
int CoursePrice;
int totalMarks;

Preferred:

java
int studentAge;
int coursePrice;
int totalMarks;

Consistency makes code reviews and collaboration easier.

A Basic Approach to Reading Compiler Errors

When there is a syntax error, the compiler may provide information about the file, line, and problem. For example:

text
Main.java:4: error: ';' expected

When fixing an error:

  1. Look at the first reported error
  2. Check that line
  3. If necessary, also check the previous line
  4. Fix the error
  5. Compile again

One syntax error can sometimes produce several misleading errors afterward. Therefore, it is usually best to start with the first error.

A Clean Java Program

java
public class CourseInformation {

    static final int COURSE_DURATION_IN_WEEKS = 8;

    public static void main(String[] args) {
        String courseName = "Java and OOP Foundation";
        String courseLanguage = "Bangla";

        System.out.println(courseName);
        System.out.println(courseLanguage);
        System.out.println(COURSE_DURATION_IN_WEEKS);
    }
}

The naming conventions used here are:

  • Class → CourseInformation
  • Constant → COURSE_DURATION_IN_WEEKS
  • Variables → courseName, courseLanguage
  • Method → main

Even if you cannot yet implement every concept used in this syntax, it is important to recognize the naming and formatting patterns.

Common Mistakes

Missing semicolons, quotes and braces and wrong capitalization were shown in lesson 1.07, and the missing-semicolon message in the section on reading compiler errors above. Two more mistakes produce messages that are harder to read.

Missing Parenthesis

Wrong:

java
System.out.println("Hello";

The compiler reached ; while it still expected the closing ) of the call (or a , and another argument):

text
Main.java:4: error: ')' or ',' expected
        System.out.println("Hello";
                                  ^

Correct:

java
System.out.println("Hello");

Invalid Identifier or Keyword as a Name

Wrong:

java
int 1stMark = 80;

The compiler does not say "bad name". Because a name cannot start with a digit, it cannot make sense of the line at all:

text
Main.java:4: error: not a statement
        int 1stMark = 80;
        ^
Main.java:4: error: ';' expected
        int 1stMark = 80;
           ^
2 errors

int class = 10; fails the same way, with three errors. Both are good reasons to read the first error and then look at the line itself. Correct:

java
int firstMark = 80;
int classCount = 10;

Practice Exercise 1: Valid or Invalid?

Solutions: lesson 1.23.

Determine whether each identifier below is valid or invalid:

  1. studentName
  2. 2ndStudent
  3. coursePrice
  4. class
  5. _total
  6. $generatedValue
  7. student name
  8. totalMarks
  9. course-price

If an identifier is valid but conventionally poor, mention that as well.

Practice Exercise 2: Improve the Naming

Improve the following names according to Java conventions:

text
student_name
Studentage
COURSEname
total-price
n
isactive

Assume they represent:

  • Student name
  • Student age
  • Course name
  • Total price
  • Student count
  • Active status

Practice Exercise 3: Match the Convention

Write the appropriate naming style for each element:

  1. Class
  2. Method
  3. Variable
  4. Constant
  5. Package

Possible styles: PascalCase, camelCase, UPPER_SNAKE_CASE, and lowercase.

Practice Exercise 4: Fix the Syntax

Fix the following code:

<!-- error -->
java
public class Main {

    public static void main(String[] args) {
        String course name = "Java Foundation"
        int 1duration = 8;

        system.out.println(course name);
    }
}

Expected output:

text
Java Foundation

Practice Exercise 5: Format the Code

Format the following code so it is readable:

java
public class Main{public static void main(String[]args){String courseName="Java Foundation";System.out.println(courseName);}}

Practice Exercise 6: Improve the Names

Suppose we have:

java
int a = 500;
int b = 3;
int c = a * b;

Here:

  • a = product price
  • b = quantity
  • c = total price

Rewrite the code using meaningful variable names.

Knowledge Check

Question 1

What is Java syntax?

Question 2

What does it mean that Java is case-sensitive?

Question 3

What is a keyword?

Question 4

What is an identifier?

Question 5

Can an identifier start with a number?

Question 6

Can an identifier contain a space or hyphen?

Question 7

What is the common naming convention for classes?

Question 8

What is the common naming convention for variables and methods?

Question 9

What is the common naming convention for constants?

Question 10

What is a semicolon used for?

Question 11

What do curly braces define?

Question 12

How does a single-line comment begin?

Question 13

Why is meaningful naming important?

Question 14

Is indentation required by the compiler?

Question 15

If one syntax error produces many compiler errors, which one should usually be fixed first?

Knowledge Check Answers

Answer 1

Java syntax is the set of grammatical rules and structures used to write Java code.

Answer 2

Java treats uppercase and lowercase letters as different.

Answer 3

A keyword is a reserved word in the Java language with a predefined meaning.

Answer 4

An identifier is a programmer-defined name for a class, method, variable, or another program element.

Answer 5

No. An identifier cannot start with a number.

Answer 6

No. An identifier cannot contain spaces or hyphens.

Answer 7

The common naming convention for classes is PascalCase.

Answer 8

The common naming convention for variables and methods is camelCase.

Answer 9

The common naming convention for constants is UPPER_SNAKE_CASE.

Answer 10

A semicolon indicates the end of a simple Java statement.

Answer 11

Curly braces define the boundaries of classes, methods, and other code blocks.

Answer 12

A single-line comment begins with //.

Answer 13

Meaningful names make the purpose of code and its data easier to understand.

Answer 14

The Java compiler generally does not require indentation, but indentation is important for readable and maintainable code.

Answer 15

Usually, you should fix the first error reported by the compiler first. One syntax error can cause many subsequent errors.

Lesson Summary

  • Syntax is the set of grammatical rules of Java. Breaking them generally causes a compilation error.
  • Java is case-sensitive, so System and system are different identifiers.
  • Keywords are reserved words and cannot be used as identifiers.
  • An identifier cannot start with a number, contain spaces or hyphens, or be a keyword.
  • Classes use PascalCase, methods and variables use camelCase, constants use UPPER_SNAKE_CASE, and packages use lowercase.
  • A valid name and a good name are not the same: names should make the purpose of the code clear.
  • Consistent indentation, whitespace, and formatting make code easier to read. IntelliJ IDEA can reformat code for you.
  • Comments should add information the code cannot show. When reading compiler errors, start with the first one.

Mõtle enne

Tulekul

Kontrollküsimused, mille puhul valid vastuse enne, kui õppetund selle näitab.