Structure of Java Program

In this tutorial, you will learn about structure of Java program and its various components with the help of example. Basically, a Java program involves the following components:

  • Documentation section
  • Package statement
  • Import statements
  • Interface statement
  • Class definition
  • Main method
Structure of Java program.

Documentation Section in Structure of Java Program

Documentation is the first section in the structure of Java program which consists of comment lines and descriptive text that provide information about the program, such as its name, the programmer’s name, date, and a brief description of its purpose or functionality.

Java documentation involves inline comments, block comments, and JavaDoc comments, which can be used to generate professional HTML documentation. JavaDoc comments start with /** and end with */. An example of JavaDoc comment is as follows:

/**
 * This class represents a simple HelloWorld Java program.
 */

Common JavaDoc Tags:

  • @param: Describes a method parameter.
  • @return: Describes the return value of a method.
  • @throws: Specifies exceptions thrown by a method.
  • @author: Specifies the author of the code.

Here’s a detailed example of JavaDoc comments with multiple tags:

/**
 * A simple program to demonstrate the use of JavaDoc comments.
 * This program performs basic arithmetic operations.
 *
 * <p>Features:</p>
 * <ul>
 *   <li>Addition of two numbers</li>
 *   <li>Subtraction of two numbers</li>
 *   <li>Multiplication of two numbers</li>
 *   <li>Division of two numbers</li>
 * </ul>
 *
 * @author John Doe
 * @version 1.0
 * @since 2024-12-19
 */

Package Statement in Structure of Java Program

Package statement is the first line allowed in the Java file, which is used to declare the package name. It tells the Java compiler that the classes defined within the program belong to this package.

A package in Java is a namespace that organizes classes and interfaces. Think of it as a folder that groups related classes together. Packages help to organize classes and avoid name conflicts between them. If you don’t define a package in IDE, the class automatically belongs to the default package.

An example of package declaration in Java is as follows:

package com.example.myapp;

In this example, package is a keyword. The com.example.myapp is the name of the package. It generally follows a hierarchical structure.

Hierarchical Structure:

  • com → This defines a top-level domain (TLD), which is often used as the root of the package name.
  • example → It represents the name of organization or domain.
  • myapp → It represents a specific module or application within the organization.

This hierarchy structure follows the reverse domain name convention. For example, example.com becomes com.example to ensure global uniqueness.

Import Statements

Next, import statements come in the structure of Java program, which allows you to bring classes and interfaces from other packages into your program so that you can use them without specifying their fully qualified names. It’s an essential feature for organizing and reusing code effectively.

With the import statements, you can use predefined Java classes or third-party libraries in your program.

import package_name.class_name; // Importing a specific class
import package_name.*;          // Importing all classes in a package

For example, if you want to import the Scanner class from the java.util package, then write like this:

import java.util.Scanner;

If you want to import all classes from the java.util package, write like this:

import java.util.*;

Some packages are automatically imported into every Java program. For example, java.lang.*: contains fundamental classes like String, Math, System, etc. which are automatically imported into every Java program.

Interface Statement

An interface is like a class that defines a set of method declaractions. This is an optional section in the Java program structure and can be used only when you want to implement multiple inheritance(s) or asbtraction within the program. The general syntax to declare an interface is as:

access_modifier interface InterfaceName {
   // Constant variables
   // Abstract methods
   // Default methods (Java 8+)
   // Static methods (Java 8+)
   // Private methods (Java 9+)
}

You will learn more about the interface in the further chapter.

Class Definition

A class is main and important element of any Java program. It is a template or blueprint that explains the states/behaviors that an object of its type support. A Java program can contain multiple class definitions. However, every Java program must have at least one class declaration. The class keyword is used to define a class. The general syntax to define a class in Java program is as follows:

public class Main {
    // Class body
    // Data members
   // Methods
}

You must note that every class definition in a Java program must start with an opening brace ({) and end with a matching closing brace (}).

Read More: Class in Java with Example

Main Method

Every Java program needs a main method that indicates the starting point to execute the Java program. This is the the first method that the Java Virtual Machine (JVM) executes when running a program. Without a properly defined main method, a Java program will not execute.

A application program can have multiple classes, but only one class should have the main method to act as the entry point. The basic syntax to define a main method in a Java program is as follows:

public static void main(String[] args) {
    // Code to execute
}

In the above syntax of main method,

  • public: This is an access modifier that specifies that the main method is accessible from anywhere.
  • static: This is a keyword indicating that the main method belongs to the class, not an instance. The JVM can call the main method without creating an object of the class.
  • void: This is a keyword which specifies that the method does not return any value. The JVM does not expect any output from the main method.
  • main: This is the name of the method. It is predefined and recognized by the JVM as the starting point of execution.
  • String[] args: This represents an array of String arguments passed to the program via the command line. It allows users to pass data into the program at runtime.

General Structure of a Java Program

A Java program has a standard structure that organizes the components of the code in a logical and functional order. Understanding this structure helps in writing, debugging, and maintaining Java programs effectively.

Components of a Java Program

Here is the general structure of a Java program with explanations for each component:

// 1. Documentation Section
/**
 * This is a sample Java program.
 * Author: Saanvi Kumari
 * Date: December 19, 2024
 * Description: An example of a simple Java program structure.
 */

// 2. Package Declaration
package com.example.myapp;

// 3. Import Statements
// This allows the program to use the Scanner class.
import java.util.Scanner; 

// 4. Class Declaration
public class SampleProgram {

 // 5. Data Fields/Variables
    private String message = "Hello, Java!";

 // 6. Constructor
    public SampleProgram() {
        System.out.println("Constructor definition.");
    }

 // 7. Methods
    public void displayMessage() {
        System.out.println(message);
    }
 // 8. Main Method
    public static void main(String[] args) {
        System.out.println("Program started.");

     // Create an object of the class
        SampleProgram program = new SampleProgram();
        program.displayMessage();
        System.out.println("Program ended.");
    }
}
Output:
     Program started.
     Constructor definition.
     Hello, Java!
     Program ended.

In this example, we have a documentation section that describes the purpose, author, version, and other details of the program. Next, we have declared package name and import statement.

After that, we have defined a class using a keyword Class with a public access modifier. Note that the class name must match the file name if it is declared public. Inside the class, we have declared fields or variables to store data or state information for the object.

After that declaration of field, we have declared a constructor which have the same name as that of class. Then, we have declared a method to display the output. Next, we have declared main method in which we have created an object of the class and accessed members of the class.

Example 2:

/**
 * This is a simple Java program to demonstrate the general structure.
 * Author: Shanvika Kumari
 * Date: December 19, 2024
 */
package myProgram;
public class Person {
 // Instance variable.
	String name;
//  Constructor declaration.
    public Person(String name) {
        this.name = name;
    }
 // Method declaration.   
    public void displayInfo() {
        System.out.println("Name: " + name);
    }
 // Main method.   
   public static void main(String[] args) {
   // Creating an object of class Person.	   
      Person person = new Person("Shanvika");
      person.displayInfo(); // Calling method.
    }
}
Output:
     Name: Shanvika

Best Practices for Java Program Structure

There are some key points for the structure of Java program that you should keep in mind. They are:

  • Always use meaningful package names to group related classes and avoid name conflicts.
  • Choose descriptive names for classes, methods, and variables according to task perform.
  • Add necessary simple comments to explain the purpose of complex code.
  • Use camelCase for naming classes, variables and methods.

Please Share Your Love.

Leave a Reply

Your email address will not be published. Required fields are marked *