Java Hello World App

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 294 of 306

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!
PartMeaning
public class HelloWorldA 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[] argsCommand-line arguments passed after the class name
System.out.println(...)Prints text followed by a new line to the console
javacThe compiler: turns .java source into .class bytecode
javaThe launcher: starts the JVM and runs the class

How it works:

  • javac HelloWorld.java creates HelloWorld.class. This bytecode runs on any operating system that has a JVM, which is why Java code is portable.
  • java HelloWorld takes the class name, not the file name, so there is no .class at the end.
  • Java is case-sensitive. helloworld, Main or system.out all 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 .class file 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 styleCompact 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 versionNeeds 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().
  • IO lives in java.lang, so it needs no import. Its methods must still be called as IO.println, not plain println.
  • 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, args is an empty array, never null. Checking args.length > 0 before reading args[0] avoids an ArrayIndexOutOfBoundsException.
  • The shell splits arguments on spaces. Quotes keep "Asha Rao" together as one argument.
  • The ternary operator condition ? a : b picks 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 (without ln) 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 prints Hello, 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:

  • greetingFor takes the time as a parameter instead of calling LocalTime.now() inside. That makes it easy to test with fixed times, as the first three lines do.
  • getHour() returns 0–23. The if statements are checked from top to bottom, and the first match returns.
  • withNano(0) drops the fractions of a second, so the time prints as 10:21:17.

Organize the Hello World App Into Packages

Real projects separate code into classes and packages. The finished app has two classes:

ClassResponsibility
GreeterKnows the greeting phrases and builds a message
HelloAppReads 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 in com/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 Greeter object 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 for loop walks through args. The arrow-style switch handles each option without break statements.
  • valueAfter(args, i++) passes the current position, then moves i forward 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: 1 for a bad value, 2 for 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
CommandPurpose
javac -d out ...Compile and write .class files into out/, following the package folders
jar --create --file X.jarCreate 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 out keeps compiled files away from source files and recreates the com/gocourse/hello/ folders automatically.
  • The manifest line Main-Class: com.gocourse.hello.HelloApp is what makes the JAR executable. Without it, java -jar fails with no 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:

  1. Two classes, two jobs. Greeter contains the logic and knows nothing about the command line. HelloApp handles input and output. This split lets you reuse Greeter later in a web app without changes.
  2. Defaults make it easy to start. With no options it prints Good morning, World!, so the first run always works.
  3. Clear failures. Every mistake produces a one-line explanation on stderr and a non-zero exit code, the same behavior users expect from tools like git or curl.
  4. One file to ship. hello-app.jar contains the classes and the manifest. Any machine with Java 21+ runs it with java -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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Hello World App and get answers drawn from it.

Signed-in readers only.