Java Program Structure – Complete Guide with Examples and Explanation
Learn the complete structure of a Java program, including classes, methods, main function, package declaration, and how to write a well-structured Java program for beginners.
Java Program Structure – Complete Detailed Tutorial
Understanding the structure of a Java program is essential before writing any Java code. Java programs follow a strict structure to ensure readability, maintainability, and proper execution by the JVM.
1. Basic Structure of a Java Program
A typical Java program includes the following components:
- Package Declaration (Optional)
- Import Statements (Optional)
- Class Declaration (Required)
- Main Method (Required)
- Statements / Logic
Diagram of Structure
2. Package Declaration
- Packages are used to group related classes together.
- Declared at the top of the program.
- Syntax:
Example:
3. Import Statements
- Used to import classes from other packages.
- Must be after package declaration and before class declaration.
- Syntax:
Example:
4. Class Declaration
- All Java code must reside inside a class.
- Syntax:
Rules:
- Class name should start with a capital letter (convention).
- File name must match the public class name.
{}braces define the class body.
Example:
5. Main Method
- The entry point of any Java program.
- Syntax:
Explanation of Each Keyword
| KeywordMeaning | |
| public | Accessible by JVM from anywhere |
| static | Can be called without creating object |
| void | Returns nothing |
| main | Standard method name |
| String[] args | Accepts command-line arguments |
Example:
6. Statements / Logic
- The main method contains statements that define the program logic.
- Each statement ends with a semicolon
;. - Java supports expression statements, method calls, and control structures.
Example:
7. Comments in Java
- Comments are used to document code.
- Types:
- Single-line comment:
// Comment here - Multi-line comment:
/* Comment */ - Documentation comment:
/** Comment */
Example:
8. Complete Java Program Example
Explanation:
- Package groups class (optional)
- Import statement allows
Scannerusage - Class
Calculatorcontains the main method - Main method executes logic to calculate sum and difference
9. Rules for Java Program Structure
- Every Java program must have a class.
- File name must match the public class name.
- Main method is mandatory for standalone execution.
- Statements end with a semicolon.
- Java is case-sensitive.
{}braces define blocks.- Comments are optional but recommended.
10. Summary
- Java program starts with main method.
- Package and imports are optional but organize code.
- Class is mandatory and is the container for code.
- Statements inside main method define program behavior.
- Proper structure ensures readability, maintainability, and execution.