Your First Java Program

Java · Lesson 3 of 32 8 min read Updated

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):

Java
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:

Terminal
javac Hello.java
java Hello
Output
Namaste, 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

PartMeaning
public class HelloDeclares 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.
publicThe method can be called from anywhere, including by the JVM.
staticThe method belongs to the class itself, so the JVM can call it without creating an object first.
voidThe method does not return a value.
mainThe special name the JVM looks for when the program starts.
String[] argsAn 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.

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.

Java
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");
    }
}
Output
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:

Terminal
java Hello.java

This 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:

Java
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;
}
Output
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 main method, otherwise it does not compile. Statements cannot sit directly at the top level; they belong inside methods.
  • Every public class in the module java.base is imported automatically. That is why List above works without an import line. Scanner, Map, ArrayList and Path work the same way.
  • The methods of IO are not imported automatically. Write IO.println(...), not println(...).

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:

  1. If there is a main with a String[] parameter, it is used. Otherwise a main with no parameters is used.
  2. If the chosen method is static, Java calls it directly.
  3. If it is not static, Java first creates an object using the class's no-argument constructor (which must not be private), then calls main on 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.java containing public class Welcome fails with: error: class Welcome is public, should be declared in a file named Welcome.java.
  • Missing semicolon. The compiler reports error: ';' expected and points just after the line that needs it.
  • Wrong capital letters. Java is case-sensitive. Writing system.out.println gives error: package system does not exist. It must be System.
  • Running the .class file name. java Hello.class fails with Error: Could not find or load main class Hello.class. Use java Hello.
  • Calling println without IO. in a compact file. On Java 25, write IO.println("Hi").

Key points

  • javac Hello.java compiles source code into Hello.class; java Hello runs the class.
  • java Hello.java compiles 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.println prints a line; System.out.print prints without a new line.
  • Java 25 compact source files need only void main(), import all of java.base automatically, and use IO.println for 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
Java
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!");
    }
}
Output
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?

2. Which command runs a compiled class named Hello?

3. What does System.out.println("5" + 5) print?

4. In a Java 25 compact source file, how do you print a line?

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