Your First Java Program Explained: Classes, main, Statements and Comments
A line-by-line explanation of a simple Java program: classes and naming rules, why the file name matters, what public static void main(String[] args) means, statements and method calls, print vs println, exit codes, comments, and Java 25's simpler main.
kvi5hnuCode Sprout team member13 min readOn this page
Every Java application, from a one-line exercise to a banking system, starts from the same skeleton. This article takes one of the simplest Java programs apart, piece by piece. Take your time here: you'll see these pieces in every program you write from now on.
public class Solution {
public static void main(String[] args) {
System.out.println("Hi, Java!");
}
}
Hi, Java!

Java Is Case-Sensitive
Before anything else: uppercase and lowercase letters are different in Java. Main and main, String and string, System and system are completely different names. If you type Public instead of public, or Main instead of main for the method, the program won't compile or won't run. Many beginners' first errors are capitalisation mistakes, so when something "should work but doesn't", check case first.
Line 1: The Class
public class Solution {
public: an access modifier
public is an access modifier. Access modifiers control which other parts of a program may use a piece of code. public means "anyone may use this class". You'll learn the other modifiers (private, protected, and the default "package" access) in the objects and classes part.
class: everything lives in a class
The keyword class introduces a class. In Java, all code lives inside classes. There are no free-standing functions or global variables as in C, Python or JavaScript. For now, think of a class as a container for your program's logic. In the next part you'll see that classes are much more than that: they are the blueprints from which objects are made, and the building blocks of every Java application.
The class name
After class comes the class's name, here Solution. The rules for names (called identifiers) are generous:
| Rule | Allowed | Not allowed |
|---|---|---|
Must start with a letter, _ or $ | Solution, _temp, $cache | 1stProgram |
Then any letters, digits, _ or $ | Version2, max_value | my-class, my class, total% |
| "Letters" include Unicode letters | Größe, π, नमस्ते | |
| Cannot be a reserved word | Klass, myClass | class, public, int, new |
| Case-sensitive | Main ≠ main | |
| Length | essentially unlimited |
A lone underscore _ isn't a valid name; since Java 22 it has a special meaning for unused variables. The $ character is legal but by convention reserved for names generated by tools; don't use it in your own code. The full list of reserved words (keywords) is in the keywords appendix article at the end of the course.
Naming conventions
The compiler accepts any legal name, but Java programmers follow strong conventions that make code readable:
- Class names are nouns that start with an uppercase letter:
Solution,Student,BankAccount. - If a name has several words, each word starts with an uppercase letter:
FirstSample,HttpRequestParser. Capitals in the middle of a word are called camel case (or, appropriately, CamelCase), because they look like humps. - Methods and variables use camel case starting with a lowercase letter:
main,println,totalPrice.
| Kind of name | Convention | Examples |
|---|---|---|
| Class, record, interface, enum | UpperCamelCase | String, ArrayList, LocalDate |
| Method, variable, parameter | lowerCamelCase | println, length, firstName |
| Constant | UPPER_SNAKE_CASE | MAX_VALUE, PI |
| Package | all lowercase, dot-separated | java.util, com.example.shop |
The file name must match
The source file must be named after the public class, plus .java. The class Solution goes in Solution.java; a class FirstSample goes in FirstSample.java, and case matters here too (firstsample.java is wrong). When you compile with javac Solution.java, the compiler writes the bytecode to Solution.class in the same directory. You run the program with java Solution, the class name, without .class.
Braces: Blocks
public class Solution { // class body starts
...
} // class body ends
Curly braces { } mark blocks, groups of code that belong together. The class has a body in braces; the method inside it has its own body in braces. Every { must have a matching }.
Java doesn't care about whitespace (spaces, tabs, line breaks between tokens), so you can place braces however you like. The two common brace styles are:
public class Solution {
public static void main(String[] args) {
System.out.println("Hi");
}
}
public class Solution
{
public static void main(String[] args)
{
System.out.println("Hi");
}
}
The first style is the convention used by the JDK itself, Google's and Oracle's style guides, and this course. The second style lines up matching braces and is popular among programmers coming from C# or C++. Arguing about brace style is a famous waste of time: pick one, and above all be consistent (or let your IDE's formatter decide).
Line 2: The main Method
public static void main(String[] args) {
A method is Java's name for a function: a named block of code that performs a task. When you run java Solution, the JVM loads the class Solution and starts execution in its main method. So every Java application needs a main method in the class you launch. You can write other methods and call them from main; you'll learn how in the objects and classes part.
Each word in this header has a meaning:
| Part | Meaning | Explained in detail |
|---|---|---|
public | The JVM, from outside the class, must be able to call it | Objects and classes part |
static | It belongs to the class itself, so it can run without creating a Solution object first | Static fields and methods article |
void | It returns no value | Defining classes article |
main | The name the launcher looks for, exactly main, lowercase | |
String[] args | An array of strings holding command-line arguments | Arrays article |
For now, treat public static void main(String[] args) as a fixed formula. Here's the shape of every classic Java application:
public class ClassName {
public static void main(String[] args) {
// program statements
}
}
Exit codes and System.exit
In C and C++, main returns an integer exit code to the operating system: 0 for success, anything else for failure. Java's main is void and returns nothing. If main finishes normally, the program's exit code is 0. To end the program with a different code, call System.exit:
if (inputFileMissing) {
System.err.println("Input file not found");
System.exit(2); // exit code 2 signals an error to scripts
}
Exit codes matter when your program is used from scripts or build pipelines, which check them to decide whether a step succeeded. (System.err is the standard error stream, the right place for error messages.)
Line 3: A Statement
System.out.println("Hi, Java!");
The body of main holds statements, the "sentences" of the language, executed one after another from top to bottom. This program has just one.
- Every statement ends with a semicolon
;. A line break does not end a statement, so a long statement may span several lines, and (although it's bad style) several statements may share a line. "Hi, Java!"is a string literal: text in double quotes. Single quotes are for single characters ('H'), as you'll see in the data types articles.
Calling a method: object.method(arguments)
System.out.println("Hi, Java!") is a method call. Java's general syntax for calling a method is:
object.method(arguments)
Here System.out is an object representing the standard output, usually the terminal window. println is a method of that object, and "Hi, Java!" is the argument: the value handed to the method. The dots connect the parts: System is a class, out is an object stored in that class, and println is a method of out.
Methods can take zero, one or several arguments, separated by commas. Even with no arguments you must write the parentheses:
System.out.println(); // prints an empty line
println vs print
println ("print line") prints its argument and then moves to a new line, so the next output starts on the next line. print prints its argument and stays on the same line:
public class Solution {
public static void main(String[] args) {
System.out.print("Hello"); // no line break after this
System.out.print(", ");
System.out.println("World!"); // line break after this
System.out.println(); // an empty line
System.out.println("Done.");
}
}
Hello, World!
Done.
You'll meet a third method, printf, for formatted output in the console input/output article.
Comments
Comments are notes for human readers. The compiler ignores them completely, so they don't make the compiled program bigger or slower. Java has three kinds:
/**
* Prints a short greeting. ← documentation comment (Javadoc)
* @author Ada
*/
public class Solution {
public static void main(String[] args) {
// A single-line comment runs from // to the end of the line.
System.out.println("Hi"); // it can also follow code
/* A block comment can span
several lines. */
System.out.println("Bye");
}
}
| Syntax | Kind | Typical use |
|---|---|---|
// … | Single-line comment | Short remarks; also used for several lines, one // per line |
/* … */ | Block comment | Longer explanations; temporarily disabling code |
/** … */ | Documentation comment | Describing classes and methods; the javadoc tool turns them into HTML API documentation (see the Javadoc article) |
/// … | Markdown documentation comment (Java 23+) | Same purpose as /** */, written in Markdown |
Good comments explain why, not what. The code already says what it does. A comment such as i++; // add 1 to i adds nothing. A comment such as // retry once: the payment API fails on the first call after a timeout saves your colleagues an hour.
Java 25: A Simpler main
public static void main(String[] args) is a lot of ceremony for "print a line". Java 21 introduced a preview feature to simplify it, it was refined in later previews, and Java 25 made it final (JEP 512, Compact Source Files and Instance Main Methods). Two things changed.
1. main can be an instance method without parameters. No public, no static, no String[] args:
class Solution {
void main() {
System.out.println("Hi, Java!");
}
}
2. Small programs can skip the class declaration. A file containing only methods (and fields) is a compact source file. The compiler wraps it in an implicitly declared class for you:
void main() {
IO.println("Hi, Java!");
}
IO is a small class in java.lang, also new in Java 25, with simple methods for console programs: IO.println(...), IO.print(...) and IO.readln(...) (read a line of input). Compact source files also automatically import the whole java.base module, so classes such as List and ArrayList can be used without import statements.
When several possible main methods are present, the launcher picks one with a fixed rule: a main with a String[] parameter is preferred over one with no parameters, and a static one is invoked directly. For an instance main, the launcher first creates an object of the class using its no-argument constructor. main may not be private.
Common questions
Why must main be static in the classic form?
When the program starts, no objects exist yet. A static method belongs to the class itself, so the launcher can call it without creating an object first. Since Java 25, an instance main is also allowed; the launcher then creates the object for you using the no-argument constructor.
Can a file contain more than one class?
Yes, but only one of them may be public, and the file must be named after that public class. Each class still compiles to its own .class file. Most code puts one top-level class in each file, which keeps things easy to find.
Does args have to be called args?
No. It is a normal parameter name, so main(String[] arguments) works. The type must be String[] or the varargs form String.... Everyone uses args by convention.
What exit code does a program get when it ends with an exception?
If main throws an exception that nobody catches, the JVM prints the stack trace and the process exits with code 1. Normal completion gives 0. Use System.exit(n) when a script needs a specific code.
Should I switch to compact source files and IO.println?
Use them for quick experiments and scripts on Java 25 or later. For programs that grow beyond one file, write normal classes. You will need packages, imports and explicit classes anyway, and almost all existing code uses the classic form.
Summary
- Java is case-sensitive.
- All code lives in classes. Class names start with an uppercase letter and use CamelCase; a public class
Xmust be in the fileX.java. - Identifiers start with a letter (or
_/$), continue with letters and digits, and can't be reserved words. - Execution starts in
public static void main(String[] args).mainreturns nothing; useSystem.exit(code)for a non-zero exit code. - Braces
{}form blocks; statements end with;; method calls look likeobject.method(arguments). printlnends the line;printdoesn't.- Comments:
//line,/* */block (they don't nest),/** */documentation, and since Java 23///Markdown documentation. - Java 25 allows
void main()instance methods and compact source files withIO.println.
Practice Questions
Which of these are legal class names: Student, 2ndPlace, my-app, _Temp, class, Größe?
Legal: Student, _Temp, Größe (Unicode letters are allowed). Illegal: 2ndPlace (starts with a digit), my-app (a hyphen isn't allowed), class (reserved word). By convention, only Student and Größe follow class-naming style; avoid leading underscores.
The file is named Program.java but contains public class Hello. What happens?
Compilation fails: "class Hello is public, should be declared in a file named Hello.java". Rename the file or the class so they match.
What does this print? System.out.print("A"); System.out.println("B"); System.out.print("C");
AB
C
print("A") stays on the line, println("B") prints B and ends the line, and print("C") starts the new line.
Why doesn't wrapping code in /* */ always comment it out?
Block comments don't nest. If the code already contains a /* … */ comment, its */ closes your outer comment early, and the remaining lines are compiled, usually causing syntax errors. Use // on each line instead.
A script needs to know whether your Java program failed. How do you report failure?
Call System.exit with a non-zero status, for example System.exit(1), typically after printing a message to System.err. If main finishes normally the exit code is 0, meaning success.
Rewrite the Hi, Java! program as a Java 25 compact source file.
void main() {
IO.println("Hi, Java!");
}
Save it, for example as Hi.java, and run it with java Hi.java on Java 25 or later.
Previous: JShell Tutorial: Java's Interactive REPL for Quick Experiments
Next: Java Primitive Types: Integers and Floating-Point Numbers Explained
Related reading
- Java Streams Explained: From Loops to Stream Pipelines
- Java Collectors.toMap: Collecting Streams into Maps
- Collecting Java Stream Results: toList, toArray, joining and Summary Statistics
- Java Optional Best Practices: Pitfalls, Creating Optionals, flatMap and stream()
- Java Optional: Getting, Consuming and Transforming Optional Values

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.