Java First Program
In this page:
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
public class Main {
public static void main(String[] args) {
System.out.println("main() lives inside a class - Java has no free-floating functions.");
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
System.out.println("JVM looks for exactly this signature to start the program.");
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
System.out.println("First line");
System.out.println("Second line automatically starts fresh");
}
}
Login to try C/C++/Java/PHP code in the editor
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
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.");
}
}
Login to try C/C++/Java/PHP code in the editor
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
public class Main {
public static void main(String[] args) {
int a = 5;
int b = 10;
System.out.println(a + b);
}
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: