Skip to content

2.1. Basic Program Structure

Writing Your First Java Program

Let's start with the classic example to understand the structure of a basic Java program:

java
// 1. Class Declaration
public class HelloWorld {

  // 2. Main Method Declaration
  public static void main(String[] args) {

    // 3. Statement
    System.out.println("Hello, World!");
  }
}
// 4. End of class

A Java program consists of one or more classes. Among these, one class must contain the main method, which serves as the entry point for the application.

Key Components of a Java Program

Comments

Comments are used to explain code for human readers. They are ignored by the Java compiler.

java
// Single-line comment

/*
Multi-line comment
*/

/**
 * Documentation comment
 */

Class Declaration

  • Concept: Java is an object-oriented language. Everything resides inside a class, which acts as a blueprint for creating objects.
  • Syntax: public class ClassName { ... }
    • public: An access modifier indicating the class is accessible from anywhere.
    • class: The keyword to declare a class.
    • HelloWorld: The class name, which is an identifier you choose.
  • Rules for Class Names:
    • Use CamelCase (capitalize the first letter of each word).
    • Start with a letter, underscore _, or dollar sign $.
    • Avoid Java keywords (e.g., class, public, static).
  • Important Rule: The filename must exactly match the public class name (case-sensitive) and have a .java extension. For example, HelloWorld must be in HelloWorld.java.

The Main Method

  • Purpose: The entry point of any standalone Java application. The JVM starts execution from this method.
  • Breakdown:
    • public: Makes the method accessible from anywhere.
    • static: Indicates the method belongs to the class, not an instance.
    • void: Specifies the method does not return a value.
    • main: The fixed name of the method.
    • (String[] args): The parameter list:
    • String[]: An array of String objects.
    • args: The parameter name (can be renamed, but args is conventional).
    • Used to accept command-line arguments.

The Method Body

  • Defined by curly braces { }. All code inside belongs to the method.
  • Indentation: While not required, proper indentation improves readability and is a best practice.

Statement

  • Purpose: Executes an action, such as printing text to the console.
  • Breakdown:
    • System: A predefined class providing system-related functionality.
    • out: A static member representing the standard output stream.
    • println(): A method that prints text followed by a new line.
    • "Hello, World!": A string literal enclosed in double quotes.
  • Semicolon (;): Marks the end of a statement. Omitting it causes a syntax error.

Compilation and Execution Process

Understanding the behind-the-scenes process:

  1. Write: Create a .java file (e.g., HelloWorld.java) containing the source code.
  2. Compile: Use the Java compiler (javac HelloWorld.java) to:
    • Check for syntax errors.
    • Convert the source code into bytecode (platform-independent intermediate language).
    • Save the bytecode in a .class file (e.g., HelloWorld.class).
  3. Execute: Run the program using the Java interpreter (java HelloWorld):
    • The JVM reads the .class file.
    • Translates bytecode into native machine instructions.
    • Executes the instructions.

This "Write Once, Run Anywhere" process ensures Java's platform independence.

Variations

  • Without public: A class doesn't need to be public. If no public class exists, the filename can differ from the class name.

    java
    class MyClass {
      public static void main(String[] args) {
        System.out.println("This works!");
      }
    }

    The file can be named MyClass.java or something else.

  • Command-Line Arguments (args): Pass information to the program at runtime.

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

    Run with java Greeter Alice to output: Hello, Alice!

  • print() vs. println(): System.out.print() does not add a new line, while println() does.

Summary

ComponentExamplePurpose
Classpublic class MyAppA blueprint for objects. The basic unit of a Java program.
Main Methodpublic static void main(...)The mandatory entry point for the JVM.
StatementSystem.out.println(...);A single executable command.
Block{ ... }A group of zero or more statements.
Comment// ExplanationText ignored by the compiler, for documentation.
Semicolon;Marks the end of a statement.

Golden Rule: Every Java application must have at least one class containing a main method with the exact signature: public static void main(String[] args).