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:
// 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 classA 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.
// 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
.javaextension. For example,HelloWorldmust be inHelloWorld.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 ofStringobjects.args: The parameter name (can be renamed, butargsis 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:
- Write: Create a
.javafile (e.g.,HelloWorld.java) containing the source code. - 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
.classfile (e.g.,HelloWorld.class).
- Execute: Run the program using the Java interpreter (
java HelloWorld):- The JVM reads the
.classfile. - Translates bytecode into native machine instructions.
- Executes the instructions.
- The JVM reads the
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.javaclass MyClass { public static void main(String[] args) { System.out.println("This works!"); } }The file can be named
MyClass.javaor something else.Command-Line Arguments (
args): Pass information to the program at runtime.javapublic class Greeter { public static void main(String[] args) { System.out.println("Hello, " + args[0] + "!"); } }Run with
java Greeter Aliceto output:Hello, Alice!print()vs.println():System.out.print()does not add a new line, whileprintln()does.
Summary
| Component | Example | Purpose |
|---|---|---|
| Class | public class MyApp | A blueprint for objects. The basic unit of a Java program. |
| Main Method | public static void main(...) | The mandatory entry point for the JVM. |
| Statement | System.out.println(...); | A single executable command. |
| Block | { ... } | A group of zero or more statements. |
| Comment | // Explanation | Text 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).
