Java Syntax and Coding Conventions
Learn Java's syntax rules, keywords and identifiers, naming conventions, readable formatting and comments, and spot common syntax errors.
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:
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:
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:
int age = 30;
int Age = 40;
However, you should avoid creating similar names that differ only by capitalization. This is valid but confusing:
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:
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:
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.
_ageand$generatedValueare 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.
1studentand2ndCourseare invalid; writestudent1andsecondCourseinstead. - Cannot contain spaces.
student ageis invalid; writestudentAge. - Cannot contain hyphens.
course-priceis invalid; writecoursePrice. - Cannot use a keyword.
class,public, andreturnare invalid, whileclassCount,publicCourse, andreturnValuecould be valid identifiers.
Valid and Invalid Identifiers
| Identifier | Valid? | Note |
|---|---|---|
studentName | Yes | Recommended style |
course2 | Yes | Valid |
_total | Yes | Valid, usually avoid leading _ |
$value | Yes | Valid, uncommon in normal code |
2student | No | Starts with a number |
student name | No | Contains a space |
student-name | No | Contains a hyphen |
class | No | Java 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:
int a = 20;
String n = "Sakib";
Better:
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:
| Element | Convention | Example |
|---|---|---|
| Class | PascalCase | GradeCalculator |
| Method | camelCase | calculateTotal() |
| Variable | camelCase | studentName |
| Parameter | camelCase | coursePrice |
| Constant | UPPER_SNAKE_CASE | MAXIMUM_ATTEMPTS |
| Package | lowercase | com.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:
boolean isActive;
boolean hasPermission;
boolean canEnroll;
boolean paymentCompleted;
Less clear:
boolean flag;
boolean value;
boolean status;
Constants: UPPER_SNAKE_CASE
A common Java convention for constants is UPPER_SNAKE_CASE:
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:
int stdCnt;
String crsNm;
Better:
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:
int age = 30; String name = "Sakib";
However, for readable code, they are generally written on separate lines, one statement per line:
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:
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:
String language = "Java";
char grade = 'A';
Wrong:
String language = 'Java';
Correct:
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:
System.out.println("Hello Java");
Output:
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:
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:
- Single-line comments
- Multi-line comments
- Javadoc comments
Single-Line Comment
A single-line comment begins with //. Everything after // on that line is part of the comment:
// 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:
/*
* This program demonstrates
* basic Java syntax.
*/
Javadoc Comment
A Javadoc comment begins with /** and ends with */:
/**
* 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:
// 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:
int studentAge = 30;
Do Not Use Comments to Hide Bad Naming
Poor:
int x = 4990; // Course price
Better:
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:
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:
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:
int student_age;
int CoursePrice;
int totalMarks;
Preferred:
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:
Main.java:4: error: ';' expected
When fixing an error:
- Look at the first reported error
- Check that line
- If necessary, also check the previous line
- Fix the error
- 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
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:
System.out.println("Hello";
The compiler reached ; while it still expected the closing ) of the call (or a , and another argument):
Main.java:4: error: ')' or ',' expected
System.out.println("Hello";
^
Correct:
System.out.println("Hello");
Invalid Identifier or Keyword as a Name
Wrong:
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:
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:
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:
studentName2ndStudentcoursePriceclass_total$generatedValuestudent nametotalMarkscourse-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:
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:
- Class
- Method
- Variable
- Constant
- Package
Possible styles: PascalCase, camelCase, UPPER_SNAKE_CASE, and lowercase.
Practice Exercise 4: Fix the Syntax
Fix the following code:
<!-- error -->public class Main {
public static void main(String[] args) {
String course name = "Java Foundation"
int 1duration = 8;
system.out.println(course name);
}
}
Expected output:
Java Foundation
Practice Exercise 5: Format the Code
Format the following code so it is readable:
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:
int a = 500;
int b = 3;
int c = a * b;
Here:
a= product priceb= quantityc= 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
Systemandsystemare 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
TulekulKontrollküsimused, mille puhul valid vastuse enne, kui õppetund selle näitab.