← Back to Core Java Course | Chapter 1: Introduction & Basics | Lesson 4 of 12

Java First Program

The Main Class

Java has no free-floating functions -- every method, including main, has to live inside a class, and by convention the file's public class should share its exact name so the compiler can find your entry point.

Example: The Main Class

java
public class Main {
	public static void main(String[] args) {
		System.out.println("main() lives inside a class - Java has no free-floating functions.");
	}
}

The main Method

The JVM specifically looks for public static void main(String[] args) -- get that signature wrong (wrong capitalization, missing static, different parameter type) and Java won't recognize it as the program's starting point.

Example: The main Method

java
public class Main {
	public static void main(String[] args) {
		System.out.println("JVM looks for exactly this signature to start the program.");
	}
}

Printing Output

System.out.println() converts its argument to text and writes it to standard output, then appends a newline character so the next println() call starts on a fresh line automatically.

Example: Printing Output

java
public class Main {
	public static void main(String[] args) {
		System.out.println("First line");
		System.out.println("Second line automatically starts fresh");
	}
}

System and Out Classes

System is a built-in class in java.lang, and out is one of its static fields -- a PrintStream object wired to your terminal -- which is why you always write System.out rather than creating your own instance.

Example: System and Out Classes

java
public class Main {
	public static void main(String[] args) {
		java.io.PrintStream out = System.out; // out is a static PrintStream field of the System class
		out.println("Written through System's static 'out' field.");
	}
}

Statement Terminators

Unlike Python, Java requires a semicolon at the end of every statement to mark where it ends; the compiler uses this to parse your code correctly, and omitting one is one of the most common first syntax errors beginners hit.

Example: Statement Terminators

java
public class Main {
	public static void main(String[] args) {
		int a = 5;
		int b = 10;
		System.out.println(a + b);
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.