In this tutorial, you will learn the structure of a Java program, the order of its main parts, and how package declarations, imports, classes, variables, methods, and the main() method fit together in a working Java file.

Basic structure of a Java program

A Java program is usually written as one or more .java files. Each file contains Java code arranged in a specific order. A simple Java source file may include a package declaration, import statements, comments, a class definition, variables, constructors, methods, and, for an executable application, a main() method.

The usual order of a Java program is:

  • Package Declaration
  • Import Statements
  • Comments
  • Class Definition
  • Variables (Class and Local)
  • Methods/Routines/Behaviors

The diagram below illustrates these elements, showing how they come together to form the overall structure of a Java program.

Structure of a Java program
Structure of a Java Program

Java program structure syntax template

The following template shows the basic format of a Java program. Not every Java file needs every part, but this order is commonly used in beginner and real project files.

</>
Copy
package packageName;

import packageName.ClassName;

// Comments describe the purpose of the class or code.
public class ClassName {

    // Fields or instance variables
    dataType variableName;

    // Constructor
    ClassName() {
        // initialization code
    }

    // Main method - program execution starts here
    public static void main(String[] args) {
        // statements
    }

    // Other methods
    returnType methodName(parameters) {
        // method body
        return value;
    }
}

In a very small Java program, the package declaration, import statements, fields, constructor, and extra methods may be absent. The class definition is required, and the main() method is required when you want to run the class directly as a Java application.

1 Package declaration in a Java program

Java classes are often organized into packages, which group related classes together. The package declaration at the top of a Java file defines the package to which the class belongs.

If a package declaration is used, it must appear before import statements and before the class definition. A Java source file can have only one package declaration.

</>
Copy
package com.example.demo;

For small beginner programs, you may write a class without a package declaration. In larger projects, packages help keep code organized and reduce naming conflicts.

2 Import statements in a Java program

Many useful classes reside in different packages or libraries. Import statements allow you to access these external classes in your program. You can include multiple import statements to bring in the functionality you need.

Import statements are written after the package declaration and before the class definition.

</>
Copy
import java.util.Scanner;
import java.time.LocalDate;

Java automatically imports the java.lang package, so classes such as String, System, and Math can be used without writing an explicit import statement.

3 Comments in a Java source file

Comments are notes written for humans who read the code. The Java compiler ignores comments. Comments are useful for explaining the purpose of a class, method, variable, or important logic.

</>
Copy
// Single-line comment

/*
 Multi-line comment
*/

/**
 * Documentation comment used by Javadoc.
 */

Use comments where they add clarity. Avoid comments that simply repeat what the code already says.

4 Class definition in a Java program

Every Java program requires at least one class definition. A class groups data and behaviour into a single unit. In a basic Java application, the class contains the main() method and any other fields or methods required by the program.

If a top-level class is declared as public, the source filename must match the public class name. For example, a public class named HelloWorld should be saved in a file named HelloWorld.java.

</>
Copy
public class HelloWorld {
    // class body
}

5 Variables and fields in Java program structure

Variables store data values that your program uses during execution. They can be declared at the class level or inside methods.

  • Fields are variables declared inside a class but outside methods. They represent data that belongs to an object or to the class itself.
  • Local variables are declared inside a method, constructor, or block. They can be used only within that area.
  • Static variables belong to the class rather than to a specific object.
</>
Copy
public class Student {
    String name;        // field
    static int count;   // static variable

    void printName() {
        int year = 2026; // local variable
        System.out.println(name + " - " + year);
    }
}

6 Main method as the Java application entry point

The main method is the entry point of a Java application. When you run a Java class from the command line or an IDE, the Java runtime looks for a valid main() method and starts execution from there.

</>
Copy
public static void main(String[] args) {
    // program starts here
}

Each keyword in the main method signature has a purpose:

  • public allows the method to be accessed by the Java runtime.
  • static allows the method to run without creating an object of the class first.
  • void means the method does not return a value.
  • String[] args stores command-line arguments passed to the program.

7 Methods and behaviour inside a Java class

Methods encapsulate a set of instructions that perform specific tasks. By defining methods, you can reuse code and simplify complex operations. Methods may accept parameters and return values, allowing you to create modular and maintainable programs.

</>
Copy
static int add(int a, int b) {
    return a + b;
}

In this method, a and b are parameters, int is the return type, and return a + b; sends the result back to the caller.

Complete Java program structure example

The following example shows a small Java program with imports, a class, a field, the main() method, and another method.

</>
Copy
import java.util.Scanner;

public class GreetingApp {

    static String defaultName = "Student";

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter your name: ");
        String name = scanner.nextLine();

        if (name.isBlank()) {
            name = defaultName;
        }

        printGreeting(name);
        scanner.close();
    }

    static void printGreeting(String name) {
        System.out.println("Hello, " + name + "!");
    }
}

If the user enters Arjun, the output is:

Enter your name: Arjun
Hello, Arjun!

In this example, GreetingApp is the class name, defaultName is a static field, main() starts the program, name is a local variable, and printGreeting() is a reusable method.

How to compile and run a basic Java program

Save the file with the same name as the public class. For the example above, the filename should be GreetingApp.java. Then compile and run it from the terminal as shown below.

</>
Copy
javac GreetingApp.java
java GreetingApp

The javac command compiles the source file and creates a .class file. The java command runs the compiled class.

Java program structure checklist for beginners

  • Check that the package declaration, if present, is the first non-comment statement.
  • Place import statements after the package declaration and before the class definition.
  • Save a public class in a file with the same name as the class.
  • Use a valid public static void main(String[] args) method when the class must run as an application.
  • Declare local variables before using them inside a method.
  • Close every opening brace { with a matching closing brace }.

Common mistakes in Java program structure

  • Writing import statements before the package declaration.
  • Using a filename that does not match the public class name.
  • Misspelling public static void main(String[] args).
  • Declaring a local variable inside one method and trying to use it in another method.
  • Forgetting semicolons at the end of Java statements.
  • Forgetting to close braces in class or method blocks.

Basic parts of a Java program: quick summary

Part of Java programPurposeRequired?
Package declarationPlaces the class in a named packageNo
Import statementsAllows use of classes from other packagesNo
Class definitionDefines the main unit of Java codeYes
FieldsStore object-level or class-level dataNo
Main methodStarts execution of a Java applicationYes, for directly runnable applications
Other methodsDefine reusable behaviourNo

Structure of a Java program FAQs

What is the structure of a Java application?

A Java application is usually structured as one or more classes. A runnable application has a class with a valid main() method. In larger applications, classes are grouped into packages and may use imports to access classes from libraries or other packages.

What is the basic format of a Java program?

The basic format is package declaration first, import statements next, and then the class definition. Inside the class, you may write fields, constructors, the main() method, and other methods.

What are the basic parts of a Java program?

The basic parts are package declaration, import statements, comments, class definition, variables, constructors, methods, and the main() method. A very small Java program may contain only a class and a main() method.

Should every Java program have a main method?

No. A class needs a main() method only when it must be run directly as a Java application. Classes used as models, utilities, services, or library components may not have a main() method.

Are the four pillars of Java part of Java program structure?

The four pillars usually refer to object-oriented programming concepts: encapsulation, inheritance, polymorphism, and abstraction. They are important Java concepts, but they are different from the physical structure of a Java source file.

What to remember about the structure of a Java program

In this Java Tutorial, we explored the essential components that make up the structure of a Java program. The most important rule is to understand the order of the source file: package declaration, imports, class definition, fields, constructors, and methods. In our next tutorial, we will delve into Object-Oriented Programming concepts, starting with Classes and Objects in Java.