Java Syntax and Program Structure

Syntax refers to the set of rules that define how a Java program must be written. Just like grammar rules govern how sentences are formed in a language, Java syntax governs how instructions are written in code. Understanding the syntax and structure of a Java program is essential before writing anything meaningful.

Basic Structure of a Java Program

Every Java program follows this general structure:

// Optional: Package declaration
package mypackage;

// Optional: Import statements
import java.util.Scanner;

// Class definition
public class MyProgram {

    // Main method – entry point
    public static void main(String[] args) {

        // Statements go here
        System.out.println("This is a Java program.");

    }
}

Let's explore each section in detail.

1. Package Declaration

package mypackage;

A package is a way to group related classes together, similar to a folder on a computer. The package declaration is always the first line in a Java file (if used). It is optional but becomes important in larger projects.

2. Import Statements

import java.util.Scanner;

Import statements allow the use of classes from other packages. Java has a large library of built-in classes. If a program needs to use one of them, it must import it first. The import keyword is followed by the full path of the class.

For example, java.util.Scanner is used to read input from the user.

3. Class Definition

public class MyProgram {
    // class body
}

In Java, every program must be enclosed in a class. The class is defined using the class keyword, followed by the class name. The body of the class is enclosed in curly braces { }.

  • Class names should start with a capital letter (by convention).
  • The file name must match the public class name.

4. The main Method

public static void main(String[] args) {
    // statements
}

The main method is the starting point of every Java application. The JVM looks for and executes this method first. It must always be written exactly as shown above — the method signature is fixed and cannot be changed.

5. Statements and Semicolons

Each instruction in Java is called a statement. Every statement must end with a semicolon ;. Forgetting the semicolon is one of the most common beginner errors.

System.out.println("Hello");   // correct
System.out.println("Hello")    // error – missing semicolon

Java Case Sensitivity

Java is a case-sensitive language. This means uppercase and lowercase letters are treated as completely different characters.

int number = 5;
int Number = 10;   // This is a different variable than 'number'

Built-in keywords like System, String, and public must always be written with the correct capitalization.

Comments in Java

Comments are notes written in the code that are ignored by the compiler. They are used to explain what the code is doing, making it easier for others (and future self) to understand.

Single-Line Comment

// This is a single-line comment
System.out.println("Comments are ignored by compiler");

Multi-Line Comment

/*
   This is a multi-line comment.
   It can span multiple lines.
*/
System.out.println("Multi-line comment example");

Documentation Comment (Javadoc)

/**
 * This method prints a greeting message.
 * @param name The name of the person to greet
 */
public void greet(String name) {
    System.out.println("Hello, " + name);
}

Javadoc comments are used to automatically generate documentation for Java code.

Identifiers and Naming Rules

An identifier is the name given to a class, method, variable, or other element in a Java program. Java has strict rules for naming identifiers:

  • Must start with a letter (A–Z or a–z), underscore _, or dollar sign $.
  • Cannot start with a digit (0–9).
  • Cannot use reserved keywords like class, int, void.
  • No spaces are allowed in identifiers.
  • Java identifiers are case-sensitive.
Valid IdentifiersInvalid Identifiers
studentName1student (starts with digit)
_totalmy name (contains space)
$amountclass (reserved keyword)
totalMarkstotal-marks (contains hyphen)

Java Naming Conventions

While not enforced by the compiler, following naming conventions makes code readable and professional:

  • Classes: Start with uppercase letter, use CamelCase. Example: BankAccount, StudentDetails
  • Methods and Variables: Start with lowercase, use camelCase. Example: studentName, calculateTotal()
  • Constants: All uppercase with underscores. Example: MAX_SIZE, PI_VALUE
  • Packages: All lowercase. Example: com.example.project

Java Reserved Keywords

Java has a set of reserved keywords that have special meaning in the language. These cannot be used as identifiers.

abstract  assert    boolean   break     byte
case      catch     char      class     const
continue  default   do        double    else
enum      extends   final     finally   float
for       goto      if        implements import
instanceof int      interface long      native
new       package   private   protected public
return    short     static    strictfp  super
switch    synchronized this   throw     throws
transient try       void      volatile  while

White Space and Formatting

Java ignores extra spaces, tabs, and blank lines. These are called white space. Programmers use white space to format code neatly and improve readability.

// Both of these are identical to the compiler:
System.out.println("Hello");
System   .   out   .   println(   "Hello"   );  // ugly but valid

A Complete Example with All Elements

// Package declaration
package basics;

// Import statement
import java.util.Date;

// Class definition
public class StructureDemo {

    // Main method
    public static void main(String[] args) {

        // Single-line comment
        System.out.println("Learning Java Structure");

        /*
           Multi-line comment:
           This prints the current date
        */
        Date today = new Date();
        System.out.println("Today is: " + today);
    }
}

Summary

  • A Java program consists of package declarations, imports, class definitions, and the main method.
  • Every statement ends with a semicolon ;.
  • Java is case-sensitive — spelling and capitalization must be exact.
  • Comments are ignored by the compiler and are used for code documentation.
  • Identifiers must follow naming rules and should follow naming conventions.
  • Reserved keywords cannot be used as variable or class names.

Leave a Comment

Your email address will not be published. Required fields are marked *