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

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 |
|
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.
|
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() |
|
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. |

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.
|
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.
|
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)
|
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.
|
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.
|
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
|
Iteration Control Structure in Java – for, while, do-while
|
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 {
// 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) {
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
hashSet.add("Java"); hashSet.add("Python"); hashSet.add("Java");
System.out.println(hashSet); // Output: [Java, Python] (no duplicate)
// LinkedHashSet - insertion order preserved
linkedSet.add(3); linkedSet.add(1); linkedSet.add(2);
System.out.println(linkedSet); // Output: [3, 1, 2]
// TreeSet - automatically sorted
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
System.out.println("Union: " + union); // [1,2,3,4,5,6,7]
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
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.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 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).
What is the structure of the Java Program?
What is Object Oriented Programming (OOP) in Java?
What are Packages in Java?
How do I declare and use variables in Java?
Updated on April 16, 2026
