A Java program is a set of classes; execution starts at public static void main(String[] args) of the class you launch.
Anatomy of a source file
package com.example.app; // 1. optional package (must be first)
import java.util.List; // 2. imports
public class Main { // 3. at most ONE public top-level class, named like the file
static final int LIMIT = 3; // fields
public static void main(String[] args) { // entry point
List<String> names = List.of("Ada", "Linus", "Grace");
for (int i = 0; i < LIMIT; i++) {
greet(names.get(i));
}
}
static void greet(String name) { // methods
System.out.println("Hi, " + name);
}
}Hi, Ada
Hi, Linus
Hi, GraceDissecting main
| Part | Why |
|---|---|
public | The JVM calls it from outside the class. |
static | No object exists yet — the JVM calls it on the class itself. |
void | Returns nothing; use System.exit(code) to set an exit status. |
main | The name the launcher looks for. |
String[] args | Command-line arguments (also String... args). Never null; empty if none. |
public class Main {
public static void main(String[] args) {
System.out.println("count = " + args.length);
for (String a : args) System.out.println("arg: " + a);
}
}count = 2
arg: hello
arg: 42Rules and conventions
One
publictop-level class per file, and the file must be named after it:Main→Main.java.Every statement ends with
;; blocks use{ }. Java is case-sensitive (Main≠main).Naming:
PascalCaseclasses/interfaces,camelCasemethods/variables,UPPER_SNAKE_CASEconstants,lowercase.dottedpackages (reversed domain:com.example.app).Comments:
// line,/* block */,/** Javadoc */(turned into HTML API docs byjavadoc).java.lang(String,Math,System,Integer…) is imported automatically.
Console output & input
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String name = in.next();
int age = in.nextInt();
System.out.print("No newline, ");
System.out.println("then newline");
System.out.printf("%s is %d years old (%.2f decades)%n", name, age, age / 10.0);
System.out.println(String.format("[%5d] [%-5s] [%05d]", 42, "ab", 42));
}
}No newline, then newline
Ravi is 27 years old (2.70 decades)
[ 42] [ab ] [00042]| Format | Meaning |
|---|---|
%d / %s / %c / %b | integer / string / char / boolean |
%f, %.2f, %e | floating point, 2 decimals, scientific |
%5d, %-5s, %05d | width 5 right-aligned, left-aligned, zero-padded |
%x, %o | hexadecimal, octal |
%n | platform line separator (prefer over \n in printf) |
Can we overload main? Can main be private or non-static?
Why is main static?
Can a source file have no public class?