Blog header background

Structure of Java Program: A Complete Guide with Examples

Updated on April 16, 2026

16 min read

Copy link
Share on WhatsApp

A citation-ready guide to java class structure, control structures, data structures, and complete program examples

Java is one of the most widely used object-oriented programming languages – powering web applications, enterprise software, Android development, and backend systems. Understanding the structure of java program is the essential first step for any developer. This guide covers every section of the basic structure of java program – from documentation comments to the main method – along with control structures, java class structure, and the key java data structures (graph and set).

Structure of Java Program – Overview

A complete java program structure example consists of the following sections, in order. Mandatory sections are required in every program; optional sections can be omitted.

Section

Mandatory?

Purpose

Documentation Section

Optional

Comments explaining the program – ignored by compiler

Package Declaration

Optional

Declares which package the class belongs to

Import Statements

Optional

Imports classes/interfaces from other packages

Interface Section

Optional

Defines interfaces the class may implement

Class Definition

Mandatory

The container for all program code – every Java program needs at least one class

Class Variables & Identifiers

Contextual

Declares variables and data members used by the class

Main Method

Mandatory (for execution)

The JVM entry point – execution always starts here

Methods & Behaviours

Contextual

Defines reusable blocks of logic called by the program

Note: The structure of java program follows a strict top-to-bottom ordering: documentation → package → imports → interface → class definition → main method. Only the class definition and main method are mandatory for a runnable program.

Also Read: Array in Java

brochure-banner-bg

POSTGRADUATE PROGRAM IN

Multi Cloud Architecture & DevOps

Master cloud architecture, DevOps practices, and automation to build scalable, resilient systems.

Documentation Section

The documentation section is the first – and optional – part of the structure of java program. It contains comments: author name, creation date, version, program description, and company name. Comments improve readability and are completely ignored by the Java compiler during execution.

Comment Type

Syntax

Use Case

Single-line

// comment text

Short explanations on a single line

Multi-line

/* comment text */

Longer explanations spanning multiple lines

Documentation

/** comment */

Javadoc – generates HTML API documentation via the javadoc tool

/**

* Program Name: HelloWorld

* Author: Hero Vired

* Date: 2024-01-01

* Description: Demonstrates the basic structure of java program

* Version: 1.0

*/

// This is a single-line comment

/*

This is a multi-line comment

spanning multiple lines

*/

Package Declaration

A package declaration groups related classes and interfaces into a named namespace. It is optional but recommended for any non-trivial java program structure. There can be only one package statement per file, and it must appear before any class or interface declaration – immediately after the documentation section.

// Package declaration in java language structure

package com.herovired.app;

// Once declared, all classes in this file belong to the 'com.herovired.app' package

// Packages prevent naming conflicts and organise code into logical modules

If no package is declared, the class belongs to the default package – acceptable for small programs but not recommended for production code structures in java.

Import Statements in Java

Import statements in java tell the compiler which external classes or packages the program uses. They must appear after the package declaration and before any class definitions. Without import statements, you must use the fully qualified class name (e.g., java.util.ArrayList) every time.

Import Type

Syntax

Imports

Specific class

import java.util.ArrayList;

Only the ArrayList class from java.util

Entire package

import java.util.*;

All public classes in java.util (not sub-packages)

Static import

import static java.lang.Math.*;

Static members – allows using sqrt() directly instead of Math.sqrt()

// import statements in java - code structure in java

import java.util.*; // Import entire java.util package

import java.util.StringTokenizer; // Import specific class

import java.io.IOException; // Import specific exception class

import static java.lang.Math.*; // Static import - use sqrt() not Math.sqrt()

Note: Import statements in java do not increase the compiled bytecode size – the compiler only includes what is actually used. Wildcard imports (.*) are convenient but can cause ambiguity if two packages have classes with the same name.

skill-test-section-bg

82.9%

of professionals don't believe their degree can help them get ahead at work.

Interface Section

An interface in java defines a contract – a set of method signatures that implementing classes must provide. Interfaces only contain abstract method declarations (prior to Java 8), constants, and (since Java 8+) default and static methods. They cannot be instantiated directly.

// Interface section in the java class structure

interface Drawable {

// Constants (implicitly public static final)

int MAX_SIZE = 1000;

// Abstract method - implementing class must provide the body

void draw();

// Default method (Java 8+) - optional to override

default void resize(int factor) {

System.out.println("Resizing by " + factor);

}

}

// Implementing the interface

class Circle implements Drawable {

@Override

public void draw() {

System.out.println("Drawing a circle");

}

}

Class Definition & Java Class Structure

The class definition is the mandatory core of every Java program. All Java code lives inside a class. The java class structure follows a specific format: access modifier, class keyword, class name, optional inheritance/interface clause, and the class body.

// java class structure - complete format

public class ProgramName extends ParentClass implements Interface1, Interface2 {

// 1. Class/static variables (shared across all instances)

static int instanceCount = 0;

// 2. Instance variables (unique per object)

private String name;

private int age;

// 3. Constructors

public ProgramName(String name, int age) {

this.name = name;

this.age = age;

instanceCount++;

}

// 4. Methods

public void display() {

System.out.println(name + " | Age: " + age);

}

// 5. Main method (entry point)

public static void main(String[] args) {

ProgramName p = new ProgramName("Hero", 25);

p.display();

}

}

A single Java file can contain multiple class definitions, but only one can be declared public. The public class name must match the filename exactly – a rule enforced by the Java compiler as part of the java language structure.

Class Variables, Identifiers & Naming Rules

Variables store data within the class. In the structures in java, variables are categorised by scope and lifecycle:

Variable Type

Scope

Lifecycle

Example

Local Variable

Inside a method or block

Created when method runs; destroyed when method exits

int count = 0; inside main()

Instance Variable

Inside class, outside methods

Lives as long as the object exists

private String name; inside class

Class (Static) Variable

Shared across all instances

Lives as long as the class is loaded

static int count = 0; inside class

Parameter Variable

Inside method signature

Same as local variable

public void set(String name)

Rules for Naming Variables in Java

• Must begin with a letter, underscore (_), or dollar sign ($) – not a digit

• Can contain letters, digits, underscores, and dollar signs

• Case-sensitive – name, Name, and NAME are three different identifiers

• Cannot be a Java reserved keyword (int, class, void, static, etc.)

• Should be meaningful and descriptive – use camelCase convention (studentAge, not sa)

// Valid variable declarations in simple java program structure

int age = 25;

String studentName = "Mohan";

double _salary = 75000.00;

char $grade = 'A';

// Invalid - compile errors

// int 1count = 5; ← starts with digit

// String class = "Java"; ← reserved keyword

// double my-price = 99; ← hyphen not allowed

Main Method Class

The main method is the mandatory entry point of every executable Java program. The JVM (Java Virtual Machine) calls this method directly when the program is launched. It must have the exact signature shown below – any deviation will prevent the program from running.

// Main method in the structure of java program

public static void main(String[] args) {

// 'public' - accessible by JVM from outside the class

// 'static' - JVM calls it without creating a class instance

// 'void' - returns nothing to the JVM

// 'main' - the name JVM specifically looks for

// 'String[] args' - command-line arguments passed to the program

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

}

Keyword

Why Required in Main Method

public

JVM must call this from outside the class – must be accessible

static

JVM calls main without creating an object – no instance needed

void

main returns nothing – JVM doesn’t use a return value

main

The specific identifier JVM searches for as the entry point

String[] args

Receives command-line arguments as a String array

Methods and Behaviours

Methods are reusable blocks of statements that perform a specific task. They are a core part of the java class structure and embody the OOP principle of encapsulation – hiding implementation details behind a well-defined interface.

// Methods and behaviours in code structure in java

import java.io.*;

public class Main {

// Static method - called without creating an object

public static int add(int a, int b) {

return a + b;

}

// Instance method - requires an object

public void greet(String name) {

System.out.println("Hello, " + name + "!");

}

public static void main(String[] args) throws Exception {

// Call static method directly

int sum = add(10, 20);

System.out.println("Sum: " + sum); // Output: Sum: 30

// Call instance method via object

Main obj = new Main();

obj.greet("Java Programming"); // Output: Hello, Java Programming!

}

}

Control Structure in Java

Control structure in java determines the flow of program execution – which statements run, how many times they run, and under what conditions. A control structure in java is a fundamental part of any java program structure example and enables conditional logic, iteration, and branching.

Control Structure Type

Statements

Purpose

Sequential

Default – statements execute top-to-bottom

Normal linear program flow

Selection (Conditional)

if, if-else, if-else-if, switch

Execute different code paths based on conditions

Iteration (Loop)

for, while, do-while, enhanced-for

Repeat a block of statements multiple times

Jump/Transfer

break, continue, return

Alter normal flow – exit loop, skip iteration, return value

Selection Control Structure in Java – if-else and switch

// Selection control structure in java

public class ControlDemo {

public static void main(String[] args) {

// if-else - basic conditional

int score = 75;

if (score >= 90) System.out.println("Grade: A");

else if (score >= 75) System.out.println("Grade: B"); // Output: Grade: B

else System.out.println("Grade: C");

// switch - multi-branch selection

String day = "MON";

switch (day) {

case "MON": System.out.println("Monday"); break; // Output: Monday

case "TUE": System.out.println("Tuesday"); break;

default: System.out.println("Other");

}

}

}

Iteration Control Structure in Java – for, while, do-while

// Iteration control structure in java

public class LoopDemo {

public static void main(String[] args) {

// for loop - known number of iterations

for (int i = 1; i <= 5; i++)

System.out.print(i + " "); // Output: 1 2 3 4 5

System.out.println();

// while loop - condition-based iteration

int n = 10;

while (n > 0) { System.out.print(n + " "); n -= 3; }

// Output: 10 7 4 1

System.out.println();

// enhanced for loop - iterate over array/collection

int[] nums = {2, 4, 6, 8};

for (int num : nums) System.out.print(num + " ");

// Output: 2 4 6 8

}

}

Java Graph Data Structure

The java graph data structure represents networks of connected nodes (vertices) and edges. A java graph data structure is widely used in social networks, maps, routing algorithms, and dependency resolution. In Java, graphs are typically implemented using an adjacency list (HashMap with lists) or adjacency matrix (2D array).

Graph Type

Description

Common Use Cases

Undirected Graph

Edges have no direction - connection is bidirectional

Social networks, road maps

Directed Graph (Digraph)

Edges have direction - A→B does not imply B→A

Web page links, dependency graphs

Weighted Graph

Edges carry a numeric weight/cost

GPS routing, network bandwidth

Cyclic/Acyclic

Whether the graph contains cycles

DAGs for task scheduling (acyclic)

Java Graph Data Structure - Adjacency List Implementation

// java graph data structure - adjacency list using HashMap

import java.util.*;

public class Graph {

private Map adjList = new HashMap<>();

// Add a vertex

public void addVertex(int vertex) {

adjList.putIfAbsent(vertex, new ArrayList<>());

}

// Add an undirected edge

public void addEdge(int from, int to) {

adjList.get(from).add(to);

adjList.get(to).add(from); // Undirected - add both directions

}

// BFS traversal

public void bfs(int start) {

Set visited = new HashSet<>(); Queue queue = new LinkedList<>();

queue.offer(start); visited.add(start);

while (!queue.isEmpty()) {

int node = queue.poll();

System.out.print(node + " ");

for (int neighbour : adjList.getOrDefault(node, Collections.emptyList()))

if (!visited.contains(neighbour)) {

visited.add(neighbour); queue.offer(neighbour);

}

}

}

public static void main(String[] args) {

Graph g = new Graph();

for (int v : new int[]{1,2,3,4,5}) g.addVertex(v);

g.addEdge(1,2); g.addEdge(1,3); g.addEdge(2,4); g.addEdge(3,5);

System.out.print("BFS from 1: ");

g.bfs(1); // Output: BFS from 1: 1 2 3 4 5

}

}

Java Set Data Structure

The java set data structure stores unique elements - no duplicates are allowed. Java's Set interface (part of the java.util package) has three main implementations: HashSet (unordered, O(1) operations), LinkedHashSet (insertion-ordered, O(1) operations), and TreeSet (sorted, O(log n) operations). The java set data structure is part of the Java Collections Framework.

Set Implementation

Ordering

Performance

When to Use

HashSet

No ordering - hash-based

O(1) add, remove, contains

Most common - order doesn't matter

LinkedHashSet

Insertion order maintained

O(1) add, remove, contains

When insertion order must be preserved

TreeSet

Sorted (natural or Comparator)

O(log n) all operations

When elements must be sorted automatically

// java set data structure - practical example

import java.util.*;

public class SetDemo {

public static void main(String[] args) {

// HashSet - no duplicates, unordered

Set hashSet = new HashSet<>();

hashSet.add("Java"); hashSet.add("Python"); hashSet.add("Java");

System.out.println(hashSet); // Output: [Java, Python] (no duplicate)

// LinkedHashSet - insertion order preserved

Set linkedSet = new LinkedHashSet<>();

linkedSet.add(3); linkedSet.add(1); linkedSet.add(2);

System.out.println(linkedSet); // Output: [3, 1, 2]

// TreeSet - automatically sorted

Set treeSet = new TreeSet<>();

treeSet.add(5); treeSet.add(2); treeSet.add(8); treeSet.add(1);

System.out.println(treeSet); // Output: [1, 2, 5, 8]

// Set operations - union, intersection, difference

Set setA = new HashSet<>(Arrays.asList(1,2,3,4,5)); Set setB = new HashSet<>(Arrays.asList(3,4,5,6,7)); Set union = new HashSet<>(setA); union.addAll(setB);

System.out.println("Union: " + union); // [1,2,3,4,5,6,7]

Set intersection = new HashSet<>(setA); intersection.retainAll(setB);

System.out.println("Intersection: " + intersection); // [3,4,5]

}

}

Complete Java Program Structure Example

The following java program structure example brings together every section of the basic structure of java program - documentation, package, imports, interface, class, variables, main method, and supporting methods - in a single, fully working program.

/**

* Program: StudentManagement

* Author: Hero Vired

* Version: 1.0

* Description: Complete java program structure example

*/

// Package declaration

package com.herovired.students;

// import statements in java

import java.util.ArrayList;

import java.util.List;

// Interface section

interface Printable {

void print();

}

// Class definition - java class structure

public class Student implements Printable {

// Class variable (static - shared)

private static int totalStudents = 0;

// Instance variables

private String name;

private int rollNo;

private double gpa;

// Constructor

public Student(String name, int rollNo, double gpa) {

this.name = name;

this.rollNo = rollNo;

this.gpa = gpa;

totalStudents++;

}

// Interface method implementation

@Override

public void print() {

System.out.printf("%-12s | Roll: %d | GPA: %.1f%n", name, rollNo, gpa);

}

// Utility method

public static void printAll(List students) {

System.out.println("--- Student Records ---");

students.forEach(Student::print);

System.out.println("Total: " + totalStudents);

}

// Main method - entry point of the program

public static void main(String[] args) {

List list = new ArrayList<>();

list.add(new Student("Mohan", 101, 3.8));

list.add(new Student("Priya", 102, 3.5));

list.add(new Student("Rahul", 103, 3.9));

printAll(list);

}

}

// Output:

// --- Student Records ---

// Mohan | Roll: 101 | GPA: 3.8

// Priya | Roll: 102 | GPA: 3.5

// Rahul | Roll: 103 | GPA: 3.9

// Total: 3

This java program structure example demonstrates all eight sections of the explain java program structure: documentation (Javadoc comment), package declaration, import statements in java, interface definition, class definition, class variables, main method, and supporting methods.

Conclusion

The structure of java program is a carefully ordered sequence - from the optional documentation and package sections through mandatory class definitions and the main method. Understanding every section of the basic structure of java program, including import statements in java, the java class structure, and control structure in java, equips developers to write clean, well-organised programs.

Beyond program structure, knowing Java's key data structures - including the java graph data structure and java set data structure - enables developers to solve complex algorithmic problems efficiently. Together, the code structure in java and its data structures form the complete toolkit for Java development.

To master Java programming from fundamentals to full-stack development, explore the Certificate Program in Application Development powered by Hero Vired.

People Also Ask

What is the basic structure of a Java program?

The basic structure of java program consists of eight sections in order: Documentation Section (optional comments), Package Declaration (optional namespace), Import Statements (optional - imports classes from other packages), Interface Section (optional - defines contracts), Class Definition (mandatory - all code lives inside a class), Class Variables and Identifiers (data members), Main Method (mandatory entry point - JVM starts execution here), and Methods and Behaviours (reusable logic blocks). Only the class definition and main method are mandatory for a runnable program.

What is a control structure in Java?

A control structure in java is a programming construct that controls the order in which statements are executed. Java has three categories: selection (if, if-else, switch - choose between code paths), iteration (for, while, do-while - repeat code blocks), and jump (break, continue, return - alter flow). Control structure in java is fundamental to every java program structure example - without it, programs execute only sequentially.

What does the Java class structure look like?

The java class structure follows this order inside the class body: access modifier and class keyword, optional extends/implements clause, static variables, instance variables, constructors, methods, and the main method. The java class structure embodies Java's OOP principles - encapsulation (private fields + public methods), inheritance (extends), and polymorphism (interface implementation with @Override).

What is the Java graph data structure? The java graph data structure models a collection of vertices (nodes) connected by edges. It is implemented in Java using adjacency lists (HashMap) for sparse graphs or adjacency matrices (2D array) for dense graphs. The java graph data structure supports BFS and DFS traversal and is used in social networks, routing algorithms, dependency resolution, and web crawling.
What is the Java Set data structure?

The java set data structure is a collection that stores unique elements - no duplicates permitted. Java's Set interface has three main implementations: HashSet (unordered, O(1) operations), LinkedHashSet (insertion-ordered, O(1)), and TreeSet (sorted, O(log n)). The java set data structure is part of the Java Collections Framework and is used for membership testing, deduplication, and set operations (union, intersection, difference).

FAQs
What is the structure of the Java Program?
There are elements in the structure of the Java Program. These are Sections Documentation, Package Disclosure, Import Declarations, Connector Section, Category, Definitions, Class Constants and Variables, Method Class Main.
What is Object Oriented Programming (OOP) in Java?
Java is an object-oriented programming language, and It supports four principles of OOPs such as inheritance, encapsulations, polymorphism, and abstractions are fundamental to Java Programming.
What are Packages in Java?
Packages in Java organise classes into namespaces. This helps avoid naming conflicts and provides the hierarchical structure in the Java program.
How do I declare and use variables in Java?
Java variables can be defined using a specific data type followed by a variable name. For example, int a = 2.

Updated on April 16, 2026

Link
Loading related articles...