Programming and Java Fundamentals

Java Syntax and Coding Conventions

ReadingPreview

আপনি একটি free preview lesson দেখছেন।

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.

In this lesson, we will learn:

  • What Java syntax is
  • What it means that Java is case-sensitive
  • Keywords and identifiers
  • Identifier naming rules
  • Java naming conventions
  • Semicolons, braces, and parentheses
  • Whitespace and indentation
  • Comments
  • Basic conventions for writing readable Java code

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;

Invalid:

int age 30;

Here, the assignment operator = is missing.

Another invalid example:

int age = 30

Here, the semicolon at the end of the statement is missing.

Correct:

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.

Main
main
MAIN

These are three different identifiers.

Similarly:

int age = 30;
int Age = 40;

age and Age are two different variables.

However, you should avoid creating similar names that differ only by capitalization.

Avoid:

int price = 100;
int Price = 200;

This is valid but confusing.

Another Example of Case Sensitivity

Correct:

System.out.println("Hello");

Incorrect:

system.out.println("Hello");

because:

System

and:

system

are not the same identifier.

Java Keywords

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

You have already seen some keywords:

public
class
static
void
int

Some other common keywords include:

private
protected
boolean
if
else
for
while
return
new
final
interface
extends
implements
try
catch

Keywords cannot be used as programmer-defined identifiers.

Invalid:

int class = 10;

Invalid:

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.

Identifiers are used for:

  • Class names
  • Method names
  • Variable names
  • Parameter names
  • Constant names
  • Package names

Example:

public class Student {

    String studentName;
    int age;
}

The identifiers here are:

Student
studentName
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

Technically valid:

_age
$generatedValue

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

Invalid:

1student
2ndCourse

Correct:

student1
secondCourse

Cannot Contain Spaces

Invalid:

student age

Correct:

studentAge

Cannot Contain Hyphens

Invalid:

course-price

Correct:

coursePrice

Cannot Use a Keyword

Invalid:

class
public
return

Valid identifiers could be:

classCount
publicCourse
returnValue

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.

Technically valid:

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

But the meaning is not clear.

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:

ElementConventionExample
ClassPascalCaseGradeCalculator
MethodcamelCasecalculateTotal()
VariablecamelCasestudentName
ParametercamelCasecoursePrice
ConstantUPPER_SNAKE_CASEMAXIMUM_ATTEMPTS
Packagelowercaseio.liveklass.course

Class Names: PascalCase

Class names are generally written in PascalCase.

Good:

Student
BankAccount
GradeCalculator
CourseEnrollment

Avoid:

student
bank_account
gradecalculator

Class Names Should Be Meaningful

Good:

public class GradeCalculator {
}

Less clear:

public class Data {
}

A class name should give an idea of its responsibility or the concept it represents.

Variables and Methods: camelCase

Variable:

int studentAge;
String courseName;
boolean isAvailable;

Method:

calculateTotal()
displayResult()
createAccount()

In camelCase, the first word begins with a lowercase letter and each following word begins with a capital letter.

studentName
totalPrice
calculateAverage

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

Examples:

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.

Example:

package io.liveklass.foundation;

Avoid:

package Io.LiveKlass.Foundation;

Meaningful Names

Poor:

int x = 80;
int y = 90;
int z = x + y;

Better:

int mathematicsMark = 80;
int englishMark = 90;
int totalMarks = mathematicsMark + englishMark;

The intent of the second version is much easier to understand.

Avoid Unnecessary Abbreviations

Avoid:

int stdCnt;
String crsNm;

Better:

int studentCount;
String courseName;

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

Semicolon ;

Many simple Java statements end with a semicolon.

int age = 30;
String name = "Sakib";
System.out.println(name);

A missing semicolon can cause a compilation error.

Wrong:

int age = 30

Correct:

int age = 30;

One Statement Per Line

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:

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

Curly Braces { }

Curly braces define code blocks.

You have already seen braces in classes and methods:

public class Main {

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

Here:

  • The outer braces define the class body
  • 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.

Method declaration:

public static void main(String[] args)

Method call:

System.out.println("Hello");

In later lessons, you will also see parentheses used with conditions and expressions.

A missing parenthesis can cause a compilation error.

Wrong:

System.out.println("Hello";

Correct:

System.out.println("Hello");

Double Quotes and Single Quotes

Double quotes are used for text or String values:

String language = "Java";

Single quotes are used for a single char value:

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 includes:

  • Spaces
  • Tabs
  • New lines

The Java compiler can ignore much of the extra whitespace.

This code:

int age = 30;

and:

int     age     =     30;

can both compile.

However, the first version is much more readable.

Whitespace Inside a String Is Different

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

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

Output:

Hello     Java

Indentation

Indentation makes the structure of nested code visually clear.

Recommended:

public class Main {

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

Avoid:

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

The compiler can accept the second version, but it is difficult for humans to read.

In Java code, four spaces are commonly used for each nested level.

Blank Lines

Blank lines help separate logical sections.

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:

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

Single-Line Comment

A single-line comment begins with:

//

Example:

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

Everything after // on that line is part of the comment.

Multi-Line Comment

A multi-line comment:

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

It can be used for explanations or temporary notes spanning multiple lines.

Javadoc Comment

A Javadoc comment begins with:

/**

and ends with:

*/

Example:

/**
 * 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.

Better code:

int studentAge = 30;

Meaningful naming removes the need for many unnecessary comments.

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.

Readable:

public class Main {

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

        System.out.println(courseName);
    }
}

Hard to read:

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

Both versions can perform the same task, but the first is easier to maintain.

Formatting Code With IntelliJ IDEA

IntelliJ IDEA can automatically reformat code.

Menu:

Code
→ Reformat Code

Common shortcut:

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.

Common Syntax Errors

Missing Semicolon

Wrong:

int age = 30

Correct:

int age = 30;

Missing Quote

Wrong:

String name = "Sakib;

Correct:

String name = "Sakib";

Missing Parenthesis

Wrong:

System.out.println("Hello";

Correct:

System.out.println("Hello");

Missing Brace

Wrong:

public class Main {

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

Correct:

public class Main {

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

Invalid Identifier

Wrong:

int 1stMark = 80;

Correct:

int firstMark = 80;

Keyword as Identifier

Wrong:

int class = 10;

Correct:

int classCount = 10;

Wrong Capitalization

Wrong:

system.out.println("Hello");

Correct:

System.out.println("Hello");

A Basic Approach to Reading Compiler Errors

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

Example:

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

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.

Important Terms

Syntax

The grammatical rules for writing Java code.

Syntax Error

A compilation error caused by breaking Java syntax rules.

Keyword

A reserved word in the Java language.

Identifier

A programmer-defined name.

PascalCase

A common naming convention for class names.

GradeCalculator

camelCase

A common naming convention for variable and method names.

studentName

UPPER_SNAKE_CASE

A common naming convention for constants.

MAXIMUM_ATTEMPTS

Semicolon

Indicates the end of a simple statement.

Code Block

Code contained inside curly braces { }.

Whitespace

Spaces, tabs, and new lines.

Indentation

Spacing used to visually align nested code.

Comment

Explanatory text for developers that the compiler does not execute.

Code Formatting

The practice of keeping code spacing, indentation, and layout consistent.

Practice Exercise 1: Valid or Invalid?

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:

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
lowercase

Practice Exercise 4: Fix the Syntax

Fix the following code:

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 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

In this lesson, we learned:

  • Syntax defines the rules for writing Java code
  • Java is case-sensitive
  • Keywords are reserved and cannot be used as identifiers
  • An identifier is a programmer-defined name
  • An identifier cannot start with a number
  • An identifier cannot contain spaces or hyphens
  • Class names generally follow PascalCase
  • Variable and method names generally follow camelCase
  • Constants generally follow UPPER_SNAKE_CASE
  • Package names are generally lowercase
  • Meaningful naming makes code more readable
  • Simple statements generally end with a semicolon
  • Curly braces define code blocks
  • Parentheses are part of method declarations and calls
  • Whitespace and indentation improve code readability
  • Single-line, multi-line, and Javadoc comments have different syntax
  • Comments should provide useful context rather than repeat obvious code
  • Consistent formatting improves maintainability and collaboration
  • IntelliJ IDEA's formatter helps keep code style consistent