Java Notes
Complete guide to Java program structure — package declarations, import statements, class definitions, methods, main method anatomy, and the rules for organizing Java source files.
Every Java program follows a specific structure. Understanding this structure is essential — it's not just syntax rules, it's the foundation of how Java organizes code, manages namespaces, and compiles source files.
The Complete Structure of a Java Source File
A Java source file (.java) can contain the following elements in this exact order:
Hello, Java
Breaking Down Each Section
1. Package Declaration
The package statement declares which package (namespace/folder) this class belongs to:
// Package declaration — MUST be the first non-comment line
package com.wohotech.javacourse.fundamentals;
// This means:
// - Source file is in: src/com/wohotech/javacourse/fundamentals/
// - Class full name is: com.wohotech.javacourse.fundamentals.ClassNameRules for packages:
- Must be the first statement in the file (only comments can precede it)
- Only one package declaration per file
- Uses lowercase by convention
- Follows reverse domain name convention:
com.company.project.module - Corresponds to the folder structure on disk
// Package hierarchy example:
// com.wohotech.shop.models → src/com/wohotech/shop/models/
// com.wohotech.shop.services → src/com/wohotech/shop/services/
// com.wohotech.shop.utils → src/com/wohotech/shop/utils/
package com.wohotech.shop.models;
public class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public String toString() {
return name + " ($" + price + ")";
}
}2. Import Statements
Imports allow you to use classes from other packages without their full qualified names:
package com.example.demo;
// Single class import (preferred — explicit)
import java.util.ArrayList;
import java.util.HashMap;
import java.time.LocalDate;
// Wildcard import (imports all classes in the package)
import java.util.*; // imports everything from java.util
// Static import (imports static members)
import static java.lang.Math.PI;
import static java.lang.Math.sqrt;
import static java.lang.System.out; // allows: out.println(...)
public class ImportDemo {
public static void main(String[] args) {
// Without import: java.util.ArrayList<String> list = new java.util.ArrayList<>();
// With import:
ArrayList<String> list = new ArrayList<>();
list.add("Java");
// Using static import
double radius = 5.0;
double area = PI * radius * radius; // No need for Math.PI
double diagonal = sqrt(200); // No need for Math.sqrt()
out.println("Area: " + area); // No need for System.out
out.println("Diagonal: " + diagonal);
}
}Area: 78.53981633974483 Diagonal: 14.142135623730951
Import rules:
java.lang.*is automatically imported (String, System, Math, etc.)- Imports come AFTER the package declaration
- Order doesn't matter (but IDEs organize them alphabetically)
- Wildcard
*imports only classes, not sub-packages
import java.util.*; // imports List, Map, Set, etc.
// Does NOT import java.util.stream.* — sub-packages are separate!
import java.util.stream.*; // need this separately3. Class Declaration
The class is the fundamental building block of Java programs:
// Access modifier + class keyword + class name
public class Student {
// Class body goes here
}Class declaration rules:
// A source file can have MULTIPLE classes...
// File: MyFile.java
public class MyFile { // public class MUST match filename
// Main class
}
class Helper { // non-public class — OK in same file
// Helper class
}
class AnotherHelper { // another non-public class — OK
// Another helper
}
// RULE: Only ONE public class per file, and its name MUST match the filename
// RULE: The file MUST be named after the public class: MyFile.java4. Fields (Variables)
Fields define the state of the class:
Static initializer block executed Creating employees... Instance initializer block executed Instance initializer block executed Total employees: 2
5. Constructors
Constructors initialize objects when created with new:
public class Rectangle {
private double width;
private double height;
// Default constructor (no arguments)
public Rectangle() {
this.width = 1.0;
this.height = 1.0;
}
// Parameterized constructor
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
// Constructor chaining with this()
public Rectangle(double side) {
this(side, side); // calls the two-parameter constructor
}
public double area() {
return width * height;
}
public static void main(String[] args) {
Rectangle r1 = new Rectangle(); // uses default
Rectangle r2 = new Rectangle(5, 3); // uses parameterized
Rectangle r3 = new Rectangle(4); // uses single-param (square)
System.out.println("r1 area: " + r1.area()); // 1.0
System.out.println("r2 area: " + r2.area()); // 15.0
System.out.println("r3 area: " + r3.area()); // 16.0
}
}r1 area: 1.0 r2 area: 15.0 r3 area: 16.0
6. Methods
Methods define the behavior of the class:
public class Calculator {
// Instance method
public int add(int a, int b) {
return a + b;
}
// Static method (belongs to class, not object)
public static int multiply(int a, int b) {
return a * b;
}
// Method with variable arguments (varargs)
public int sum(int... numbers) {
int total = 0;
for (int n : numbers) {
total += n;
}
return total;
}
// Method overloading (same name, different parameters)
public double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("add(3, 4) = " + calc.add(3, 4));
System.out.println("add(3.5, 4.2) = " + calc.add(3.5, 4.2));
System.out.println("multiply(5, 6) = " + Calculator.multiply(5, 6));
System.out.println("sum(1,2,3,4,5) = " + calc.sum(1, 2, 3, 4, 5));
}
}add(3, 4) = 7 add(3.5, 4.2) = 7.7 multiply(5, 6) = 30 sum(1,2,3,4,5) = 15
7. The Main Method — Entry Point
The main method is where Java starts executing your program:
// Run with: java MainMethodAnatomy Hello World 123 Arguments received: 3 args[0] = Hello args[1] = World args[2] = 123
Valid main method signatures:
// All of these are valid main methods:
public static void main(String[] args) { } // standard
public static void main(String args[]) { } // C-style array
public static void main(String... args) { } // varargs (Java 5+)
// These are NOT valid main methods (JVM won't find them):
// static void main(String[] args) { } // not public
// public void main(String[] args) { } // not static
// public static int main(String[] args) { } // not void
// public static void main() { } // no String[] parameterComplete Program Example
Here's a realistic, well-structured Java program:
=== Computer Science Department === Total students: 4 ---------------------------------------- Alice Johnson Age:20 GPA:3.80 Bob Smith Age:21 GPA:3.50 Charlie Brown Age:19 GPA:3.90 Diana Prince Age:22 GPA:3.70 Average GPA: 3.73
Source File Rules Summary
| Rule | Description |
|---|---|
| File name | Must match the public class name + .java |
| Public classes | Only ONE public class per file |
| Package | At most one, must be first statement |
| Imports | After package, before class declarations |
| Default package | If no package is declared (not recommended) |
| Case sensitivity | Java is case-sensitive: Student.java ≠ student.java |
Compilation and File Organization
// File: src/com/example/app/App.java
package com.example.app;
public class App {
public static void main(String[] args) {
System.out.println("Structured Java program!");
}
}
// Compile: javac -d out src/com/example/app/App.java
// This creates: out/com/example/app/App.class
// Run: java -cp out com.example.app.AppStructured Java program!
Standard Project Layout
Common Mistakes
- Filename doesn't match public class name —
MyClass.javamust containpublic class MyClass. This is enforced by the compiler. - Multiple public classes in one file — only one public class is allowed per
.javafile. - Package doesn't match folder structure — if you declare
package com.example;, the file must be incom/example/directory. - Forgetting that main must be
public static void— all three modifiers are required for the JVM to find the entry point. - Putting statements before the package declaration — only comments can appear before
package. - Using default package in real projects — while valid, the default (unnamed) package can't be imported by other packages. Always use named packages.
- Confusing
String[] argswithString args[]— both are valid butString[] argsis preferred Java style.
Best Practices
- One class per file — even though multiple non-public classes are allowed, one class per file is cleaner
- Match package names to folder structure — IDE does this automatically
- Use meaningful package names —
com.company.project.module - Keep main method short — delegate to other methods
- Order members consistently — fields → constructors → methods (or follow your team's convention)
- Use access modifiers intentionally — default to
private, expose only what's needed
Interview Questions
Q1: What is the structure of a Java source file?
Answer: A Java source file contains (in order): (1) Package declaration (optional, at most one), (2) Import statements (optional, zero or more), (3) Class/Interface/Enum declarations (one or more, only one can be public). The public class name must match the filename.
Q2: Why must the filename match the public class name?
Answer: This is a design choice for the compiler and JVM to easily locate class files. When you reference com.example.MyClass, the JVM knows to look for com/example/MyClass.class. This one-to-one mapping between public class names and filenames makes the class-loading mechanism straightforward.
Q3: Can you have a Java file without any public class?
Answer: Yes. A file can contain only package-private (default access) classes. In that case, the file can have any name. However, this is uncommon and not recommended — it makes code harder to navigate.
Q4: Explain each keyword in public static void main(String[] args).
Answer: public — accessible by the JVM from outside the class. static — can be called without creating an object (JVM doesn't instantiate your class). void — returns nothing to the caller (JVM doesn't expect a return value). main — the specific method name the JVM looks for. String[] args — command-line arguments passed when running the program.
Q5: What happens if you write two public classes in one file?
Answer: The compiler throws an error. Java enforces a rule: each source file can have at most one public top-level class, and the file must be named after that class. This ensures a predictable mapping between class names and file locations for the ClassLoader.
Summary
Java program structure is precise and intentional: packages organize classes into namespaces, imports provide shortcuts to other packages, and the class body contains fields, constructors, and methods. The main method serves as the entry point, and strict file-naming rules ensure the JVM can always locate your code. Mastering this structure gives you the foundation for writing clean, organized Java applications.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Java Program Structure.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Java Master Course topic.
Search Terms
java-master-course, java master course, java, master, course, fundamentals, introduction, program
Related Java Master Course Topics