Your First Java Program
Time to write real Java. In this lesson you will create a program, compile it with javac, run it with java, and understand every word of the classic public static void main line that has puzzled Java beginners for years.
Then you will meet the shorter style added in Java 25, compact source files, which let you start with just a main method. You need to know both: the short style is great for learning and small scripts, while every existing Java project, exam paper and interview uses the classic style.
The classic Hello program
Create a folder for your Java practice, such as C:\java-practice. In it, create a file named exactly Hello.java and type this code (typing it yourself helps you remember it):
public class Hello {
public static void main(String[] args) {
System.out.println("Namaste, Java!");
System.out.println("My name is Priya and I live in Jaipur.");
}
}Now open a terminal in that folder, compile the file, and run the class:
javac Hello.java
java HelloNamaste, Java! My name is Priya and I live in Jaipur.
javac Hello.java created a new file, Hello.class, containing bytecode. java Hello started the JVM and asked it to run the class named Hello. Notice that you give javac a file name (with .java) but give java a class name (without .class).
Every word of main explained
| Part | Meaning |
|---|---|
public class Hello | Declares a class named Hello. A public class must live in a file with the same name: Hello.java. |
{ ... } | Curly braces mark where the class, and each method, begins and ends. |
public | The method can be called from anywhere, including by the JVM. |
static | The method belongs to the class itself, so the JVM can call it without creating an object first. |
void | The method does not return a value. |
main | The special name the JVM looks for when the program starts. |
String[] args | An array of text values passed on the command line. You can ignore it for now. |
System.out.println(...) | Prints a value, then moves to a new line. |
; | Ends each statement, like a full stop ends a sentence. |
You will learn exactly what classes, methods, static and arrays are in later lessons. For now, treat these lines as the frame that holds your code: everything you want to run goes between the inner braces.
print and println
System.out.println prints and then starts a new line. System.out.print prints without a new line, so the next output continues on the same line. Calling println() with nothing inside prints an empty line.
public class Print {
public static void main(String[] args) {
System.out.print("Train 12015 ");
System.out.print("leaves at ");
System.out.println("06:10");
System.out.println(2 + 3);
System.out.println("2" + 3);
System.out.println();
System.out.println("Done");
}
}Train 12015 leaves at 06:10 5 23 Done
Look carefully at 2 + 3 and "2" + 3. Without quotes, Java adds two numbers. With a string on one side, + joins text, so you get 23. This small detail causes many bugs, and you will see it again in Strings & Text Blocks.
Run a single file without javac
Since Java 11 you can skip the separate compile step for a program that fits in one file. Pass the file name to java, and it compiles the code in memory and runs it straight away:
java Hello.javaThis is the quickest way to try small programs, and it is how you will run most examples in this course. For bigger projects with many files, you still compile with javac or a build tool such as Maven.
The Java 25 way: compact source files
For years, beginners had to type public static void main(String[] args) before understanding any of it. Java 25 removes that hurdle.
A compact source file can also hold fields and other methods. Here is a slightly bigger program for a bookshop in Kochi:
String shop = "Meera's Book Corner";
void main() {
IO.println("Welcome to " + shop);
IO.println("Books sold today: " + total(12, 7));
List<String> genres = List.of("Fiction", "Exam guides", "Comics");
IO.println("Genres: " + genres);
}
int total(int morning, int evening) {
return morning + evening;
}Welcome to Meera's Book Corner Books sold today: 19 Genres: [Fiction, Exam guides, Comics]
The rules of compact source files
These rules come from JEP 512, the official description of the feature:
- Java wraps the file's fields and methods in an implicit class. That class is
final, sits in the unnamed package, and has no name you can use in code, so other classes cannot refer to it. - The file must have a launchable
mainmethod, otherwise it does not compile. Statements cannot sit directly at the top level; they belong inside methods. - Every public class in the module
java.baseis imported automatically. That is whyListabove works without animportline.Scanner,Map,ArrayListandPathwork the same way. - The methods of
IOare not imported automatically. WriteIO.println(...), notprintln(...).
How Java picks the main method
Java 25 also lets ordinary classes use a shorter main, called an instance main method. When you launch a class, Java chooses its main method like this:
- If there is a
mainwith aString[]parameter, it is used. Otherwise amainwith no parameters is used. - If the chosen method is
static, Java calls it directly. - If it is not
static, Java first creates an object using the class's no-argument constructor (which must not beprivate), then callsmainon that object.
The classic public static void main(String[] args) still works exactly as before, and it is still what you will see in nearly every existing project. A good habit: use compact source files for quick experiments, and switch to a normal class as soon as your program grows to several files.
Common mistakes
- File name and class name differ. A file
Hello.javacontainingpublic class Welcomefails with:error: class Welcome is public, should be declared in a file named Welcome.java. - Missing semicolon. The compiler reports
error: ';' expectedand points just after the line that needs it. - Wrong capital letters. Java is case-sensitive. Writing
system.out.printlngiveserror: package system does not exist. It must beSystem. - Running the
.classfile name.java Hello.classfails withError: Could not find or load main class Hello.class. Usejava Hello. - Calling
printlnwithoutIO.in a compact file. On Java 25, writeIO.println("Hi").
Key points
javac Hello.javacompiles source code intoHello.class;java Helloruns the class.java Hello.javacompiles in memory and runs a single-file program in one step.- A public class must be in a file with exactly the same name, including capital letters.
System.out.printlnprints a line;System.out.printprints without a new line.- Java 25 compact source files need only
void main(), import all ofjava.baseautomatically, and useIO.printlnfor output. - Classic
public static void main(String[] args)still works and is what most real code uses.
Exercise
Write a classic Java program Ticket.java that prints a three-line train ticket: your name, the route Rohtak to New Delhi, and the fare Rs 85. Print the first two values on one line using print, separated by a space. Compile it with javac and run it with java. If you have Java 25, write the same program as a compact source file too.
Show solution
public class Ticket {
public static void main(String[] args) {
System.out.print("Passenger: Aarav ");
System.out.println("| Route: Rohtak to New Delhi");
System.out.println("Fare: Rs 85");
System.out.println("Have a safe journey!");
}
}Passenger: Aarav | Route: Rohtak to New Delhi Fare: Rs 85 Have a safe journey!
The first print leaves the cursor on the same line, so the route continues after the name. The Java 25 version is the same code inside void main() { ... } with IO.print and IO.println instead of System.out.print and System.out.println.
Quick Quiz
1. You saved public class Bill in a file called bill.java. What happens when you compile it?
A public class must be in a file with exactly the same name, and Java is case-sensitive.
2. Which command runs a compiled class named Hello?
Pass the class name to java, without the .class extension.
3. What does System.out.println("5" + 5) print?
When one side of + is a string, Java joins the values as text.
4. In a Java 25 compact source file, how do you print a line?
IO is in java.lang, but its methods are not imported automatically, so you write IO.println.
Learn Java with a mentor
Free lessons get you started. Our Java, C & C++ Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
