Skip to content
CampusEduX

Introduction to Java · Lesson 8 of 150

Java Program Structure

This refers to the standard layout every Java file follows: an optional package statement, optional import statements, a class definition, and inside that class, methods (including the special main method where execution starts).

2 min read

01What is Java Program Structure?

This refers to the standard layout every Java file follows: an optional package statement, optional import statements, a class definition, and inside that class, methods (including the special main method where execution starts).

02Why is it used?

Java enforces this structure so that every program is organized in a predictable way. This makes it easier for any Java developer to read someone else's code and immediately understand where things begin and how they're organized.

03Real-Life Example

Think of a college application form. It always has the same order: personal details section first, then academic details, then signature at the end. Regardless of who fills it out, the structure stays the same, making it easy for anyone to review.

04Syntax

java
package com.example.myapp; // optional import java.util.Scanner; // optional public class StructureDemo { // fields (variables) go here public static void main(String[] args) { // program logic goes here } // other methods go here }

05Example Program

java
package com.example.demo; public class StructureExample { static int counter = 0; // a field public static void main(String[] args) { counter++; System.out.println("Counter value: " + counter); } }

Output:

Counter value: 1

06Key Points to Remember

  • Order matters: package, then imports, then the class.
  • A Java file can have only one public class, and its name must match the file name.
  • The main method signature must always be public static void main(String[] args).

Practice Problems

Try each question yourself first, then check the answer.

1

Order the parts

List the parts of a Java file in the required top-to-bottom order.

Show answer
(optional) package statement -> (optional) import statements -> class definition -> inside the class: fields and methods, including main.
2

Spot the bug

java
import java.util.Scanner; package com.example; public class Demo { }

Why will this not compile?

Show answer
The package statement must come before any import and be the first statement in the file. Here import appears first, which is invalid.
3

File and class names

A file Report.java contains public class Summary { ... }. What is wrong?

Show answer
A public class must have the same name as its file. Either rename the file to Summary.java or rename the class to Report.
4

Write the signature

Write the exact required signature of the program's entry-point method.

Show answer
public static void main(String[] args)