Java Program Structure Tutorial: Classes, main() Method, Packages, Imports and Syntax
Introduction
Understanding the Java program structure is one of the first steps in learning Java programming. Before learning variables, data types, operators, methods, and object-oriented programming, you should understand how a Java source file is organized.
A Java program is generally organized using classes, methods, packages, imports, statements, comments, keywords, and identifiers. The JVM starts a conventional Java application through its main() method.
For beginners, understanding these building blocks makes it easier to read, write, compile, debug, and maintain Java programs.
In this tutorial, you will learn:
- Java program structure
- Java classes
- The
main()method - Java packages
- Import statements
- Java comments
- Java keywords
- Java identifiers
- Java naming conventions
- Complete Java program examples
- Common Java syntax rules
- Practice exercises
By the end of this tutorial, you will be able to create a basic, well-structured Java program and understand the purpose of each major part of the source code.
Table of Contents
- Java Program Structure
- Java Class
- main() Method
- Java Package
- Java Import Statement
- Comments in Java
- Java Keywords
- Java Identifiers
- Java Naming Conventions
- Complete Java Program Example
- Hello World Java Program
- Student Information Program
- Common Java Program Structure Rules
- Summary
- Practice Exercises
- Frequently Asked Questions
Java Program Structure
A basic Java program can contain a package declaration, import statements, a class declaration, methods, and executable statements.
Example:
1package com.example; 2 3import java.util.Scanner; 4 5public class HelloWorld { 6 7 public static void main(String[] args) { 8 System.out.println("Hello, World!"); 9 } 10 11}
This Java program contains several important components:
- Package declaration
- Import statement
- Class declaration
main()method- Java statement
Not every Java file must contain all of these components. For example, a simple Java program may not require a package or import statement.
Basic Java Program Structure
1Package Declaration 2 │ 3 ▼ 4Import Statements 5 │ 6 ▼ 7Class Declaration 8 │ 9 ▼ 10Methods 11 │ 12 ▼ 13Java Statements
Understanding this structure helps beginners understand how Java source files are organized.
Java Class
A class is one of the fundamental building blocks of Java programming.
A class defines the structure and behavior of objects. It can contain:
- Variables
- Methods
- Constructors
- Nested classes
- Initialization blocks
Java Class Syntax
1public class Student { 2 3}
Here:
publicis an access modifier.classis a Java keyword.Studentis the class name.{ }contains the class body.
Java Class Example
1public class Car { 2 3 String model; 4 5 void start() { 6 System.out.println("Car started"); 7 } 8 9}
The Car class contains a variable named model and a method named start().
Java Class Naming Rule
By convention, Java class names use PascalCase.
Examples:
1Student 2BankAccount 3EmployeeManager 4OnlinePayment 5StudentInformation
If a top-level class is declared public, the source file name must match the class name.
For example:
1Student.java
should contain:
1public class Student { 2 3}
A mismatch between the public class name and file name causes a compilation error.
main() Method in Java
The main() method is the conventional entry point for a standalone Java application launched by the Java launcher.
A commonly used declaration is:
1public static void main(String[] args) { 2 3}
When you run a class as an application, the Java launcher looks for a compatible main method.
Understanding the main() Method
Consider:
1public static void main(String[] args) { 2 3}
Each part has a purpose.
public
1public
public is an access modifier. It allows the method to be accessible from outside the class.
static
1static
static means the method belongs to the class rather than a particular object instance.
This allows the Java launcher to invoke the method without first creating an instance of the class.
void
1void
void indicates that the method does not return a value.
main
1main
main is the conventional method name recognized by the Java launcher for starting an application.
String[] args
1String[] args
This parameter contains command-line arguments supplied when launching the application.
Example
1public class Hello { 2 3 public static void main(String[] args) { 4 5 System.out.println("Welcome to Java!"); 6 7 } 8 9}
Output:
1Welcome to Java!
Command-Line Arguments Example
1public class Arguments { 2 3 public static void main(String[] args) { 4 5 System.out.println("First argument: " + args[0]); 6 7 } 8 9}
Run:
1java Arguments Java
Output:
1First argument: Java
Java Package
A package is used to organize related Java classes and interfaces.
Packages provide a namespace that helps avoid naming conflicts and makes large applications easier to organize.
Package Syntax
1package com.tech3space;
The package declaration normally appears before import declarations and the type declarations in a source file.
Package Example
1package com.school; 2 3public class Student { 4 5 public void display() { 6 System.out.println("Student information"); 7 } 8 9}
Benefits of Packages
Packages provide several benefits:
- Better code organization
- Namespace management
- Easier maintenance
- Better project structure
- Access control
- Reusable code organization
Types of Java Packages
Java applications commonly use both standard library packages and developer-created packages.
Built-in Java Packages
The Java platform provides many packages.
Examples include:
1java.lang 2java.util 3java.io 4java.net 5java.time
For example, the java.util package contains commonly used utility classes.
User-Defined Packages
Developers can create their own packages.
Example:
1package com.company.project;
A project might be organized like:
1com.company.project 2├── model 3├── service 4├── controller 5└── util
This type of organization is particularly useful in larger Java applications.
Java Import Statement
The import declaration allows source code to refer to types by their simple names instead of using their fully qualified names.
For example:
1import java.util.Scanner;
After importing Scanner, you can write:
1Scanner input = new Scanner(System.in);
instead of:
1java.util.Scanner input = new java.util.Scanner(System.in);
Java Import Example
1import java.util.Scanner; 2 3public class UserInput { 4 5 public static void main(String[] args) { 6 7 Scanner input = new Scanner(System.in); 8 9 System.out.println("Enter your name:"); 10 11 String name = input.nextLine(); 12 13 System.out.println("Hello, " + name); 14 15 input.close(); 16 } 17 18}
Importing Multiple Types
You can import individual classes:
1import java.util.Scanner; 2import java.util.ArrayList; 3import java.util.HashMap;
You can also use a wildcard import:
1import java.util.*;
However, explicitly importing the types used by your source code can make dependencies easier to understand.
Important Note About java.lang
Classes from java.lang are automatically available without an explicit import.
For example, you can use:
1String 2System 3Math 4Object
without writing:
1import java.lang.String;
Comments in Java
Comments are used to explain source code, document decisions, and improve readability.
Comments are not executed as Java statements.
Java supports:
- Single-line comments
- Multi-line comments
- Documentation comments
Single-Line Comments
A single-line comment begins with //.
1// This is a single-line comment 2 3System.out.println("Hello");
Everything after // on that line is treated as a comment.
Example
1public class Example { 2 3 public static void main(String[] args) { 4 5 // Print a welcome message 6 System.out.println("Welcome to Java!"); 7 8 } 9 10}
Multi-Line Comments
Multi-line comments begin with /* and end with */.
1/* 2 This is a 3 multi-line comment. 4*/
Example
1public class Example { 2 3 public static void main(String[] args) { 4 5 /* 6 * Display a message 7 * to the user. 8 */ 9 10 System.out.println("Hello, Java!"); 11 12 } 13 14}
Documentation Comments in Java
Documentation comments use /** and are commonly processed by the Javadoc tool.
Example:
1/** 2 * Calculates the total price. 3 * 4 * @param price item price 5 * @param quantity number of items 6 * @return total price 7 */ 8public double calculateTotal(double price, int quantity) { 9 10 return price * quantity; 11 12}
Javadoc comments are especially useful when creating reusable libraries and APIs.
Java Keywords
Java keywords are reserved words that have predefined meanings in the Java language.
You cannot use a keyword as the name of a variable, method, class, or other identifier where the language prohibits it.
Common Java Keywords
| Keyword | Purpose |
|---|---|
class | Declares a class |
public | Access modifier |
private | Access modifier |
protected | Access modifier |
static | Declares a class-level member |
void | Indicates no return value |
return | Returns from a method |
new | Creates an object |
if | Conditional statement |
else | Alternative conditional branch |
switch | Multi-way selection |
for | Loop |
while | Loop |
do | Used with a do-while loop |
break | Terminates a loop or switch |
continue |
Invalid Keyword Example
1int class = 10;
This produces a compilation error because class is a reserved Java keyword.
Java Identifiers
An identifier is a name used to identify a program element such as a:
- Class
- Variable
- Method
- Interface
- Package
- Field
Examples:
1studentName 2totalMarks 3Employee 4calculateSalary 5MAX_SIZE
Java Identifier Rules
Java identifiers:
- Can contain letters.
- Can contain digits, but cannot begin with a digit.
- Can contain
_. - Can contain
$, although using$in ordinary application code is generally discouraged by convention. - Cannot contain spaces.
- Cannot be Java keywords.
- Are case-sensitive.
Valid Java Identifiers
1student 2Student 3student1 4_student 5$value
Invalid Java Identifiers
11student 2student name 3class 4total-marks
For example:
1int studentAge = 20;
is valid, while:
1int student age = 20;
is invalid because spaces are not allowed in identifiers.
Java Naming Conventions
Naming conventions are not simply syntax rules. They are recommended practices that make Java code easier to read and maintain.
Class Names
Use PascalCase for class names.
Examples:
1Student 2BankAccount 3EmployeeManagement 4OnlinePayment
Method Names
Use camelCase for methods.
Examples:
1calculateSalary() 2printDetails() 3getName() 4calculateTotal()
Variable Names
Use camelCase for variables.
Examples:
1studentName 2totalMarks 3userAge 4accountBalance
Constants
Constants are commonly written using UPPER_SNAKE_CASE.
Examples:
1MAX_SIZE 2DEFAULT_TIMEOUT 3MINIMUM_BALANCE
A typical Java constant is declared using static final:
1public static final int MAX_SIZE = 100;
Package Names
Package names are normally written in lowercase.
Examples:
1com.tech3space 2com.example.project 3org.company.application
Complete Java Program Example
The following example combines several concepts from this tutorial.
1package com.tech3space; 2 3public class Student { 4 5 public static void main(String[] args) { 6 7 // Student information 8 String name = "Ankit"; 9 int age = 23; 10 String course = "Computer Science"; 11 12 System.out.println("Student Information"); 13 System.out.println("-------------------"); 14 System.out.println("Name : " + name); 15 System.out.println("Age : " + age); 16 System.out.println("Course : " + course); 17 18 } 19 20}
Output
1Student Information 2------------------- 3Name : Ankit 4Age : 23 5Course : Computer Science
This example contains:
- A package declaration
- A class
- The
main()method - A comment
- Variables
- Java statements
- String concatenation
System.out.println()
Hello World Java Program
The traditional first Java program is the Hello World program.
Create a file named:
1HelloWorld.java
Add:
1public class HelloWorld { 2 3 public static void main(String[] args) { 4 5 System.out.println("Hello, World!"); 6 7 } 8 9}
Compile it:
1javac HelloWorld.java
Run it:
1java HelloWorld
Output:
1Hello, World!
This simple program demonstrates the minimum structure required for a conventional Java application.
Student Information Program
Here is another beginner-friendly example:
1public class StudentInformation { 2 3 public static void main(String[] args) { 4 5 String name = "Rahul"; 6 int age = 20; 7 String city = "Delhi"; 8 9 System.out.println("Student Details"); 10 System.out.println("----------------"); 11 System.out.println("Name : " + name); 12 System.out.println("Age : " + age); 13 System.out.println("City : " + city); 14 15 } 16 17}
Output:
1Student Details 2---------------- 3Name : Rahul 4Age : 20 5City : Delhi
This example introduces variables along with the basic structure of a Java class and main() method.
Common Java Program Structure Rules
Keep the following rules in mind when writing Java programs:
Rule 1: Match a public class with its file name
If you have:
1public class Student { 2 3}
the file should be:
1Student.java
Rule 2: Use the correct package location
If the source contains:
1package com.example.demo;
the source file should normally be located according to the project's package and source-directory structure.
Rule 3: Use imports when required
For example:
1import java.util.Scanner;
allows the source file to refer to Scanner by its simple name.
Rule 4: Follow Java naming conventions
Use:
1PascalCase → Classes 2camelCase → Methods and variables 3UPPER_SNAKE_CASE → Constants 4lowercase → Packages
Rule 5: Use comments appropriately
Comments should explain important logic or decisions rather than unnecessarily describing every obvious line.
Java Program Structure vs Java Program Execution
It is useful to distinguish between program structure and program execution.
Program structure describes how Java source code is organized:
1Package 2 ↓ 3Imports 4 ↓ 5Class 6 ↓ 7Methods 8 ↓ 9Statements
Program execution describes what happens when the application runs:
1.java Source File 2 ↓ 3 javac 4 ↓ 5.class Bytecode 6 ↓ 7 JVM 8 ↓ 9 Execution 10 ↓ 11 Output
Understanding both concepts will make later Java topics easier to learn.
Summary
In this Java program structure tutorial, you learned:
- What the structure of a Java program looks like
- What a Java class is
- How the
main()method works - How Java packages organize source code
- How import declarations are used
- How to write single-line and multi-line comments
- How Javadoc comments work
- What Java keywords are
- What Java identifiers are
- The rules for valid identifiers
- Java naming conventions
- How to write a complete Java program
- How to create a Hello World program
- How to compile and run a Java program
- Common Java program structure rules
These concepts provide the foundation for learning Java variables, data types, operators, input/output, conditional statements, loops, methods, arrays, and object-oriented programming.
Practice Exercises
Exercise 1: Hello World
Create a Java program named HelloWorld.java that prints:
1Welcome to Java Programming!
Exercise 2: Student Information
Create a Java program that displays:
- Student name
- Age
- Course
- College
Use variables and System.out.println().
Exercise 3: Java Comments
Write a Java program containing:
- A single-line comment
- A multi-line comment
- A Javadoc comment
Exercise 4: Package and Import
Create a package named:
1com.example.demo
Create a Java class inside the package and import:
1java.util.Scanner
Use Scanner to read a value from the user.
Exercise 5: Naming Conventions
Create the following using standard Java naming conventions:
- Class:
BankAccount - Method:
depositMoney - Variable:
accountBalance - Constant:
MINIMUM_BALANCE - Package:
com.bank.application
Exercise 6: Identify Program Components
Look at the following code and identify the package, import, class, method, variable, comment, and statement:
1package com.example; 2 3import java.util.Scanner; 4 5public class Student { 6 7 public static void main(String[] args) { 8 9 // Student name 10 String name = "Rahul"; 11 12 System.out.println(name); 13 14 } 15 16}
Exercise 7: Fix the Errors
Find and correct the errors in this code:
1public class student information { 2 3 public static void main(String args) { 4 5 int class = 10; 6 7 System.out.println(class); 8 9 } 10 11}
Frequently Asked Questions
What is the basic structure of a Java program?
A Java source file can contain a package declaration, import declarations, class or interface declarations, fields, constructors, methods, and statements.
What is a class in Java?
A class is a fundamental Java type that defines the structure and behavior of objects.
What is the main() method in Java?
The main() method is the conventional entry point used when launching a Java application.
What is a package in Java?
A package is a namespace used to organize related Java types and avoid naming conflicts.
What is an import statement in Java?
An import declaration allows a Java source file to refer to imported types by their simple names.
What are Java keywords?
Java keywords are reserved words with predefined meanings in the Java language, such as class, public, static, if, and return.
What is an identifier in Java?
An identifier is a name used for Java program elements such as classes, methods, variables, fields, and packages.
What are Java naming conventions?
Java naming conventions are recommended practices for naming classes, methods, variables, constants, and packages. Common conventions include PascalCase for classes, camelCase for methods and variables, and UPPER_SNAKE_CASE for constants.