LearnContact
Lesson 650 min read

Java Program Structure

Understand the complete structure of a Java program, including packages, imports, classes, fields, constructors, methods, the main method, statements, blocks, comments, and execution flow.

Introduction

Every Java program follows a structure. A small program may contain only a class and a main method, while a large application may contain packages, imports, multiple classes, fields, constructors, methods, interfaces, annotations, and many source files.

Understanding program structure helps you know where code belongs, which parts define the application, which parts execute instructions, and how Java organizes source code.

In the previous lesson, you created your first Java program. You already used a class, the main method, a statement, braces, and a source file. In this lesson, you will examine these parts in detail and understand how they fit together.

Java Program Structure
JAVA SOURCE FILE

├── Package Declaration
│
├── Import Statements
│
└── Type Declaration
    │
    └── Class
        │
        ├── Fields
        ├── Constructors
        ├── Methods
        └── Nested Types
What You Will Learn
  • The basic structure of a Java source file.
  • The role of package declarations.
  • The role of import statements.
  • How classes are declared.
  • What a class body contains.
  • What class members are.
  • The difference between fields and local variables.
  • The basic purpose of constructors.
  • The basic purpose of methods.
  • The difference between static and instance members.
  • The detailed structure of the main method.
  • What statements and expressions are.
  • How code blocks work.
  • How nested blocks work.
  • Where local variables are declared.
  • Where comments can appear.
  • What annotations look like.
  • The normal order of elements in a source file.
  • How multiple classes can exist in one file.
  • Why only one public top-level class is normally allowed per file.
  • Why the filename must match the public class name.
  • Why a class does not always need a main method.
  • How Java program execution begins.
  • The difference between declaration order and execution order.
  • How whitespace and indentation affect readability.
  • How Java files are organized in real projects.
  • Common structural mistakes and how to fix them.

Basic Java Program Structure

The smallest traditional Java application usually contains a class and a main method.

Basic Structure
public class Main {

    public static void main(String[] args) {

        System.out.println("Hello, Java!");

    }

}
Structure
SOURCE FILE

└── CLASS
    │
    └── main METHOD
        │
        └── STATEMENT

This simple structure is enough to create a complete executable Java application.

Complete Java Program Example

A more complete Java source file can contain a package declaration, imports, fields, a constructor, methods, and the main method.

Student.java
package com.programinds.app;

import java.time.LocalDate;

public class Student {

    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void displayDetails() {
        System.out.println("Name: " + name);
        System.out.println("Age: " + age);
    }

    public static void main(String[] args) {

        Student student = new Student("Alex", 21);

        student.displayDetails();

        System.out.println("Date: " + LocalDate.now());
    }

}
Complete Structure
package com.programinds.app;
        │
        └── PACKAGE DECLARATION


import java.time.LocalDate;
        │
        └── IMPORT STATEMENT


public class Student {
        │
        └── CLASS DECLARATION


    private String name;
    private int age;
        │
        └── FIELDS


    public Student(...) {
    }
        │
        └── CONSTRUCTOR


    public void displayDetails() {
    }
        │
        └── METHOD


    public static void main(String[] args) {
    }
        │
        └── MAIN METHOD
}

Program Structure Overview

Top-Level Structure
1. PACKAGE DECLARATION

package com.example;


2. IMPORT DECLARATIONS

import java.util.Scanner;


3. TYPE DECLARATION

public class Main {

    // Class Members

}

The package declaration, when present, appears before imports. Import declarations appear before the class declaration. Fields, constructors, and methods are written inside the class body.

Package

Identifies the package to which the source type belongs.

Imports

Allow types from other packages to be referenced using simpler names.

Class

Defines a type and contains fields, constructors, methods, and other members.

Members

Represent the data and behavior defined inside the class.

The Java Source File

Java source code is normally stored in files with the .java extension. A source file can contain declarations that define classes, interfaces, enums, records, and annotation interfaces.

Source File
Student.java

        │
        ▼

CONTAINS JAVA SOURCE CODE

        │
        ▼

COMPILED BY javac

        │
        ▼

GENERATES BYTECODE

For now, this course focuses primarily on classes. Other Java type declarations will be introduced when appropriate.

Elements of a Java Source File

Source File Elements
JAVA SOURCE FILE

├── Comments
├── Package Declaration
├── Import Declarations
└── Type Declarations
    ├── Classes
    ├── Interfaces
    ├── Enums
    ├── Records
    └── Annotation Interfaces
Important
  • Not every source file contains every possible element.
  • A package declaration is optional.
  • Import declarations are optional.
  • Comments are optional.
  • A simple source file may contain only one class.

Package Declaration

Package Declaration
package com.programinds.app;

A package declaration identifies the package to which the type belongs. Packages help organize related classes and avoid naming conflicts.

Package Hierarchy
com
└── programinds
    └── app
        └── Student.java
Student.java
package com.programinds.app;

public class Student {

}
Packages Will Be Covered Later
  • You will learn package creation in detail in Lesson 20.
  • For now, understand where a package declaration appears in a source file.

Position of the Package Declaration

When a package declaration is present, it must appear before import declarations and type declarations, except that comments and whitespace may appear before it.

Correct Order
// Comment

package com.example;

import java.util.Scanner;

public class Main {

}
Incorrect Order
import java.util.Scanner;

package com.example;

public class Main {

}
Correct Position
COMMENTS

        │
        ▼

PACKAGE

        │
        ▼

IMPORTS

        │
        ▼

TYPE DECLARATION

Import Statements

Import Statement
import java.util.Scanner;

An import declaration allows a type from another package to be referenced using its simple name instead of repeatedly writing its fully qualified name.

Without Import
java.util.Scanner scanner =
    new java.util.Scanner(System.in);
With Import
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

    }

}
Import Purpose
FULLY QUALIFIED NAME

java.util.Scanner

        │
        ▼

IMPORT

import java.util.Scanner;

        │
        ▼

SIMPLE NAME

Scanner

Position of Import Statements

Import declarations appear after the package declaration and before type declarations.

Correct Structure
package com.example;

import java.util.Scanner;
import java.time.LocalDate;

public class Main {

}
Import Placement
  • Imports do not normally appear inside a class.
  • Imports do not appear inside a method.
  • Imports belong before top-level type declarations.

Class Declaration

Class Declaration
public class Student {

}

A class declaration defines a class. The class can contain data and behavior through fields, constructors, methods, and other members.

Class Declaration Parts
public class Student {
  │      │      │
  │      │      └── Class Body
  │      │
  │      └───────── Class Name
  │
  └──────────────── Access Modifier

Access Modifier

Access Modifier
public class Student {

}

The public keyword controls accessibility. A public top-level class can be accessed from other packages when other access requirements are satisfied.

Later Topic
  • Access modifiers will be explained in detail during Object-Oriented Programming lessons.
  • For now, recognize public as part of the class declaration.

The class Keyword

class Keyword
class

The class keyword tells Java that a class is being declared.

Examples
class Student {

}

class Employee {

}

class Product {

}

Class Name

Class Name
public class Student {

}

Student is the class name. Class names should be meaningful and conventionally use PascalCase.

PascalCase
Student

BankAccount

EmployeeManager

OnlineShoppingCart
Good Class Names
  • Describe what the class represents.
  • Begin each word with an uppercase letter.
  • Avoid unclear abbreviations.
  • Use singular names for classes representing individual objects when appropriate.

Class Body

Class Body
public class Student {

    // Everything here is inside the class body

}

The class body is the region between the opening and closing braces of the class.

Class Body
public class Student

{

    CLASS BODY

}

The class body can contain fields, constructors, methods, initializer blocks, and nested type declarations.

Class Members

Common Class Members
CLASS

├── Fields
├── Constructors
├── Methods
└── Nested Types
Example Class Members
public class Student {

    // Field
    String name;

    // Constructor
    Student(String name) {
        this.name = name;
    }

    // Method
    void displayName() {
        System.out.println(name);
    }

}

Fields

Fields
public class Student {

    String name;
    int age;

}

Fields are variables declared as members of a class. They represent data associated with the class or its objects.

Field Position
CLASS

{

    FIELD

    FIELD

    METHOD

    {

        LOCAL VARIABLE

    }

}
Fields Will Be Covered Later
  • You will learn variables in the next lesson.
  • You will learn object fields in greater detail when studying classes and objects.

Static Fields

Static Field
public class Student {

    static String schoolName = "PrograMinds Academy";

}

A static field belongs to the class itself rather than to an individual object.

Static Field Concept
Student CLASS

        │
        ▼

schoolName

        │
        ▼

SHARED AT CLASS LEVEL

Instance Fields

Instance Fields
public class Student {

    String name;
    int age;

}

An instance field belongs to an object created from the class. Different objects can hold different values.

Instance Field Concept
STUDENT OBJECT 1

name = "Alex"
age = 21


STUDENT OBJECT 2

name = "Priya"
age = 23

Constructors

Constructor
public class Student {

    String name;

    Student(String name) {
        this.name = name;
    }

}

A constructor is used during object creation. It has the same name as the class and does not declare a return type.

Constructor Structure
Student(String name)
   │         │
   │         └── Parameter
   │
   └──────────── Constructor Name
Constructors Will Be Covered Later
  • Constructors are Lesson 19.
  • For now, recognize where a constructor appears inside a class.

Methods

Method
public void displayMessage() {

    System.out.println("Hello!");

}

A method defines behavior. It contains statements that perform a task.

Basic Method Structure
public void displayMessage()
  │     │          │
  │     │          └── Method Name
  │     │
  │     └───────────── Return Type
  │
  └─────────────────── Access Modifier

{

    METHOD BODY

}

Static Methods

Static Method
public static void showMessage() {

    System.out.println("Hello!");

}

A static method belongs to the class. It can be called using the class name without first creating an object.

Calling a Static Method
public class Message {

    public static void showMessage() {
        System.out.println("Hello!");
    }

    public static void main(String[] args) {
        Message.showMessage();
    }

}

Instance Methods

Instance Method
public void displayName() {

    System.out.println("Alex");

}

An instance method is associated with an object. It is normally called using an object reference.

Calling an Instance Method
public class Student {

    public void displayName() {
        System.out.println("Alex");
    }

    public static void main(String[] args) {

        Student student = new Student();

        student.displayName();
    }

}

The main Method

main Method
public static void main(String[] args) {

}

The main method is the traditional entry point of a standalone Java application.

Execution Entry
java Main

        │
        ▼

CLASS LOADED

        │
        ▼

main METHOD LOCATED

        │
        ▼

EXECUTION BEGINS

Structure of the main Method

main Method Breakdown
public static void main(String[] args)
  │      │      │     │        │
  │      │      │     │        └── Parameter Name
  │      │      │     │
  │      │      │     └─────────── String Array Type
  │      │      │
  │      │      └───────────────── Method Name
  │      │
  │      └──────────────────────── Return Type
  │
  └─────────────────────────────── Modifiers
  • public makes the traditional entry-point method accessible to the launcher.
  • static allows it to be used without creating an object first.
  • void means it does not return a value.
  • main is the method name.
  • String[] is the parameter type.
  • args is the parameter name.

Method Body

Method Body
public static void main(String[] args) {

    System.out.println("First");
    System.out.println("Second");

}

The method body is the block between the method braces. It contains the statements executed when the method runs.

Method Structure
METHOD DECLARATION

public static void main(String[] args)

        │
        ▼

METHOD BODY

{

    STATEMENT

    STATEMENT

}

Statements

A statement is an instruction that forms part of a Java program.

Statements
int age = 21;

age = age + 1;

System.out.println(age);
Sequential Statements
STATEMENT 1

        │
        ▼

STATEMENT 2

        │
        ▼

STATEMENT 3
Not Every Statement is the Same
  • Some statements declare variables.
  • Some statements assign values.
  • Some statements call methods.
  • Some statements control program flow.
  • Many simple statements end with a semicolon.

Expressions

An expression is code that evaluates to a value.

Expressions
10 + 20

age + 1

name.toUpperCase()

number > 10
Expression Inside a Statement
int result = 10 + 20;
Breakdown
int result = 10 + 20;
             │
             └── EXPRESSION
Expression vs Statement
  • An expression produces a value.
  • A statement performs an action as part of program execution.
  • Expressions can appear inside statements.

Code Blocks

A code block is a group of declarations and statements enclosed within curly braces.

Code Block
{

    System.out.println("First");

    System.out.println("Second");

}
Common Blocks
CLASS BLOCK

METHOD BLOCK

CONSTRUCTOR BLOCK

CONDITIONAL BLOCK

LOOP BLOCK

Nested Blocks

A block can exist inside another block. This creates nested structure.

Nested Blocks
public class Main {                 // Class block

    public static void main(String[] args) {  // Method block

        if (true) {                          // Conditional block

            System.out.println("Hello");

        }

    }

}
Nested Structure
CLASS

└── METHOD

    └── CONDITIONAL

        └── STATEMENT

Local Variables

Local Variables
public static void main(String[] args) {

    String name = "Alex";

    int age = 21;

}

A local variable is declared inside a method, constructor, or block. Its scope is limited to the region where it is declared according to Java scope rules.

Field vs Local Variable
CLASS

{

    int field;

    METHOD

    {

        int localVariable;

    }

}
Next Lesson
  • Variables are the next Core Java topic.
  • You will learn declaration, initialization, assignment, scope, lifetime, and naming rules.

Comments in Program Structure

Comments
// Single-line comment

/*
    Multi-line comment
*/

/**
 * Documentation comment
 */

Comments can appear in many places where Java syntax permits whitespace. They are used to explain code and provide documentation.

Comments in a Program
// Package declaration
package com.example;

// Import
import java.util.Scanner;

/**
 * Main application class.
 */
public class Main {

    // Application entry point
    public static void main(String[] args) {

        // Display message
        System.out.println("Hello!");

    }

}

Annotations

Annotation Example
@Override
public String toString() {

    return "Student";

}

Annotations provide metadata about program elements. They begin with the @ symbol.

Annotation
@Override
    │
    ▼
ANNOTATION
Advanced Topic
  • You do not need to master annotations now.
  • Recognize that annotations can appear before classes, methods, fields, parameters, and other program elements.

Normal Order of Elements

Common Source File Order
package com.example;

import java.util.Scanner;

public class Student {

    // Static fields

    // Instance fields

    // Constructors

    // Methods

    // main method

}
Typical Organization
1. PACKAGE

2. IMPORTS

3. CLASS

    3.1 STATIC FIELDS

    3.2 INSTANCE FIELDS

    3.3 CONSTRUCTORS

    3.4 METHODS

    3.5 NESTED TYPES
Style vs Language Requirement
  • Some ordering rules are required by Java syntax.
  • Some ordering choices are coding conventions.
  • Consistent organization makes large classes easier to understand.

Valid Program Structures

Java classes can be organized in different valid ways depending on what the class needs to represent.

Only main Method
public class Main {

    public static void main(String[] args) {

        System.out.println("Hello!");

    }

}
Fields and Methods
public class Student {

    String name;

    void displayName() {
        System.out.println(name);
    }

}
Fields, Constructor, and Methods
public class Student {

    String name;

    Student(String name) {
        this.name = name;
    }

    void displayName() {
        System.out.println(name);
    }

}

Multiple Classes in One Source File

A Java source file can contain multiple top-level classes, subject to rules about public top-level types.

Main.java
public class Main {

    public static void main(String[] args) {

        Helper.showMessage();

    }

}

class Helper {

    static void showMessage() {

        System.out.println("Hello from Helper!");

    }

}
Source File
Main.java

├── public class Main
│
└── class Helper
Common Practice
  • Although multiple top-level classes can exist in one source file, projects usually place important classes in separate files.
  • Separate files improve organization and maintainability.

The Public Top-Level Class Rule

A source file cannot declare multiple public top-level classes.

Invalid Structure
public class Student {

}

public class Teacher {

}
Problem
ONE SOURCE FILE

├── public class Student
│
└── public class Teacher

        │
        ▼

NOT ALLOWED
Separate Files
// Student.java
public class Student {

}


// Teacher.java
public class Teacher {

}

Filename and Public Class Name

When a public top-level class is declared, the source filename must match the class name.

Correct
SOURCE FILE

Student.java


PUBLIC CLASS

Student
Incorrect
SOURCE FILE

Person.java


PUBLIC CLASS

Student

        │
        ▼

COMPILATION ERROR
Exact Match
  • Student must be stored in Student.java.
  • BankAccount must be stored in BankAccount.java.
  • Java is case-sensitive.
  • student.java and Student.java are not the same name.

Empty Class

Empty Class
public class Student {

}

An empty class is valid Java. It contains no explicitly declared fields, constructors, or methods.

Valid Does Not Mean Useful
  • The class can compile.
  • It does not contain a main method.
  • Running it as a traditional standalone application will not work because there is no application entry point.

Can a Java Class Exist Without main()?

Yes. Most classes in real Java applications do not contain a main method.

Student.java
public class Student {

    String name;

    void study() {

        System.out.println("Student is studying.");

    }

}
Main.java
public class Main {

    public static void main(String[] args) {

        Student student = new Student();

        student.study();

    }

}
Application Structure
APPLICATION

├── Main.java
│   └── Contains main()
│
└── Student.java
    └── Does not contain main()

Java Program Execution Flow

Execution Overview
SOURCE CODE

        │
        ▼

COMPILATION

        │
        ▼

BYTECODE

        │
        ▼

JAVA LAUNCHER

        │
        ▼

JVM STARTS

        │
        ▼

CLASS LOADING

        │
        ▼

CLASS INITIALIZATION

        │
        ▼

main METHOD

        │
        ▼

STATEMENTS

        │
        ▼

METHOD CALLS / OBJECT CREATION

        │
        ▼

PROGRAM COMPLETES

Class Loading

Before a class can be used by the running application, the JVM must load its class information.

Class Loading
Main.class

        │
        ▼

CLASS LOADER

        │
        ▼

CLASS INFORMATION AVAILABLE TO JVM
Advanced Process
  • Class loading is more complex than this simplified diagram.
  • You will encounter deeper JVM behavior in advanced Java.
  • For now, understand that the class must be available before execution can use it.

Static Initialization

Static Initialization Example
public class Main {

    static String message = "Java";

    static {
        System.out.println("Static block");
    }

    public static void main(String[] args) {

        System.out.println(message);

    }

}
Output
Static block
Java

Static fields and static initializer blocks participate in class initialization. Their detailed rules will be studied later.

main Method Execution

Main Execution
public class Main {

    public static void main(String[] args) {

        System.out.println("First");
        System.out.println("Second");
        System.out.println("Third");

    }

}
Execution Order
main STARTS

        │
        ▼

PRINT "First"

        │
        ▼

PRINT "Second"

        │
        ▼

PRINT "Third"

        │
        ▼

main ENDS

Object Creation During Execution

Object Creation
public class Main {

    public static void main(String[] args) {

        Student student = new Student();

    }

}
Simplified Flow
main EXECUTES

        │
        ▼

new Student()

        │
        ▼

OBJECT CREATED

        │
        ▼

REFERENCE STORED IN student

Method Calls During Execution

Method Call
public class Main {

    static void greet() {

        System.out.println("Hello!");

    }

    public static void main(String[] args) {

        System.out.println("Before");

        greet();

        System.out.println("After");

    }

}
Execution Flow
main

        │
        ▼

PRINT "Before"

        │
        ▼

CALL greet()

        │
        ▼

PRINT "Hello!"

        │
        ▼

RETURN TO main

        │
        ▼

PRINT "After"

Program Termination

A simple program normally ends when execution finishes and no remaining non-daemon work keeps the JVM running.

Simple Program End
main STARTS

        │
        ▼

STATEMENTS EXECUTE

        │
        ▼

main RETURNS

        │
        ▼

NO REMAINING WORK

        │
        ▼

PROGRAM ENDS

Top-to-Bottom Execution

Statements inside a method generally execute from top to bottom unless control-flow statements, method calls, exceptions, or other language features change the path.

Sequential Execution
System.out.println("A");

System.out.println("B");

System.out.println("C");
Output
A
B
C

Declaration Order vs Execution Order

The physical position of a method declaration does not mean the method executes automatically at that position.

Declaration and Execution
public class Main {

    static void greet() {

        System.out.println("Hello!");

    }

    public static void main(String[] args) {

        System.out.println("Start");

        greet();

        System.out.println("End");

    }

}
Actual Output
Start
Hello!
End
Important Difference
  • A method declaration defines behavior.
  • The method body executes when the method is called.
  • Code location and runtime execution order are not always the same.

Whitespace in Java

Whitespace includes spaces, tabs, and line breaks. Java generally allows flexible whitespace between tokens.

Readable
public class Main {

    public static void main(String[] args) {

        System.out.println("Hello");

    }

}
Compact but Valid
public class Main{public static void main(String[] args){System.out.println("Hello");}}
Readable Code is Better
  • Both examples can represent valid Java.
  • The first version is easier to read.
  • Professional code should use consistent formatting.

Indentation

Consistent Indentation
public class Main {

    public static void main(String[] args) {

        if (true) {

            System.out.println("Hello");

        }

    }

}
Indentation Levels
LEVEL 0    class

LEVEL 1        method

LEVEL 2            conditional

LEVEL 3                statement
Formatting Recommendation
  • Use consistent indentation throughout the project.
  • Do not randomly mix indentation styles.
  • Use your IDE formatter when working on larger projects.

Brace Styles

Common Java Style
public class Main {

    public static void main(String[] args) {

    }

}
Alternative Style
public class Main
{

    public static void main(String[] args)
    {

    }

}

Different teams may use different brace styles. The important requirement is to follow the project convention consistently.

Java Naming Conventions

Common Conventions
PACKAGE

com.programinds.app


CLASS

StudentAccount


METHOD

displayDetails


VARIABLE

studentName


CONSTANT

MAX_ATTEMPTS

Packages

Conventionally use lowercase names.

Classes

Conventionally use PascalCase.

Methods

Conventionally use camelCase.

Variables

Conventionally use camelCase.

Constants

Conventionally use UPPER_SNAKE_CASE.

Standard Java File Organization

Simple Project
project

└── src
    └── com
        └── programinds
            └── app
                ├── Main.java
                ├── Student.java
                └── Course.java
Package Relationship
FOLDER STRUCTURE

com/programinds/app

        │
        ▼

PACKAGE NAME

com.programinds.app

Simple Application Structure

Main.java
public class Main {

    public static void main(String[] args) {

        System.out.println("Application Started");

    }

}
Project
SimpleApplication

└── Main.java

Multi-Class Application Structure

Student.java
public class Student {

    String name;

    Student(String name) {
        this.name = name;
    }

    void displayName() {
        System.out.println(name);
    }

}
Main.java
public class Main {

    public static void main(String[] args) {

        Student student = new Student("Alex");

        student.displayName();

    }

}
Project Structure
StudentApplication

├── Main.java
│   └── Application Entry Point
│
└── Student.java
    └── Student Data and Behavior

Common Program Structure Errors

Common Errors
STRUCTURE ERRORS

├── Package in Wrong Position
├── Import Inside Class
├── Method Outside Class
├── Statement Directly in Class Body
├── Missing Opening Brace
├── Missing Closing Brace
├── Multiple Public Top-Level Classes
├── Filename Does Not Match Public Class
├── main Method Written Incorrectly
├── Method Declared Inside Another Method
└── Code Written Outside All Types
Method Outside Class
public class Main {

}

public static void showMessage() {

}
Import Inside Class
public class Main {

    import java.util.Scanner;

}
Method Inside Method
public class Main {

    public static void main(String[] args) {

        void greet() {

        }

    }

}
Check the Structure First
  • Verify that package and imports are at the top level.
  • Verify that methods are inside classes.
  • Verify that statements are inside executable blocks.
  • Verify that braces are balanced.
  • Verify that the filename matches the public class.

Best Practices

  • Use one important public top-level class per source file.
  • Match the filename with the public class name.
  • Place the package declaration before imports.
  • Place imports before type declarations.
  • Keep related classes in appropriate packages.
  • Use meaningful class names.
  • Use PascalCase for class names.
  • Use camelCase for methods and variables.
  • Use UPPER_SNAKE_CASE for constants.
  • Keep class members logically organized.
  • Use consistent indentation.
  • Use consistent brace style.
  • Keep methods focused on clear tasks.
  • Avoid placing unrelated responsibilities in one class.
  • Use comments to explain important decisions rather than obvious syntax.
  • Keep braces balanced and visually aligned.
  • Understand the difference between fields and local variables.
  • Understand the difference between declarations and executable statements.
  • Remember that method declaration position does not determine runtime execution order.
  • Use separate source files as applications grow.
  • Use IDE formatting tools consistently.
  • Follow the coding convention of the project or team.

Java Program Structure Checklist

Checklist
JAVA STRUCTURE CHECKLIST

[ ] Source file uses .java extension

[ ] Package declaration is first when present

[ ] Imports appear after package

[ ] Type declaration appears after imports

[ ] Public class name matches filename

[ ] Only one public top-level class exists in the file

[ ] Class has opening and closing braces

[ ] Fields are declared inside the class

[ ] Constructors are declared inside the class

[ ] Methods are declared inside the class

[ ] Methods are not declared inside other methods

[ ] Executable statements are inside valid blocks

[ ] main method is correctly declared when needed

[ ] Method braces are balanced

[ ] Nested blocks are properly closed

[ ] Indentation is consistent

[ ] Names follow Java conventions

[ ] Source file is saved before compilation

Common Misconceptions

Avoid These Misconceptions
  • Every Java class does not need a main method.
  • Most classes in real applications do not contain main().
  • A Java application can use many classes.
  • A source file can contain more than one top-level class.
  • A source file cannot contain multiple public top-level classes.
  • The public class name must match the filename.
  • Package declarations do not go inside classes.
  • Import declarations do not go inside methods.
  • Methods must be declared inside a class or another valid type declaration.
  • A normal method cannot be declared inside another method.
  • Fields and local variables are not the same.
  • Fields are declared as class members.
  • Local variables are declared inside methods, constructors, or blocks.
  • A class body can contain more than the main method.
  • A method body contains executable statements.
  • An expression and a statement are not always the same thing.
  • Expressions can appear inside statements.
  • Curly braces define blocks.
  • Indentation does not replace braces in Java.
  • Whitespace is flexible but readable formatting still matters.
  • The first method written in the file does not automatically execute first.
  • Methods execute when they are invoked.
  • Program execution does not simply run every line in the source file from top to bottom.
  • Declarations define program structure.
  • Executable statements run according to runtime control flow.
  • Static members belong to the class.
  • Instance members are associated with objects.
  • Constructors are not ordinary methods.
  • Constructors do not declare a return type.
  • A class can compile even if it has no main method.
  • A class without main() cannot normally be launched directly as a traditional standalone application.
  • Imports do not copy another class into your source file.
  • An import allows a type to be referenced using a simpler name.
  • Comments are part of source code documentation but are not executed as normal statements.
  • Annotations provide metadata.
  • The package declaration, import declarations, and class body serve different purposes.
  • The source file structure and runtime execution flow are different concepts.
  • A large Java project is normally divided across multiple files and packages.

Practice Exercises

Exercise 1: Identify Program Parts
  • Create a Main class.
  • Add a main method.
  • Add three output statements.
  • Identify the class declaration.
  • Identify the method declaration.
  • Identify the method body.
  • Identify each statement.
Exercise 2: Add a Field
  • Create a Student class.
  • Add a String field named name.
  • Add an int field named age.
  • Identify which variables are fields.
Exercise 3: Add a Method
  • Create a method named displayMessage.
  • Print a message inside the method.
  • Call the method from main.
  • Observe the execution order.
Exercise 4: Multiple Classes
  • Create Main.java.
  • Create Student.java.
  • Keep main() only in Main.
  • Create a Student object from Main.
  • Call a Student method.
Exercise 5: Find Structural Errors
  • Move an import inside a class and observe the error.
  • Move a method outside the class and observe the error.
  • Remove a closing brace and observe the error.
  • Restore the correct structure after each test.
Exercise 6: Execution Order
  • Print Start inside main.
  • Call another method.
  • Print a message inside that method.
  • Return to main.
  • Print End.
  • Write the expected output before running the program.
Exercise 7: Build a Structured Class
  • Create a class named Employee.
  • Add two fields.
  • Add one constructor.
  • Add one instance method.
  • Add one static method.
  • Create an Employee object from main.
  • Call both methods.

Common Interview Questions

What is the basic structure of a Java program?

A basic Java program normally contains a class declaration and, for a traditional standalone application, a main method containing executable statements.

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

The package declaration appears first when present, followed by import declarations and then type declarations.

Can a Java class exist without a main method?

Yes. Most classes in Java applications do not contain a main method.

Can a Java source file contain multiple classes?

Yes. A source file can contain multiple top-level classes, but it cannot declare multiple public top-level classes.

Why must the filename match the public class name?

Java requires a public top-level class to be declared in a source file with the corresponding class name.

What is a class body?

The class body is the region enclosed by the class opening and closing braces.

What can a class body contain?

A class body can contain fields, constructors, methods, initializer blocks, and nested type declarations.

What is a field?

A field is a variable declared as a member of a class.

What is a local variable?

A local variable is declared inside a method, constructor, or block.

What is a method?

A method defines behavior and contains statements that perform a task.

What is a code block?

A code block is a group of declarations and statements enclosed within curly braces.

What is an expression?

An expression is code that evaluates to a value.

What is a statement?

A statement is an instruction that forms part of program execution.

Can a method be declared inside another method?

A normal Java method cannot be declared inside another method.

What is the purpose of an import declaration?

It allows a type from another package to be referenced using its simple name.

What is the purpose of a package declaration?

It identifies the package to which the declared type belongs.

Do methods execute in the order they are written in the source file?

No. Methods execute when they are called according to runtime control flow.

What is the difference between a static member and an instance member?

A static member belongs to the class, while an instance member is associated with an object.

What is the traditional entry point of a Java application?

The traditional entry point is the main method.

What are Java naming conventions?

Common conventions include lowercase package names, PascalCase class names, camelCase method and variable names, and UPPER_SNAKE_CASE constant names.

Frequently Asked Questions

Does every Java file need a package declaration?

No. A source file can belong to the unnamed package, though named packages are normally used in real applications.

Does every Java file need imports?

No. Imports are only needed when you want to use simple names for types that are not otherwise directly available by simple name.

Can comments appear before the package declaration?

Yes. Comments and whitespace can appear before the package declaration.

Can imports appear before the package declaration?

No. When a package declaration is present, it must precede import declarations.

Can I put an import inside main()?

No. Import declarations belong at the source-file level before type declarations.

Can I put System.out.println() directly inside a class body?

A normal executable statement cannot simply appear directly in the class body. It must be inside a valid executable context such as a method, constructor, or initializer block.

Can I have two main methods?

Methods can be overloaded with different parameter lists, but the launcher looks for the appropriate application entry-point form.

Can multiple classes have main methods?

Yes. Different classes can each define a main method and can be launched separately.

Does the main method have to be written first inside the class?

No. Its physical position inside the class does not make it execute earlier or later.

Can fields be declared after methods?

Java can allow member declarations in different orders, but projects normally follow consistent organization conventions.

Is an empty class valid?

Yes. An empty class declaration is valid.

Can an empty class be run directly?

Not as a traditional standalone application unless it provides an appropriate entry point.

What is the difference between source structure and execution flow?

Source structure describes how code is organized, while execution flow describes the order in which instructions run.

Why are braces important?

Braces define the boundaries of classes, methods, constructors, conditionals, loops, and other blocks.

Does indentation define blocks in Java?

No. Braces define blocks. Indentation is used to make the structure readable.

Can one Java application have hundreds of classes?

Yes. Large Java applications can contain hundreds or thousands of classes organized into packages and modules.

Should every class be placed in a separate file?

Important top-level classes are commonly placed in separate files because it improves organization, although Java can allow multiple non-public top-level classes in one file.

What is the difference between a field and a local variable?

A field is declared as a class member, while a local variable is declared inside a method, constructor, or block.

What is the difference between a constructor and a method?

A constructor participates in object creation, has the class name, and has no declared return type. A method defines behavior and has its own method name and return type.

What happens first when a Java application runs?

At a simplified level, the JVM loads and initializes required classes before invoking the application entry point.

Key Takeaways

  • Java programs follow a structured organization.
  • Java source files use the .java extension.
  • A source file can contain package, import, and type declarations.
  • A package declaration identifies the package of a type.
  • The package declaration appears before imports.
  • Import declarations appear before type declarations.
  • Imports allow types to be referenced using simpler names.
  • A class declaration defines a class.
  • The class keyword is used to declare a class.
  • Class names conventionally use PascalCase.
  • The class body is enclosed in curly braces.
  • A class body can contain fields.
  • A class body can contain constructors.
  • A class body can contain methods.
  • A class body can contain nested types.
  • Fields are variables declared as class members.
  • Static fields belong to the class.
  • Instance fields are associated with objects.
  • Constructors participate in object creation.
  • Constructors have the same name as the class.
  • Constructors do not declare a return type.
  • Methods define behavior.
  • Static methods belong to the class.
  • Instance methods are associated with objects.
  • The main method is the traditional application entry point.
  • The main method is commonly declared as public static void main(String[] args).
  • A method body contains executable statements.
  • Statements form executable instructions.
  • Expressions evaluate to values.
  • Expressions can appear inside statements.
  • Code blocks are enclosed in curly braces.
  • Blocks can be nested.
  • Local variables are declared inside methods, constructors, or blocks.
  • Comments can document program structure.
  • Annotations provide metadata.
  • A source file can contain multiple top-level classes.
  • A source file cannot contain multiple public top-level classes.
  • A public top-level class name must match the source filename.
  • An empty class is valid.
  • A class does not always need a main method.
  • Most classes in real applications do not contain main().
  • A Java application can contain many classes.
  • One class can provide the application entry point.
  • Other classes can provide data and behavior.
  • Program execution begins from the entry point in a traditional application.
  • Classes must be available to the JVM before they can be used.
  • Static initialization can occur before main executes.
  • Statements inside a method generally execute sequentially unless control flow changes.
  • Method calls temporarily transfer execution to another method.
  • Object creation can occur during execution.
  • The program can return from a called method and continue the caller.
  • Source declaration order is not the same as runtime execution order.
  • Methods execute when called.
  • Whitespace is flexible between many Java tokens.
  • Readable formatting is still essential.
  • Indentation visually represents nesting.
  • Braces define blocks, not indentation.
  • Projects should use consistent brace styles.
  • Package names conventionally use lowercase.
  • Class names conventionally use PascalCase.
  • Method names conventionally use camelCase.
  • Variable names conventionally use camelCase.
  • Constants conventionally use UPPER_SNAKE_CASE.
  • Real Java projects organize files into packages.
  • Folder structure commonly reflects package structure.
  • Large applications use multiple source files.
  • Methods cannot normally be declared inside other methods.
  • Imports cannot be declared inside classes or methods.
  • Executable statements cannot simply be placed anywhere in a source file.
  • Balanced braces are essential for correct structure.
  • Understanding program structure makes future Java topics easier.

Summary

A Java source file has a defined structure. When present, the package declaration appears first, followed by import declarations and then type declarations such as classes.

A class declaration contains a class body enclosed by curly braces. The class body can contain fields, constructors, methods, initializer blocks, and nested types.

Fields represent data defined at class level. Static fields belong to the class, while instance fields are associated with individual objects. Local variables are different because they are declared inside methods, constructors, or blocks.

Constructors participate in object creation, while methods define behavior. Static methods belong to the class, and instance methods are normally called through objects.

The main method is the traditional entry point of a standalone Java application. Its body contains statements that begin the application execution flow.

Statements perform actions, while expressions evaluate to values. Statements and declarations are organized into blocks using curly braces, and blocks can be nested inside other blocks.

A Java source file can contain multiple top-level classes, but it cannot contain multiple public top-level classes. When a public top-level class exists, the source filename must match that class name.

Not every Java class requires a main method. Real applications normally contain many classes, while only specific classes provide application entry points.

Source code organization and runtime execution order are different concepts. A method does not execute simply because it appears earlier in the file. Methods execute when they are called according to program flow.

Good Java structure uses meaningful names, consistent indentation, balanced braces, logical member organization, appropriate packages, and separate source files as applications grow.

Lesson 6 Completed
  • You understand the basic structure of a Java program.
  • You understand the structure of a Java source file.
  • You understand the purpose of package declarations.
  • You know where package declarations appear.
  • You understand the purpose of import declarations.
  • You know where imports appear.
  • You understand class declarations.
  • You recognize access modifiers in class structure.
  • You understand the class keyword.
  • You understand class naming conventions.
  • You understand the class body.
  • You understand what class members are.
  • You recognize fields.
  • You understand the basic difference between static and instance fields.
  • You recognize constructors.
  • You recognize methods.
  • You understand the basic difference between static and instance methods.
  • You understand the role of the main method.
  • You understand the detailed main method structure.
  • You understand method bodies.
  • You understand statements.
  • You understand expressions.
  • You understand the basic difference between expressions and statements.
  • You understand code blocks.
  • You understand nested blocks.
  • You recognize local variables.
  • You understand where comments can appear.
  • You recognize annotations.
  • You understand the normal order of source-file elements.
  • You understand that multiple valid class structures are possible.
  • You understand that one source file can contain multiple classes.
  • You understand the public top-level class rule.
  • You understand the relationship between filename and public class name.
  • You understand that an empty class is valid.
  • You understand that not every class needs main().
  • You understand the basic program execution flow.
  • You understand basic class loading.
  • You recognize static initialization.
  • You understand main method execution.
  • You understand object creation in program flow.
  • You understand method-call flow.
  • You understand simple program termination.
  • You understand top-to-bottom statement execution.
  • You understand the difference between declaration order and execution order.
  • You understand Java whitespace.
  • You understand why indentation matters.
  • You recognize different brace styles.
  • You understand basic Java naming conventions.
  • You understand standard file organization.
  • You understand simple application structure.
  • You understand multi-class application structure.
  • You can identify common structural errors.
  • You know the best practices for organizing Java code.
  • You are ready to learn Java variables in detail.
Next Lesson →

Variables in Java