ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 1 · Core Java & Modern Java
  4. Volume I
  5. Java Program Structure
Book 1 · Volume I — Java Language Fundamentals & Object-Oriented Programming · Topic 2.1

Java Program Structure

Package, imports, class declaration, main(), statements, expressions and blocks

15 min readStage 1 · Foundations14 interview questions
Prerequisites
1.2 Source-to-Execution Lifecycle
Covers
Package declaration · Imports · Class declaration · main() · Statements · Expressions · Blocks
Related
2.2 Identifiers & Keywords · 4.1 Classes · B1V5 Ch1 Java Modules
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally
  5. 5. APIs / Features / Syntax
  6. 6. Practical Examples
  7. 7. Common Problems & Mistakes
  8. 8. Performance & Production Considerations
  9. 9. Architecture & Design Considerations
  10. 10. Interview Questions & Answers
  11. Key Takeaways

1Concept / Definition

A Java source file has a fixed outer structure: an optional package declaration, then import declarations, then one or more type declarations (classes, interfaces, enums, records). Inside a class, methods contain blocks, blocks contain statements, and statements contain expressions. Execution of an application starts at a main method.

The parts of a typical source file, from package declaration to blocks
Figure 1 — The parts of a typical source file, from package declaration to blocks

2Why It Exists

The fixed layout of a source file is what lets the compiler, the class loader and other developers find things without a central registry. A package declaration gives every type a globally unique name, so com.shop.order.Order and com.billing.Order can coexist in one application, and the directory layout that mirrors the package lets javac locate the source of a referenced type on the source path. The rule that a public top-level type lives in a file of the same name serves the same purpose: given a type name, the tools know exactly which file to open.

Imports exist so that this precision does not cost readability: code says List while the class file still records java.util.List. A single, conventional main method gives every launcher, IDE, build tool and container image one agreed entry point. Inside methods, the hierarchy of blocks, statements and expressions gives the language clear rules for scope, evaluation order and where a value can appear, which is what makes definite-assignment checks and readable compiler errors possible.

3Core Concepts

Package declaration

package com.shop.order; must be the first statement in the file (only comments may come before it). It places the types in a namespace, and the directory structure should mirror it. A file without a package declaration is in the unnamed package, which is acceptable only for scripts and experiments.

Imports

Imports let you use short names instead of fully qualified ones. They are purely a compile-time convenience: an import loads nothing at run time and has no performance cost. java.lang is imported automatically.

FormExampleImports
Single-typeimport java.util.List;One type
Type-on-demandimport java.util.*;All public types in one package
Staticimport static java.lang.Math.max;A static member
Module (Java 25)import module java.sql;All packages exported by a module

Class declaration

A file may declare several top-level types, but at most one may be public, and the file must be named after it. The declaration names the type, its modifiers, its superclass and interfaces, and a body containing fields, constructors, methods and nested types (Chapter 4).

main()

The launcher starts an application by calling a main method. The traditional form is public static void main(String[] args): public so the launcher can reach it, static so no object is needed, String[] for command-line arguments. Java 25 relaxes this (JEP 512): main no longer has to be public or static, and the parameter is optional. The launcher prefers a main with a String[] parameter over one without; if the chosen method is not static, it first creates an instance using the class's no-argument constructor.

How the launcher chooses and calls main, and the four valid forms in Java 25
Figure 2 — How the launcher chooses and calls main, and the four valid forms in Java 25

Figure 2 shows the order. The class is initialised before main is chosen, so its static initialisers run first (Q8), and the JVM exits when the last non-daemon thread ends, not when main returns.

Statements, expressions and blocks

An expression computes a value: count * 2, items.size(), new Order(). A statement is a complete instruction: a declaration, an if, a loop, a return, or an expression statement such as an assignment or method call ending in a semicolon. A block is a group of statements in braces; it forms a scope for the variables declared inside it (2.3).

Blocks contain statements, and statements contain expressions and nested blocks
Figure 3 — Blocks contain statements, and statements contain expressions and nested blocks

4How It Works Internally

From compilation unit to class files

A source file is a compilation unit, and javac turns it into one class file per type, not per file. A nested class Line inside OrderApp becomes OrderApp$Line.class, and a second top-level type in the same file gets its own class file. The package becomes part of the binary name, com/shop/order/OrderApp, and the output directory mirrors it. Imports leave no trace: the constant pool records the fully qualified name of every type and member the code refers to, whichever import form was used.

How the launcher reaches main

Running java -cp app.jar com.shop.order.OrderApp makes the application class loader load the class, link it and run its static initialisers, and only then is main selected and invoked. In source-file mode, java OrderApp.java compiles the file in memory first and needs no separate javac step; since Java 22 the program may span several source files. Other classes are loaded lazily on first use, not because they appear in an import or a field type.

Blocks do not exist in bytecode

Blocks and local scope are compile-time concepts. The compiler maps each local variable to a numbered slot in the method's frame and reuses a slot once a block ends. Expressions become instructions on the frame's operand stack.

For example, a method containing { int a = count * 2; count = a; } followed by { int b = count + 1; return b; } compiles to bytecode in which a and b both live in local slot 1, as javap -c -l shows in its local variable table; count, the parameter, occupies slot 0. Scope violations are therefore caught only by the compiler, never by the JVM.

5APIs / Features / Syntax

6Practical Examples

Example 1 — The traditional structure

The smallest complete layout of a production source file: a package, one import, one public class named after the file and a static main. Compiled and run with java -cp out com.shop.order.OrderApp, it prints Items: 2.

JAVAOrderApp.javatraditional structure
package com.shop.order;

import java.util.List;

public class OrderApp {

    public static void main(String[] args) {
        List<String> items = List.of("pen", "notebook"); // declaration
        int count = items.size();                        // uses an expression
        if (count > 0) {                                  // block begins
            System.out.println("Items: " + count);
        }                                                 // block ends
    }
}

Example 2 — Mini program: one source file with every structural element

Problem. Example 1 shows the minimum. A real file usually also has a static import, a nested type, an anonymous class and sometimes a second, non-public top-level class. This program has all of them, prints an order summary, and is then used to see what javac produces from one file.

JAVAOrderReport.java
package com.shop.order;                              // 1. package
 
import java.math.BigDecimal;                         // 2. imports
import java.util.List;
import static java.math.RoundingMode.HALF_UP;        //    static import
 
public class OrderReport {                           // 3. public type
    record Line(String sku, int qty, BigDecimal price) {   // OrderReport$Line
        BigDecimal total() { return price.multiply(BigDecimal.valueOf(qty)); }
    }
 
    public static void main(String[] args) {         // 4. entry point
        List<Line> lines = List.of(
                new Line("pen", 3, new BigDecimal("1.20")),
                new Line("notebook", 2, new BigDecimal("4.50")));
        BigDecimal sum = BigDecimal.ZERO;            // statement: declaration
        for (Line l : lines) {                       // block: the loop body
            BigDecimal t = l.total();                // expression: method call
            sum = sum.add(t);                        // expression statement
            System.out.printf("%-9s %d x %s = %s%n",
                    l.sku(), l.qty(), l.price(), t);
        }
        BigDecimal net = Discounts.apply(sum);
        System.out.println("total " + sum + ", after discount " + net);
        Runnable done = new Runnable() {             // OrderReport$1
            public void run() {
                System.out.println("nested: " + Line.class.getName());
            }
        };
        done.run();
    }
}
 
class Discounts {                                    // second top-level type
    static BigDecimal apply(BigDecimal amount) {
        boolean big = amount.compareTo(BigDecimal.TEN) >= 0;
        BigDecimal rate = big ? new BigDecimal("0.95") : BigDecimal.ONE;
        return amount.multiply(rate).setScale(2, HALF_UP);
    }
}
TERMINAL
$ javac -d out OrderReport.java
$ find out -name '*.class' | sort
out/com/shop/order/Discounts.class
out/com/shop/order/OrderReport$1.class
out/com/shop/order/OrderReport$Line.class
out/com/shop/order/OrderReport.class
$ java -cp out com.shop.order.OrderReport
OUTPUT
pen       3 x 1.20 = 3.60
notebook  2 x 4.50 = 9.00
total 12.60, after discount 11.97
nested: com.shop.order.OrderReport$Line

Why it behaves this way. javac writes one class file per type, not per source file (Figure 4). The nested record becomes OrderReport$Line, the anonymous Runnable becomes OrderReport$1, and Discounts gets its own file even though it is declared in OrderReport.java. -d out puts every file under out/com/shop/order/ because the package is part of the binary name, as the last output line shows. The imports leave no trace: the class files name java.math.BigDecimal in full. Only OrderReport may be public, because the file is named after it.

One source file, four class files: one per type, named by package and nesting
Figure 4 — One source file, four class files: one per type, named by package and nesting

Example 3 — A Java 25 compact source file

JAVAA Java 25 script-style program
// report.java — Java 25 compact source file, run with: java report.java
import module java.net.http;

void main() {
    var client = HttpClient.newHttpClient();
    IO.println("HTTP client ready: " + client.version());
}

Run with java report.java on Java 25, it prints HTTP client ready: HTTP_2. The file declares no class: the compiler wraps main in an implicitly declared class, and import module java.net.http makes HttpClient visible. The class has no name other code can use, so the file is a program, never a library.

Example 4 — An import clash and its one-line fix

Problem. Two type-on-demand imports both supply a type called List: java.util.List and the AWT widget java.awt.List. Code that worked with java.util.* alone stops compiling as soon as someone adds java.awt.* for an unrelated class such as Point.

JAVAImportClash.java
import java.awt.*;
import java.util.*;
import java.util.List;                     // the fix: a single-type import wins
 
public class ImportClash {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>(List.of("pen", "ink"));
        Collections.sort(names);
        System.out.println(names + " " + names.getClass().getName());
        System.out.println("awt List is " + java.awt.List.class.getName());
        Point origin = new Point(0, 0);    // java.awt still imported on demand
        System.out.println("origin " + origin.x + "," + origin.y);
    }
}

Without the third import, javac rejects the file (src/compile-errors/ImportClash.java in the kit):

TERMINAL
$ javac ImportClash.java
ImportClash.java:6: error: reference to List is ambiguous
        List<String> names = new ArrayList<>(List.of("pen", "ink"));
        ^
  both interface java.util.List in java.util and class java.awt.List
  in java.awt match
# ... the same error again for List.of on the same line
2 errors

Output of the fixed version:

OUTPUT
[ink, pen] java.util.ArrayList
awt List is java.awt.List
origin 0,0

Why it behaves this way. Two on-demand imports that supply the same simple name are an ambiguity; there is no "first import wins". A single-type import always takes precedence, so import java.util.List; resolves the clash while Point still comes from java.awt.*. import module behaves like on-demand imports of every exported package, so a library upgrade that adds a class with a common name can break code that never changed.

Example 5 — Blocks share local variable slots

Problem. Section 4 says that blocks exist only in the source and that a slot is reused once its block ends. javap shows it.

JAVAScopeSlots.java
public class ScopeSlots {
    static int twice(int count) {
        { int a = count * 2; count = a; }
        { int b = count + 1; return b; }
    }
 
    public static void main(String[] args) {
        System.out.println(twice(20));
    }
}
TERMINALjavap excerpt
$ javac -g ScopeSlots.java
$ javap -c -l ScopeSlots
  static int twice(int);
    Code:
       0: iload_0
       1: iconst_2
       2: imul
       3: istore_1
       4: iload_1
       5: istore_0
       6: iload_0
       7: iconst_1
       8: iadd
       9: istore_1
      10: iload_1
      11: ireturn
    LocalVariableTable:
      Start  Length  Slot  Name   Signature
          4       2     1     a   I
         10       2     1     b   I
          0      12     0 count   I

Why it behaves this way. The method is static, so the parameter count takes slot 0. a lives in slot 1 from bytecode offset 4 for 2 bytes, and b reuses slot 1 from offset 10: the two names never exist at the same time. No instruction opens or closes a block; only the Start and Length columns, written with -g for debuggers, record the scope. The program prints 41.

7Common Problems & Mistakes

MistakeWhy it hurtsFix
File name does not match the public class nameCompile error: "class OrderApp is public, should be declared in a file named OrderApp.java"Name the file after its public type; one top-level type per file is the usual rule
Package declaration does not match the directoryThe class compiles, but it is looked up by its package path, so the launcher or a class loader cannot find it: ClassNotFoundException or "Could not find or load main class"Mirror the package in the directory tree and let the build tool own the layout
Wildcard or module imports that clash on a simple name, such as java.util.List and java.awt.List"reference to List is ambiguous", sometimes only after a library upgrade adds a classAdd a single-type import for the clashing name (Example 4)
Compact source files for production servicesThe implicit class has no usable name, no package and no place for tests or other classesKeep them for scripts, teaching and small tools; services keep packages and a classic main
Real code in the unnamed packageNo class in a named package can import a type from the unnamed package, so the code cannot be reusedGive every class a package from the first commit
Starting a class by its simple name: java -cp app.jar OrderAppThe launcher needs the binary name and reports "Could not find or load main class OrderApp"Use com.shop.order.OrderApp, or a Main-Class entry in the JAR manifest
Heavy work in the static initialisers of the main classIt runs before main on every start; an exception becomes ExceptionInInitializerError before logging is configuredKeep the main class thin and initialise lazily (Q8)

8Performance & Production Considerations

Program structure has almost no direct run-time cost. Imports are free, and the number of classes declared in a file does not matter to the JVM. What does matter at startup is how much work happens before and inside main: static initialisers of the main class run before main is called, and every class touched during startup is loaded, verified and initialised. Keep main thin, move heavy initialisation behind lazy paths, and measure startup with -Xlog:class+load or JFR rather than guessing.

In production, services rarely start from a bare class name. An executable JAR names its entry point in the Main-Class manifest attribute, and Spring Boot's launcher reads its own Start-Class entry before calling your main. For faster starts, Java 25 can record an AOT cache in a training run with -XX:AOTCacheOutput and reuse it with -XX:AOTCache, so loaded and linked classes are ready immediately. Source-file mode recompiles on every launch, adding hundreds of milliseconds, which is acceptable for scripts and admin tools but not for a service restarted by Kubernetes.

9Architecture & Design Considerations

Package structure is the first, and cheapest, architecture decision in a Java codebase. Packaging by feature, such as com.shop.order and com.shop.payment, keeps related classes together and lets package-private visibility hide implementation details; packaging by layer, such as controller, service and repository, forces most types to be public and spreads one feature across the tree. Most teams that start by layer drift towards feature packages with layers inside them.

Treat main as the composition root: the one place that reads configuration and wires objects together, whether by hand or by starting a framework such as Spring Boot. Business logic should not live in it. As a codebase grows, enforce the intended package dependencies with ArchUnit tests or with module descriptors (B1V5 Ch1), which make an exported package an explicit API decision instead of an accident of the public keyword.

10Interview Questions & Answers

Q1L1 · BasicConcept

What is the order of elements in a Java source file?

The order is fixed: an optional package declaration first, then any import declarations, then one or more type declarations such as classes, interfaces, enums and records. Only comments may appear before the package line; package annotations belong in package-info.java. Within that layout, at most one top-level type may be public, and the file must then be named after it, so OrderApp lives in OrderApp.java. The directory should mirror the package, com/shop/order. Getting the order wrong is a compile error, while a package that does not match the folder compiles but fails at run time with ClassNotFoundException or NoClassDefFoundError when the class is looked up by its expected name.

Q2L2 · IntermediateConcept

What is the difference between a statement and an expression?

An expression is evaluated to produce a value, while a statement is a complete instruction that is executed for its effect. count * 2, items.size() and new Order() are expressions; a local variable declaration, an if, a loop, a return or a throw are statements. The two meet in expression statements: an assignment, increment, method call or object creation becomes a statement when followed by a semicolon, but a bare count * 2; does not compile. The distinction matters in practice because switch can be either: a switch expression yields a value and must be exhaustive, whereas a switch statement only selects code to run.

Q3L3 · Senior EngineerInternals

Why is main traditionally public and static, and what changed in Java 25?

Traditionally main is public so that the launcher, which lives outside the class and its package, can call it, and static so that it can be called before any object exists; String[] carries the command-line arguments. Java 25 finalised compact source files and instance main methods through JEP 512. main no longer has to be public or static, and the parameter is optional, so void main() is valid. The launcher prefers a main that takes String[]; if the selected method is an instance method, it first creates an object through the class's no-argument constructor. Production services usually keep the classic form, which every tool and framework understands.

Q4L3 · Senior EngineerTricky

Do wildcard imports affect performance or class loading?

No. Imports are resolved entirely by the compiler: the class file stores fully qualified names in its constant pool whichever import style was used, so the bytecode for import java.util.* and import java.util.List is identical. Nothing is loaded because it was imported; a class is loaded lazily the first time running code actually uses it. The real costs of wildcard imports are maintenance ones. They hide which types a file depends on, and they can turn into compile errors when a later library version adds a class with a clashing simple name, as with java.util.List and java.awt.List. That is why most style guides and IDE settings prefer single-type imports.

Q5L1 · BasicConcept

What is the unnamed package, and when is it acceptable to use it?

A source file without a package declaration puts its types in the unnamed package. Such types cannot be imported by any class in a named package, so they cannot be reused by the rest of a codebase. It is acceptable for single-file scripts, experiments and compact source files, whose implicitly declared class always lives there; everything that is built, tested and deployed belongs in a named package.

Q6L2 · IntermediateCode

What does this program print?

JAVANamesQuiz.java
package com.shop.order;
 
public class NamesQuiz {
    record Line(String sku) {}
 
    public static void main(String[] args) {
        Class<?> c = Line.class;
        System.out.println(c.getName());
        System.out.println(c.getSimpleName());
        System.out.println(c.getPackageName());
        System.out.println(new Object() {}.getClass().getName());
    }
}

It prints com.shop.order.NamesQuiz$Line, Line, com.shop.order, com.shop.order.NamesQuiz$1. getName() returns the binary name, which includes the package and uses $ for nesting, the same name as the class file NamesQuiz$Line.class. getSimpleName() is the name as written in the source, and the anonymous class, which has no source name, is numbered in order of appearance: NamesQuiz$1. Binary names are what Class.forName, stack traces and the launcher use.

Q7L2 · IntermediateTricky

A source file declares two top-level classes, and both have a main method. Which one runs?

Whichever the command names. Each top-level class has its own class file, so java -cp out Second runs Second.main and java -cp out First runs First.main; any class with a valid main can be an entry point. In source-file mode, java App.java compiles the file and runs the first top-level class declared in it, so the order of declarations matters there. For a JAR started with -jar, the Main-Class manifest entry decides.

Q8L3 · Senior EngineerCode

What does this program print?

JAVAStartOrder.java
public class StartOrder {
    static { System.out.println("static block"); }
    static final String NAME = name();
 
    static String name() {
        System.out.println("field initialiser");
        return "app";
    }
 
    public static void main(String[] args) {
        System.out.println("main " + NAME);
    }
}

It prints static block, field initialiser, main app. The launcher initialises the class before it calls main, and initialisation runs the static initialisers and static field initialisers in the order they appear in the source. NAME is not a compile-time constant, because its value comes from a method call, so it is assigned during initialisation, after the static block. Everything in this phase happens before the first line of main, which is why heavy static initialisation slows every start and why its failures appear as ExceptionInInitializerError.

Q9L3 · Senior EngineerScenario

After a refactoring, a service fails at start with "Error: Could not find or load main class OrderApp". The JAR builds without errors. What do you check?

The launcher needs the binary name, so check that the start command or the Main-Class manifest entry says com.shop.order.OrderApp, not a simple name or the old package. Then list the JAR with jar tf app.jar and confirm that the class file is at com/shop/order/OrderApp.class; a package declaration that does not match the directory compiles but puts the class where nobody looks. For Spring Boot, check Start-Class too. The "Caused by: java.lang.ClassNotFoundException" line gives the exact name that was searched for.

Q10L3 · Senior EngineerInternals

How many class files does javac produce for one source file, and which constructs produce none?

One per type: every top-level, nested, local and anonymous class or record gets its own file, named Outer$Nested, Outer$1Local and Outer$1 (Example 2 produces four from one file). Imports, package declarations, blocks and comments produce nothing; their effect is visible only in the full names recorded in the constant pool. Lambdas produce no class file either: javac compiles the body into a private method and an invokedynamic call, and the JVM creates a hidden class at run time.

Q11L4 · Technical ArchitectDesign

You are starting a new service that will grow to about 200 classes. How do you structure its packages?

Package by feature: com.shop.order, com.shop.payment, com.shop.catalog, each with its own web, domain and persistence classes inside, so that most types can stay package-private and each package has a small public surface. Keep a thin app package for main and configuration, the composition root. Write ArchUnit tests for the allowed dependencies between packages from the first week, and consider a module-info.java once the public API of each package is clear.

Q12L4 · Technical ArchitectTrade-off

Single-type imports, wildcard imports or module imports: which would you set as the team standard?

For production code, single-type imports: every dependency of a file is visible in its header, a library upgrade cannot introduce an ambiguity, and IDEs maintain them automatically, so the extra lines cost nothing. Wildcard imports save lines but hide dependencies and can break when a package gains a class with a common name; module imports suit scripts and teaching. None of them affects performance, so the decision is about readability and stability, enforced by the formatter, not by review.

Q13L5 · Solution ArchitectDesign

A 3,000-class monolith is packaged by layer (controller, service, repository) and every class is public. How would you move it towards clear module boundaries without a rewrite?

First make the target visible: map the business capabilities and measure the current dependencies between classes with a tool such as jdeps or ArchUnit. Then move one capability at a time into a feature package, reducing visibility to package-private wherever nothing outside uses a class, and add an ArchUnit rule for each boundary so that it cannot regress.

Once a few features have stable public APIs, turn them into Maven or Gradle modules, or JPMS modules with exports only for the API packages, so the compiler enforces the boundaries. Track the number of public classes and cross-feature dependencies; this is also the preparation for extracting services later, if that is ever needed.

Q14L5 · Solution ArchitectTrade-off

Should an organisation write its operational scripts as Java 25 compact source files instead of shell or Python?

It is a reasonable default for teams whose main skill is Java: a compact source file runs with java script.java, needs no build, uses the same JDK the services already ship, and gives typed access to the JDK libraries. The costs are compilation on every launch, no third-party libraries without a class path, and a poor fit for glue between command-line tools, where shell remains simpler. A sensible policy is Java for scripts that call APIs or contain logic, shell for short command pipelines, and a proper project as soon as a script needs tests or dependencies.

Test your knowledge on this topic →Flashcards from this topic's 14 questions, filtered by level and type.

Key Takeaways

  • Package, imports, types — in that order; one public top-level type per file, named after the file.
  • Imports are compile-time only.
  • Blocks contain statements; statements contain expressions.
  • Java 25 allows compact source files, instance main methods and module imports for small programs.
Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.