Understanding the structure of a Java program is the foundation of learning the language. Java follows a strict syntax and organizational style that ensures consistency and clarity, making code easier to read, maintain, and compile. Every Java program is composed of classes and methods, with a designated entry point—the main
method—where execution begins.
Let's start with a minimal Java program:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}
This small example includes all the essential building blocks of a Java application. Let's break it down:
public class HelloWorld
Every Java application must have at least one class. In Java, everything resides within a class, even the entry point to the program. Here, HelloWorld
is the name of the class. The keyword public
makes it accessible from outside the class, including the Java Virtual Machine (JVM), which needs to invoke it.
HelloWorld
, the file must be named HelloWorld.java
.class
is used to define the class.public static void main(String[] args)
This is the entry point of any standalone Java application. The JVM looks for this exact method signature to start the program.
public
: So the method is accessible to the JVM.static
: It allows the JVM to call the method without creating an instance of the class.void
: Indicates that this method does not return a value.main
: This is the predefined method name.String[] args
: This is a parameter array that holds command-line arguments passed to the program.Without this method, the program will compile but not run.
{ }
Java uses curly braces to define blocks of code:
{ ... }
{ ... }
Each opening brace must be matched by a closing brace. This block structure defines scope, and misplacing or omitting braces results in a compile-time error.
System.out.println("Hello, Java!");
This is a statement that prints a line of text to the console. It uses the System.out
output stream and calls its println()
method to display the message.
;
).main
Method Syntaxmain
Method SyntaxThe main
method is the entry point of any standalone Java application. When you run a Java program, the Java Virtual Machine (JVM) looks specifically for this method to start executing your code. Because of this, its syntax must be exact.
Here is the correct syntax for the main
method:
public static void main(String[] args) {
// program statements go here
}
Let's break down each part of this declaration:
public
: This access modifier means the method is visible to all other classes, including the JVM. Since the JVM needs to call this method from outside your class, it must be public
.
static
: This keyword means the method belongs to the class itself, not to an instance of the class. The JVM calls the main
method without creating an object of the class, so static
is mandatory.
void
: This indicates that the method does not return any value.
main
: This is the exact method name the JVM looks for when starting a program.
String[] args
: This is the method parameter—a single argument that is an array of String
objects. It contains any command-line arguments passed to the program when it starts.
static
A very common mistake is to forget the static
keyword:
public void main(String[] args) { // Incorrect!
// ...
}
This compiles but will result in a runtime error: Error: Main method not found in class ...
Because without static
, the JVM would need to create an instance of the class before calling main
, but it cannot do this on its own.
The main
method is special because it signals where the Java program begins. Its exact signature is required by the JVM to correctly locate and invoke it. This design enforces consistency, allowing the JVM to start any Java program in a predictable way. As you continue learning Java, remember that while you can create many other methods with different names and signatures, the main
method is your program's official starting point.
In Java, classes are the fundamental building blocks of programs. Understanding how to declare classes and how they relate to your source files is crucial for writing well-structured code.
A class declaration typically looks like this:
public class MyClass {
// class body
}
class
is followed by the class name, which should follow Java naming conventions: start with a capital letter and use camel case (e.g., MyClass
, EmployeeData
).public
access modifier means this class can be accessed from anywhere.When a class is declared public
, the name of the file must exactly match the class name and end with .java
. For example, if your class is:
public class MyClass { }
then the filename must be MyClass.java
. This rule is enforced by the Java compiler and is crucial for correct compilation and program organization.
Class Declaration | Filename | Valid? |
---|---|---|
public class HelloWorld |
HelloWorld.java |
✅ Valid |
class HelloWorld |
HelloWorld.java |
✅ Valid (no public) |
public class HelloWorld |
helloWorld.java |
❌ Invalid (case mismatch) |
public class HelloWorld |
Hello.java |
❌ Invalid (name mismatch) |
Java allows multiple classes in a single .java
file, but only one of them may be declared public
, and if so, the file name must match that public class.
For example, this is valid in a file named MainApp.java
:
public class MainApp {
public static void main(String[] args) {
System.out.println("Hello from MainApp");
}
}
class Helper {
void assist() {
System.out.println("Helping...");
}
}
MainApp
is public, and the file is named MainApp.java
.Helper
class is package-private (no access modifier) and can only be accessed within the same package.public
, the filename can be anything, but this is uncommon for programs with an entry point.In Java, a statement is a complete unit of execution—something the program does, such as declaring a variable or calling a method. Most statements end with a semicolon (;
), which tells the compiler where one statement finishes and the next begins.
int number = 10; // variable declaration statement
number = number + 5; // assignment statement
System.out.println(number); // method call statement
Each of these lines is a statement and must end with a semicolon. Missing a semicolon causes a compile-time error because the compiler cannot determine where the statement ends.
A block is a group of statements enclosed in curly braces {}
. Blocks are used to define the body of methods, classes, and control structures like loops and conditionals.
Example:
if (number > 10) {
System.out.println("Number is greater than 10");
number = 10;
}
Here, the two statements inside the {}
form a block that executes only if the condition is true.
Blocks can be nested and help organize code logically.
if
, for
, or while
before their blocks; doing so ends the statement prematurely and can cause unexpected behavior.Incorrect example:
if (number > 10); { // Incorrect semicolon here!
System.out.println("This always prints");
}
Java does not enforce indentation or whitespace, but proper formatting is crucial for human readers. Using consistent indentation and clear block organization makes code easier to understand and maintain. Blocks clearly indicate the scope of statements and control flow. While semicolons are small punctuation marks, they are fundamental to Java's syntax; missing or misplaced semicolons are a frequent cause of compilation errors for beginners. Paying attention to statements, blocks, and semicolons early will build a strong foundation for writing syntactically correct Java programs.
Java programs can accept input parameters when started from the command line. These inputs, called command-line arguments, are passed to the main
method as an array of strings: String[] args
.
String[] args
The parameter args
in the main
method holds all command-line arguments as strings. You can access them by their index, starting at args[0]
.
Here is an example program that prints all command-line arguments:
public class PrintArgs {
public static void main(String[] args) {
System.out.println("Number of arguments: " + args.length);
for (int i = 0; i < args.length; i++) {
System.out.println("Argument " + i + ": " + args[i]);
}
}
}
To run this program from the terminal:
javac PrintArgs.java
java PrintArgs hello world 123
Output:
Number of arguments: 3
Argument 0: hello
Argument 1: world
Argument 2: 123
Each word after the class name is treated as a separate argument and passed to the args
array.
Comments are lines in your code that the Java compiler ignores. They help programmers explain what the code does, making it easier to read and maintain.
//
and continue to the end of the line:// This is a single-line comment
int number = 10; // Inline comment after a statement
/*
and */
and can span multiple lines:/*
This is a multi-line comment.
It can cover several lines.
*/
/** ... */
and are specially formatted for generating documentation:/**
* This method prints a greeting message.
* @param name the name to greet
*/
public void greet(String name) {
System.out.println("Hello, " + name);
}
JavaDoc comments help create API documentation and should be used on classes, methods, and important fields.
Comments should explain why something is done, clarify complex logic, or provide context—not just restate what the code clearly shows. Over-commenting trivial code or outdated comments can confuse readers. Good comments improve collaboration and ease future maintenance.
public class Example {
public static void main(String[] args) {
// Print a welcome message
System.out.println("Welcome to Java Syntax!");
/*
* Initialize a counter and increment it.
* This simulates a simple loop without actual looping.
*/
int counter = 0;
counter++;
System.out.println("Counter value: " + counter);
}
}
Consistent indentation and clean formatting are essential for readability, even though Java ignores whitespace. Use comments thoughtfully to guide readers without cluttering code. Clear structure and meaningful comments make your code professional and easier to understand by others — or yourself in the future.