Java Tutorial 0/145 lessons ~6 min read Lesson 8

    Java Syntax

    java syntax semicolon curly braces identifiers keywords comments naming conventions camelCase PascalCase main method case sensitive

    Course progress0%
    Focus
    22 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Every programming language has a set of rules that define how code should be written. These rules are called syntax.

    Think of syntax as the grammar of a programming language.

    Just as English sentences must follow grammatical rules to make sense, Java programs must follow Java syntax rules to compile and run successfully.

    Even a small mistake—such as a missing semicolon or incorrect capitalization—can cause compilation errors.

    Understanding Java syntax is the first step toward writing clean, readable, and professional Java code.

    In this lesson, you'll learn:

    • Basic Java program structure
    • Java statements
    • Blocks
    • Comments
    • Case sensitivity
    • Identifiers
    • Keywords
    • Whitespace
    • Semicolons
    • Curly braces
    • Code formatting
    • Naming conventions
    • Real-world examples
    • Best practices
    • Common mistakes
    • Hands-on exercises
    • Professional interview questions

    By the end of this lesson, you'll be able to read and write basic Java programs confidently.

    Your First Java Program

    Let's begin with a simple Java program.

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

    Output:

    Hello, Java!

    Although this program is small, it contains several important syntax elements.

    Let's understand each one.

    Understanding the Program

    Class Declaration

    java
    public class Main

    Every Java application is built using classes.

    Here:

    • public is an access modifier.
    • class is a Java keyword.
    • Main is the class name.

    A class acts as a blueprint for creating objects.

    Main Method

    java
    public static void main(String[] args)

    This is the entry point of every Java application.

    When you run a Java program, the JVM starts execution from the main() method.

    We'll study methods in detail later in this course.

    Printing Output

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

    This statement prints text to the console.

    • System is a predefined Java class.
    • out represents the standard output stream.
    • println() prints text and moves to the next line.

    Java Statements

    A statement is a complete instruction.

    Example:

    java
    int age = 25;

    Another example:

    java
    System.out.println(age);

    Each statement tells the compiler to perform a specific task.

    Semicolons (`;`)

    Almost every Java statement ends with a semicolon.

    Example:

    java
    int salary = 50000;

    Incorrect:

    java
    int salary = 50000

    Output:

    Compilation Error

    The semicolon tells the compiler where one statement ends and the next begins.

    Curly Braces (``)

    Curly braces define a block of code.

    Example:

    java
    if (true) {
    System.out.println("Welcome");
    }

    Braces group related statements together.

    You'll use them in:

    • Classes
    • Methods
    • Loops
    • Conditional statements

    Java is Case-Sensitive

    Java treats uppercase and lowercase letters as different characters.

    Example:

    java
    int age = 25;

    This is different from:

    java
    int Age = 25;

    And different from:

    java
    int AGE = 25;

    All three are separate variables.

    Keywords

    Keywords are reserved words that have predefined meanings in Java.

    Examples include:

    class
    public
    private
    static
    void
    if
    else
    for
    while
    return
    new

    You cannot use keywords as variable or class names.

    Incorrect:

    java
    int class = 10;

    This causes a compilation error.

    Identifiers

    Identifiers are names given to:

    • Variables
    • Methods
    • Classes
    • Objects
    • Packages

    Example:

    java
    String studentName;

    Here, studentName is an identifier.

    Rules for Identifiers

    Identifiers:

    • Can contain letters, digits, _, and $.
    • Cannot begin with a digit.
    • Cannot contain spaces.
    • Cannot be Java keywords.

    Valid:

    studentName
    employeeId
    totalAmount

    Invalid:

    2name
    employee name
    class

    Whitespace

    Java ignores extra spaces, tabs, and blank lines.

    Example:

    java
    int age = 25;

    and

    java
    int age = 25;

    Both compile successfully.

    However, proper formatting greatly improves readability.

    Comments

    Comments help explain code.

    The compiler ignores comments.

    Single-Line Comment

    java
    // This is a comment

    Multi-Line Comment

    java
    /*
    This
    is
    a
    multi-line
    comment.
    */

    Documentation Comment

    java
    /**
    * Calculates employee salary.
    */

    Documentation comments are used by tools that generate API documentation.

    Java Naming Conventions

    Professional developers follow naming conventions to improve readability.

    Class Names

    Use PascalCase.

    Good:

    Employee
    StudentManager
    BankAccount

    Variable Names

    Use camelCase.

    Good:

    firstName
    totalPrice
    studentAge

    Method Names

    Also use camelCase.

    Examples:

    calculateSalary()
    sendEmail()
    printInvoice()

    Constant Names

    Use uppercase with underscores.

    Example:

    MAX_USERS
    DEFAULT_TIMEOUT

    Code Formatting

    Readable code is easier to understand and maintain.

    Good:

    java
    if (marks >= 35) {
    System.out.println("Pass");
    }

    Poor:

    java
    if(marks>=35){System.out.println("Pass");}

    Although both work, the first version is much easier to read.

    Real-World Example

    Imagine you're working with a team of 50 developers.

    Everyone follows the same naming conventions and formatting style.

    Benefits include:

    • Easier code reviews
    • Faster debugging
    • Better collaboration
    • Reduced misunderstandings

    Clean code is just as important as working code.

    Common Compilation Errors

    Missing Semicolon

    java
    int age = 20

    Incorrect Capitalization

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

    Correct:

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

    Missing Curly Brace

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

    The compiler reports an error because the closing braces are missing.

    Invalid Identifier

    java
    int 2salary = 1000;

    Variable names cannot begin with numbers.

    Best Practices

    Use Meaningful Names

    Instead of:

    java
    int x;

    Use:

    java
    int employeeSalary;

    Descriptive names make the code self-explanatory.

    Keep Formatting Consistent

    Indent your code properly.

    Most IDEs can automatically format Java code.

    Write Comments Wisely

    Comment why something is done rather than repeating what the code already says.

    Good comments explain intent.

    Keep Methods Small

    As you begin writing methods, aim for small, focused methods that perform one task well.

    Let the IDE Help You

    Modern IDEs highlight syntax errors as you type and can suggest fixes.

    Use these features to learn and write cleaner code.

    Common Mistakes

    Forgetting Semicolons

    One of the most common beginner errors.

    Using Reserved Keywords as Identifiers

    Keywords such as class or return cannot be used as variable names.

    Ignoring Case Sensitivity

    main, Main, and MAIN are different identifiers.

    Poor Naming

    Avoid names like:

    a
    x
    temp

    Prefer descriptive names.

    Inconsistent Formatting

    Poor formatting makes code harder to understand and maintain.

    Hands-on Exercise

    Complete the following tasks:

    1. Write a Java program that prints your name.
    2. Create a class named Student.
    3. Declare three variables using proper naming conventions.
    4. Add single-line, multi-line, and documentation comments.
    5. Intentionally remove a semicolon and observe the compiler error.
    6. Try using a Java keyword as a variable name and see the resulting error.
    7. Format your code using your IDE's auto-format feature.

    These exercises will help you become comfortable with Java syntax and compiler feedback.

    Summary

    Java syntax provides the rules that every Java program must follow.

    Understanding statements, semicolons, braces, comments, identifiers, keywords, and naming conventions is essential for writing clean, readable, and error-free code.

    Strong syntax skills form the foundation for learning variables, control statements, object-oriented programming, and advanced Java concepts.

    Key Takeaways

    • Java is a case-sensitive programming language.
    • Every Java program starts execution from the main() method.
    • Most statements end with a semicolon.
    • Curly braces define blocks of code.
    • Identifiers must follow Java naming rules.
    • Keywords are reserved and cannot be used as identifiers.
    • Comments improve code readability and documentation.
    • Consistent formatting and naming conventions lead to professional-quality code.

    Professional Interview Questions

    1Why is Java case-sensitive?

    Professional Answer

    Java treats uppercase and lowercase letters as different characters. This allows identifiers such as age, Age, and AGE to represent different variables or methods. Case sensitivity helps avoid ambiguity and ensures consistent program behavior.

    Follow-up Questions

    • Is Main the same as main?
    • Why is System written with an uppercase S?

    Interview Tip: Use simple examples like age and Age to explain the concept clearly.

    2What is the purpose of the main() method?

    Professional Answer

    The main() method is the entry point of a Java application. When the JVM starts a Java program, it looks for the public static void main(String[] args) method and begins execution from there.

    Follow-up Questions

    • Why is main() declared as static?
    • Can a Java program have multiple methods named main()?

    Interview Tip: Remember the exact signature of the standard main() method, as interviewers often ask for it.

    3What are identifiers in Java?

    Professional Answer

    Identifiers are user-defined names assigned to classes, methods, variables, packages, and objects. They must follow Java naming rules, such as not starting with a digit and not using reserved keywords.

    Follow-up Questions

    • Can an identifier contain underscores?
    • Can an identifier start with $?

    Interview Tip: Mention both the naming rules and recommended naming conventions to show a professional understanding.

    Ready to mark this lesson complete?Track your journey across the entire course.