Java Hello World App
A Java Hello World app is the smallest complete Java program: it starts, prints a message and exits. Building it as a real project, step by step, teaches the full workflow every Java application follows: write source code, compile it to bytecode, run it on the JVM, accept input, organize classes into packages and ship it as a JAR file.
This is the first project of the tutorial. You start with a one-line program and finish with hello-app.jar, a command-line tool that greets people by name, in four languages, based on the time of day. Examples were run on JDK 21, and the compact syntax section uses JDK 25.
The Classic Java Hello World Program
Every Java program needs a class and a main method. The JVM looks for main and starts running there.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Save it as HelloWorld.java, then compile and run it:
javac HelloWorld.java
ls
java HelloWorld
HelloWorld.class
HelloWorld.java
Hello, World!
| Part | Meaning |
|---|---|
public class HelloWorld | A class named HelloWorld; a public class must live in a file with the same name |
public static void main(String[] args) | The entry point the JVM calls when the program starts |
String[] args | Command-line arguments passed after the class name |
System.out.println(...) | Prints text followed by a new line to the console |
javac | The compiler: turns .java source into .class bytecode |
java | The launcher: starts the JVM and runs the class |
How it works:
javac HelloWorld.javacreatesHelloWorld.class. This bytecode runs on any operating system that has a JVM, which is why Java code is portable.java HelloWorldtakes the class name, not the file name, so there is no.classat the end.- Java is case-sensitive.
helloworld,Mainorsystem.outall fail to compile or run.
Run a Java File Without Compiling First
Since JDK 11, the launcher can compile and run a single source file in one step. This is ideal for small programs and quick experiments.
java HelloWorld.java
Hello, World!
How it works:
- The launcher compiles the file in memory and runs it. No
.classfile is written to disk. - It only works when the program fits in one file (JDK 22 and later can also find other source files in the same folder). For bigger projects you still use
javac, as shown later in this lesson.
Compact Hello World in Java 25
JDK 25 finalized compact source files and instance main methods (JEP 512). For small programs, the class declaration, public, static and String[] args become optional, and a new java.lang.IO class provides simple console methods.
// Hello.java (JDK 25 or later)
void main() {
IO.println("Hello, World!");
}
java Hello.java
Hello, World!
The IO class can also read input:
// Greet.java (JDK 25 or later)
void main() {
String name = IO.readln("What is your name? ");
IO.println("Hello, " + name + "!");
}
What is your name? Meena
Hello, Meena!
| Classic style | Compact style (JDK 25+) |
|---|---|
public class HelloWorld { ... } | No class declaration needed |
public static void main(String[] args) | void main() |
System.out.println(...) | IO.println(...) |
new Scanner(System.in).nextLine() | IO.readln("prompt") |
| Works on every Java version | Needs JDK 25 or later |
How it works:
- The compiler wraps a compact source file in a hidden class automatically, and creates an instance of it to call
main(). IOlives injava.lang, so it needs no import. Its methods must still be called asIO.println, not plainprintln.- Compact files are meant for learning and small scripts. As soon as a program grows to several classes, switch to the classic structure used in the rest of this lesson.
Note: On JDK 21–24 this feature was a preview under different names. Use the classic form unless you are sure every machine that runs your code has JDK 25.
Say Hello to a Name With Command-Line Arguments
args holds the words typed after the class name. Use them to make the program configurable.
public class HelloName {
public static void main(String[] args) {
// use the first argument as the name, or "World" when none is given
String name = args.length > 0 ? args[0] : "World";
System.out.println("Hello, " + name + "!");
System.out.println("You passed " + args.length + " argument(s).");
}
}
java HelloName.java
java HelloName.java Asha
java HelloName.java "Asha Rao" extra
Hello, World!
You passed 0 argument(s).
Hello, Asha!
You passed 1 argument(s).
Hello, Asha Rao!
You passed 2 argument(s).
How it works:
- Without arguments,
argsis an empty array, nevernull. Checkingargs.length > 0before readingargs[0]avoids anArrayIndexOutOfBoundsException. - The shell splits arguments on spaces. Quotes keep
"Asha Rao"together as one argument. - The ternary operator
condition ? a : bpicks a default in a single line.
Read the User's Name With Scanner
For an interactive program, read from the keyboard with Scanner, as covered in the user input lessons.
import java.util.Scanner;
public class HelloInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("What is your name? ");
String name = scanner.nextLine().strip();
if (name.isEmpty()) {
name = "stranger";
}
System.out.print("Which city are you from? ");
String city = scanner.nextLine().strip();
System.out.println("Hello, " + name + " from " + city + "! Welcome to GOCOURSE.");
}
}
What is your name? Ravi
Which city are you from? Chennai
Hello, Ravi from Chennai! Welcome to GOCOURSE.
Pressing Enter without typing a name:
What is your name?
Which city are you from? Madurai
Hello, stranger from Madurai! Welcome to GOCOURSE.
How it works:
System.out.print(withoutln) keeps the cursor on the same line, so the answer appears right after the question.nextLine()reads everything up to Enter, including spaces.strip()removes spaces the user typed by accident.- An empty answer falls back to
"stranger", so the program never printsHello, from ...with a gap.
Greet Based on the Time of Day
A real greeting changes with the clock. java.time.LocalTime gives the current time.
import java.time.LocalTime;
public class TimeGreeting {
static String greetingFor(LocalTime time) {
int hour = time.getHour();
if (hour < 12) return "Good morning";
if (hour < 17) return "Good afternoon";
return "Good evening";
}
public static void main(String[] args) {
System.out.println(greetingFor(LocalTime.of(8, 30)) + " (08:30)");
System.out.println(greetingFor(LocalTime.of(14, 0)) + " (14:00)");
System.out.println(greetingFor(LocalTime.of(21, 15)) + " (21:15)");
System.out.println(greetingFor(LocalTime.now()) + ", it is now " + LocalTime.now().withNano(0));
}
}
Good morning (08:30)
Good afternoon (14:00)
Good evening (21:15)
Good morning, it is now 10:21:17
How it works:
greetingFortakes the time as a parameter instead of callingLocalTime.now()inside. That makes it easy to test with fixed times, as the first three lines do.getHour()returns 0–23. Theifstatements are checked from top to bottom, and the first match returns.withNano(0)drops the fractions of a second, so the time prints as10:21:17.
Organize the Hello World App Into Packages
Real projects separate code into classes and packages. The finished app has two classes:
| Class | Responsibility |
|---|---|
Greeter | Knows the greeting phrases and builds a message |
HelloApp | Reads command-line options and prints the result |
The folder structure must match the package name:
hello-app/
└── src/
└── com/
└── gocourse/
└── hello/
├── Greeter.java
└── HelloApp.java
Greeter.java stores phrases for four languages and picks one by hour:
package com.gocourse.hello;
import java.time.LocalTime;
import java.util.Map;
/** Builds greetings in several languages. */
public class Greeter {
private static final Map<String, String[]> PHRASES = Map.of(
// language -> { morning, afternoon, evening }
"en", new String[] {"Good morning", "Good afternoon", "Good evening"},
"ta", new String[] {"Kaalai vanakkam", "Madhiya vanakkam", "Maalai vanakkam"},
"hi", new String[] {"Suprabhat", "Namaste", "Shubh sandhya"},
"es", new String[] {"Buenos dias", "Buenas tardes", "Buenas noches"}
);
private final String language;
public Greeter(String language) {
if (!PHRASES.containsKey(language)) {
throw new IllegalArgumentException(
"Unsupported language '" + language + "'. Use one of " + PHRASES.keySet().stream().sorted().toList());
}
this.language = language;
}
public String greet(String name, LocalTime time) {
String[] phrases = PHRASES.get(language);
int hour = time.getHour();
String phrase = hour < 12 ? phrases[0] : hour < 17 ? phrases[1] : phrases[2];
return phrase + ", " + name + "!";
}
}
How it works:
package com.gocourse.hello;must be the first statement, and the file must sit incom/gocourse/hello/. The compiler rejects a mismatch.Map.of(...)creates an immutable map, so no other code can change the phrases at runtime.- The constructor validates the language and throws an exception with a helpful message. An invalid
Greeterobject can never exist.
Build the Command-Line Interface
HelloApp.java turns options such as --name Asha --lang ta into a greeting.
package com.gocourse.hello;
import java.time.LocalTime;
/** Command-line entry point: java -jar hello-app.jar [--name N] [--lang L] [--upper] */
public class HelloApp {
static final String VERSION = "1.0.0";
public static void main(String[] args) {
String name = "World";
String language = "en";
boolean upper = false;
for (int i = 0; i < args.length; i++) {
switch (args[i]) {
case "--name" -> name = valueAfter(args, i++);
case "--lang" -> language = valueAfter(args, i++);
case "--upper" -> upper = true;
case "--version" -> {
System.out.println("hello-app " + VERSION + " (Java " + Runtime.version().feature() + ")");
return;
}
case "--help" -> {
printUsage();
return;
}
default -> {
System.err.println("Unknown option: " + args[i]);
printUsage();
System.exit(2);
}
}
}
try {
String message = new Greeter(language).greet(name, LocalTime.now());
System.out.println(upper ? message.toUpperCase() : message);
} catch (IllegalArgumentException e) {
System.err.println("Error: " + e.getMessage());
System.exit(1);
}
}
private static String valueAfter(String[] args, int index) {
if (index + 1 >= args.length) {
System.err.println("Missing value after " + args[index]);
System.exit(2);
}
return args[index + 1];
}
private static void printUsage() {
System.out.println("Usage: java -jar hello-app.jar [--name NAME] [--lang en|ta|hi|es] [--upper] [--version]");
}
}
How it works:
- The
forloop walks throughargs. The arrow-styleswitchhandles each option withoutbreakstatements. valueAfter(args, i++)passes the current position, then movesiforward so the value (Asha) is not treated as an option on the next loop.- Errors go to
System.err, and the program exits with a non-zero code:1for a bad value,2for wrong usage. Scripts can check$?to know whether the command succeeded.
Compile and Package the Java Hello World App as a JAR
Compile every class into an out folder, then put them in an executable JAR.
cd hello-app
javac -d out src/com/gocourse/hello/*.java
find out -name '*.class' | sort
jar --create --file hello-app.jar --main-class com.gocourse.hello.HelloApp -C out .
jar --list --file hello-app.jar
unzip -p hello-app.jar META-INF/MANIFEST.MF
out/com/gocourse/hello/Greeter.class
out/com/gocourse/hello/HelloApp.class
META-INF/
META-INF/MANIFEST.MF
com/
com/gocourse/
com/gocourse/hello/
com/gocourse/hello/Greeter.class
com/gocourse/hello/HelloApp.class
Manifest-Version: 1.0
Created-By: 21.0.12.1 (Ubuntu)
Main-Class: com.gocourse.hello.HelloApp
| Command | Purpose |
|---|---|
javac -d out ... | Compile and write .class files into out/, following the package folders |
jar --create --file X.jar | Create a new JAR (a ZIP file with a manifest) |
--main-class ... | Write Main-Class into the manifest so java -jar knows where to start |
-C out . | Change into out/ and add everything in it |
How it works:
-d outkeeps compiled files away from source files and recreates thecom/gocourse/hello/folders automatically.- The manifest line
Main-Class: com.gocourse.hello.HelloAppis what makes the JAR executable. Without it,java -jarfails withno main manifest attribute. - The JAR is a single file you can copy to any machine with Java 21+, as shown in Java JAR Deployment.
Real-World Example: Run the Finished hello-app.jar
The finished app greets by name, language and time, and reports errors clearly.
java -jar hello-app.jar
java -jar hello-app.jar --name Asha --lang ta
java -jar hello-app.jar --name Ravi --lang hi --upper
java -jar hello-app.jar --version
Good morning, World!
Kaalai vanakkam, Asha!
SUPRABHAT, RAVI!
hello-app 1.0.0 (Java 21)
Wrong input is caught with a message and an exit code:
java -jar hello-app.jar --lang fr; echo "exit code: $?"
java -jar hello-app.jar --name; echo "exit code: $?"
java -jar hello-app.jar --colour blue; echo "exit code: $?"
Error: Unsupported language 'fr'. Use one of [en, es, hi, ta]
exit code: 1
Missing value after --name
exit code: 2
Unknown option: --colour
Usage: java -jar hello-app.jar [--name NAME] [--lang en|ta|hi|es] [--upper] [--version]
exit code: 2
Because it is a normal command, you can use it in a shell script, for example a login banner:
#!/usr/bin/env bash
# ~/.bash_login — greet the user in Tamil when a terminal opens
java -jar ~/apps/hello-app.jar --name "$USER" --lang ta
Kaalai vanakkam, asha!
How it works:
- Two classes, two jobs.
Greetercontains the logic and knows nothing about the command line.HelloApphandles input and output. This split lets you reuseGreeterlater in a web app without changes. - Defaults make it easy to start. With no options it prints
Good morning, World!, so the first run always works. - Clear failures. Every mistake produces a one-line explanation on
stderrand a non-zero exit code, the same behavior users expect from tools likegitorcurl. - One file to ship.
hello-app.jarcontains the classes and the manifest. Any machine with Java 21+ runs it withjava -jar, and JVM settings such as heap size from Java JVM Options work the same way for this small app as for a server.
The next project, the Java Calculator App, builds on this structure with arithmetic, input validation and a loop that keeps the program running until the user quits.