JavaBasics

Java Program Structure

Learn the structure of a Java program including class declaration, main method, statements, comments, and coding conventions.

Java Program StructureLink to this section

Every Java program follows a fixed and well-defined structure. Understanding this structure is critical because Java is a class-based and strongly structured language.

A proper program structure improves readability, maintainability, and helps avoid compilation errors.

Core Components of a Java ProgramLink to this section

A basic Java program consists of the following components:

  • Class declaration
  • main() method
  • Executable statements
  • Comments

note

In Java, all executable code must be written inside a class.

Class DeclarationLink to this section

A class is a blueprint used to create objects. Every Java program must contain at least one class.

Code Example: Class Declaration

The class keyword is used to declare a class followed by a valid class name.

warning

Class names should follow PascalCase naming convention.

The main() MethodLink to this section

The main() method acts as the entry point of a Java application. The Java Virtual Machine (JVM) starts program execution from this method.

Meaning of keywords:

  • public – Accessible from anywhere
  • static – Allows execution without creating an object
  • void – Does not return a value
  • String[] args – Accepts command-line arguments

note

Changing the method signature will prevent the JVM from starting the program.

Java StatementsLink to this section

Statements are instructions that perform actions in a program. Each Java statement must end with a semicolon (;).

warning

Missing semicolons cause compilation errors.

Comments in JavaLink to this section

Comments improve code readability and help explain logic. They are ignored during compilation.

tip

Write comments to explain why code is written, not what it does.

Complete Java Program ExampleLink to this section

The following example shows a complete Java program structure.

note

If a class is declared as public, the file name must exactly match the class name.
Java Program Structure
Question 1 of 5

From where does the JVM start executing a Java program?

Java Program Structure

medium
  1. Create a Java program that prints your full name and age.
  2. Write a Java program with a class named WelcomeApp and display a welcome message.
  3. Add both single-line and multi-line comments to an existing Java program explaining its logic.
  4. Remove the main() method from a Java program and observe the error produced.
  5. Rename the class without changing the file name and note the compilation error.