Java Program Structure
Table of Contents + β
In the last lesson you wrote your first Java program. Now letβs map out its parts properly. Once you can see the structure clearly, every program becomes easy to read.
πΊοΈ The big picture
Every Java program follows the same fixed shape, and Java is strict about it. Here is the full layout, labelled in comments.
// 1. Optional package linepackage com.example;
// 2. Optional importsimport java.util.Scanner;
// 3. A classpublic class Welcome {
// 4. The main method (the start point) public static void main(String[] args) {
// 5. Statements (the actual work) System.out.println("Welcome to Java!"); }}That is the whole skeleton. Think of it like a letter:
- Package line β the return address at the top.
- Imports β the tools you lay out before starting.
- Class β the envelope that holds everything.
mainmethod β the opening line where the reader begins.- Statements β the actual message.
The order is fixed: package, then imports, then class. You cannot shuffle them. Most small programs skip the package and import lines and keep just the class, main, and a few statements.
π¦ Packages
A package is a folder for your classes. It goes on the very first line.
// This must be the first real line in the file.package com.example;The name com.example is a website address written backwards, the habit Java teams follow. Each dot is a deeper folder, so com.example.bank is bank inside example inside com.
- They organise code. Packages sort hundreds of classes into groups, like folders sort files.
- They prevent name clashes.
com.example.Userandcom.shop.Userare different things, so two classes can share the nameUser. - The disk folder must match. A class in
com.examplemust sit in folder pathcom/example, or it will not compile. - Small programs can skip them. Leave the line out and Java uses a default unnamed package. Fine while learning.
π₯ Imports
An import brings in ready-made code so you can use it. It goes near the top, after the package line and before the class.
// This lets us use the Scanner tool in our code below.import java.util.Scanner;This says βI want the Scanner tool, which lives in java.utilβ. Without it, Java cannot find Scanner and you get a compile error.
- Imports unlock ready-made tools. Reading input, dates, lists β the hard part is already written. Import it, then use it.
- You import the full path once. After that you write the short name
Scanner, notjava.util.Scannerevery time. - You only import what you need. Each import names one tool. Your editor usually adds them as you type.
- One package is always free. Everything in
java.lang, likeStringandSystem, is imported automatically. That is whySystem.out.printlnneeds no import.
ποΈ The class
The class is the main container. In Java, all your code must live inside a class β no loose code floating outside.
public class Welcome { // everything goes inside here}Everything between the opening { and matching } belongs to the class.
publicmeans it is open. Other code can use this class. Starter programs are usually public.- The name uses PascalCase. Start with a capital, capitalise each word, no spaces β
WelcomeorBankAccount. - The file name must match. A public class
Welcomemust sit inWelcome.java, same spelling and capitals. This trips up many beginners.
πͺ The main method
Inside the class sits the main method, the front door where the program starts. The JVM (the program that runs Java) looks for main and begins there.
public static void main(String[] args) { // your statements go here}A quick reminder of each word:
publiclets the JVM reach it from outside the class.staticlets it run without creating an object first β the JVM callsmainbefore anything exists.voidmeans it returns nothing.mainis the exact name the JVM searches for. Spell it differently and the program will not start.String[] argsholds extra input passed from the command line.
For now, type this line exactly. One wrong word and you get βmain method not foundβ.
βοΈ Statements
Inside main you write statements β single instructions that run in order, top to bottom. Each ends with a semicolon, which tells Java one instruction has finished.
public class Welcome { public static void main(String[] args) { System.out.println("Line one"); System.out.println("Line two"); System.out.println("Line three"); }}Java runs these top to bottom, so the output comes out in the same order.
Output
Line oneLine twoLine threeThe semicolon is easy to forget, so two quick notes:
- It ends a statement, not a line. Java ignores line breaks; the semicolon is the real full stop. One long statement can span several lines as long as it ends with
;. - Forgetting it is the most common early error. Java reads your next line as part of the same statement and gets confused. The error often points at the line after the broken one.
π§± Blocks and braces
A pair of curly braces { } makes a block β a group of code that belongs together. Braces hold the whole structure together.
public class Welcome { // class block opens public static void main(String[] args) { // method block opens System.out.println("Inside main"); } // method block closes} // class block closesBlocks nest like boxes inside boxes β the method block sits inside the class block.
- Every
{needs a matching}. Open a block, you must close it. - Indentation shows the nesting. Java ignores spacing, but humans need it. Each level moves right, so you see what is inside what.
- Braces decide where things live. A statement between method braces belongs to the method; a method between class braces belongs to the class.
When braces line up neatly, a missing one jumps out. When they are messy, it can hide for a long time.
π« Naming conventions
You can name classes, methods, and variables almost anything, but teams follow shared naming conventions so code stays readable and looks right to every Java developer.
public class BankAccount { // β
PascalCase for class names public static void main(String[] args) { int accountBalance = 100; // β
camelCase for variable names printBalance(); // β
camelCase for method names }}The two styles you will use constantly:
- PascalCase for classes. Capital first, capitalise each word β
BankAccount,UserProfile. No spaces or underscores. - camelCase for methods and variables. Small first letter, then capitalise each later word β
accountBalance,printBalance. The first letter is the only difference from PascalCase. - Names should describe the thing.
accountBalancetells you what it holds;xordatamakes the reader guess.
The compiler does not check these, so your code still runs. But ignore them and other developers trust it less.
π¬ Comments
A comment is a note for humans that Java ignores. You use it to explain why your code does something. Java has two kinds.
// This is a single-line comment. It runs to the end of the line.
/* This is a multi-line comment. It can span many lines. Good for longer notes.*/
System.out.println("Comments do not affect this line.");How to use them well:
- Single-line comments start with
//. Use them for short notes beside a line. - Multi-line comments sit between
/*and*/. Use them for longer explanations. - Explain the why, not the obvious. Skip notes like
// print hellothat just repeat the code.
Comments help the next person who reads your code β often that person is you, months later.
π A fully annotated program
Letβs put every part together. This program greets a user and adds two numbers.
package com.example; // 1. package: the folder this class lives in
import java.util.Scanner; // 2. import: lets us read keyboard input
// 3. class: the container for all our codepublic class Greeter {
// 4. main method: where the program starts public static void main(String[] args) {
// 5. statements begin here, running top to bottom Scanner input = new Scanner(System.in); // make a tool to read input
System.out.print("Enter your name: "); // ask for a name String name = input.nextLine(); // store what the user types
int total = 7 + 3; // do a small calculation
System.out.println("Hello, " + name); // greet the user by name System.out.println("7 + 3 = " + total); // show the result }}Reading it from the top, the way the JVM does:
- The package line puts this class in the
com.examplefolder, first as the rule demands. - The import line pulls in
Scannerto read what the user types. - The class
Greeteropens its block; everything below belongs to it. - The main method opens next. The JVM starts here.
- The statements run in order: build a
Scanner, ask for a name, store it, add two numbers, print two lines. - The braces close in reverse: method first, then class.
Here is what you would see if you typed βRiyaβ.
Output
Enter your name: RiyaHello, Riya7 + 3 = 10Every Java program follows this same skeleton. Only the details change.
β οΈ Common Mistakes
A few structure slip-ups catch beginners again and again.
Code outside a class will not compile. Every statement must live inside a class.
// β Wrong: a statement floating outside any classSystem.out.println("Hello");
public class Welcome {}// β
Right: the statement lives inside main, inside the classpublic class Welcome { public static void main(String[] args) { System.out.println("Hello"); }}Forgetting a closing brace breaks the structure. Each { needs a matching }.
// β Wrong: the main method block is never closedpublic class Welcome { public static void main(String[] args) { System.out.println("Hello");}// β
Right: every brace has its partnerpublic class Welcome { public static void main(String[] args) { System.out.println("Hello"); }}The file name must match a public class name exactly.
// β Wrong: this class is named Welcome but the file is Hello.javapublic class Welcome {}// β
Right: a public class named Welcome lives in Welcome.javapublic class Welcome {}Finally, watch the top order: package first, then imports, then class. You cannot put an import inside main or the package line after the class.
β Best Practices
A few habits keep your code clean and easy to read.
- Match the file name to the class. Same name, same capitals β avoids the most common build error.
- Indent every block. Each level moves right, making the structure visible and missing braces easy to spot.
- Follow the naming styles. PascalCase for classes, camelCase for methods and variables.
- End every statement with a semicolon. Make it a reflex. A missing one on the line above is a common cause of confusing errors.
- Comment the why, not the what. Save comments for reasons, not a replay of the code.
π§© What Youβve Learned
Now you can read the shape of any Java program.
- β
A Java program has an optional package, optional imports, a class, the
mainmethod, and statements, in that fixed order. - β A package groups classes, and an import lets you use ready-made tools.
- β All code lives inside a class, and the program starts from the main method.
- β Statements are single instructions that run top to bottom, each ending with a semicolon.
- β
Braces
{ }make blocks, and every{needs a matching}. - β Classes use PascalCase, while methods and variables use camelCase.
- β
Comments (
//and/* */) are notes for humans that Java ignores.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
Where must all Java code live?
Why: In Java, all code must sit inside a class. There is no loose code floating outside one.
- 2
What is the job of an import statement?
Why: An import brings in a tool that already exists, like Scanner, so you can use it in your code.
- 3
In what order do statements inside main run?
Why: Statements run in order, from top to bottom, one after another.
- 4
Which naming style is used for Java class names?
Why: Class names use PascalCase: start with a capital and capitalise each word, like BankAccount.
π Whatβs Next?
You can now read the shape of any Java program. Next letβs look at comments more closely, so you can write clear notes in your code and even build proper documentation for it.