Conceptcore
Hello, world
Also called hello world, hello world program, first program, entry point, main function, standard output, exit status.
A hello world program prints Hello, world! and exits. It is the smallest complete program, and it shows the entry point, the standard output stream and the exit status of a language.
- Applies to
- core-languages
- Realized by
- Hello world in Python
Idea
A hello world program writes the text Hello, world! and ends. It is the smallest complete program in a language, so it is the first program that most programmers write, and the first test that a new compiler, toolchain or machine works. The program is short, but it touches every step of running code: the source file, the translation by a compiler or interpreter, the entry point where execution starts, a call to the standard library, the standard output stream, and the exit status that the process gives back to the system.
import subprocess
import sys
source = 'print("Hello, world!")'
child = subprocess.run([sys.executable, "-I", "-c", source], capture_output=True)
print("program: ", source)
print("stdout: ", child.stdout)
print("bytes: ", len(child.stdout), "=", child.stdout.hex(" "))
print("stderr: ", child.stderr)
print("exit status:", child.returncode)
broken = subprocess.run([sys.executable, "-I", "-c", 'print("Hello, world!"'],
capture_output=True, text=True)
print("exit status:", broken.returncode, "for", broken.stderr.splitlines()[-1])
program: print("Hello, world!")
stdout: b'Hello, world!\n'
bytes: 14 = 48 65 6c 6c 6f 2c 20 77 6f 72 6c 64 21 0a
stderr: b''
exit status: 0
exit status: 1 for SyntaxError: '(' was never closed
The program runs a hello world in a new Python process and looks at what comes out. The output is 14 bytes on standard output: the 13 characters of the text, encoded as ASCII, and a newline, byte 0a. Nothing goes to standard error, and the exit status is 0, which means success. The second program has a syntax error, so it never runs: the interpreter writes a message to standard error and exits with status 1.
How it works
The entry point. Every program has a place where execution starts. In C, C++, Java, C#, Go and Rust it is a function named main. The C++ reference states the rule: a program must "contain a global function named main, which is the designated start of the program in hosted environment."1 The Go specification says: "Program execution begins by initializing the program and then invoking the function main in package main. When that function invocation returns, the program exits."2 The Rust book says: "The main function is special: It is always the first code that runs in every executable Rust program."3 Java looks for a method in a class: "The Java Virtual Machine starts execution by invoking a main method of some specified class or interface."4 Scripting languages such as Python, JavaScript, Ruby and the shells have no special function; they run the statements of the file from top to bottom.
Top-level code. Without a main, a language needs another way to tell a program from a library. Python names the module that starts the program __main__: "__main__ is the name of the environment where top-level code is run."5 Code that should run only as a program goes under if __name__ == "__main__":, so that importing the file for its functions does not also run it. Some compiled languages also accept top-level code. C# allows top-level statements in one file and generates the Main method, and newer Java accepts a main method without a class around it. Both changes make the first program shorter for beginners.
Output. A process starts with three open streams: standard input, standard output and standard error. print, console.log, System.out.println, fmt.Println and printf write to standard output, which is the terminal, a file or the input of another program, as the user who starts the program chooses. Diagnostics go to standard error, so that they do not mix with the data. Output is text encoded as bytes, usually UTF-8, and each line ends with a newline. For speed, the standard library buffers output: it collects bytes and writes them in large blocks, at each newline on a terminal, and when the buffer is full or the program exits when the output goes to a pipe or a file. A program that ends without the normal exit path can lose buffered output, as the wrong blocks in the Python and C files show.
The exit status. When a program ends, it gives a small integer to the process that started it. Zero means success, and any other value means failure, with meanings that each program chooses. In C and C++, the value that main returns is the status, and reaching the end of main counts as return 0: "if control reaches the end of main without encountering a return statement, the effect is that of executing return 0;".1 Shells, build tools and CI systems read the status to decide whether a step worked, so a program that fails must also exit with a status other than 0.
The toolchain. The source must become something that the machine runs. For C, C++, Go and Rust, a compiler makes a native executable, which then runs alone. For Java and C#, a compiler makes bytecode, and a virtual machine runs it. Python and JavaScript load the source and run it at once. Modern tools hide the steps: java Main.java, dotnet run, go run and cargo run compile and run in one command. See compilers and interpreters.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Native | |
| C++ | Native | |
| Java | Native | |
| C | Native | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | As JavaScript; console.log("Hello, world!") is a complete program after compilation to JavaScript. |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | A top-level fun main() that calls println("Hello, world!") is a complete program; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Native | The query SELECT 'Hello, world!' returns a result set with one row and one column. |
| Bash | Native | A script with the line echo "Hello, world!" writes the text, and exit sets the status. |
| PowerShell | Native | A string on its own line goes to the output stream, and Write-Output does the same explicitly; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Native | A document whose body holds the text Hello, world! shows it in the browser. |
| CSS | Idiom | A content property on a ::before pseudo-element can insert the text, though text belongs in the document. |
| Regular expressions | Does not apply | A pattern matches text and does not produce output. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | native | top-level print; if __name__ == "__main__" |
| JavaScript | native | top-level console.log |
| TypeScript | native | as JavaScript |
| Java | native | main method; System.out.println |
| Kotlin | native | top-level fun main; println |
| C# | native | top-level statements; Console.WriteLine |
| Go | native | package main, func main; fmt.Println |
| Rust | native | fn main; the println! macro |
| C | native | int main; printf |
| C++ | native | int main; std::cout |
| Bash | native | echo |
| PowerShell | native | a string on its own line; Write-Output |
| SQL | native | SELECT 'Hello, world!' |
| Regex | n/a | a pattern produces no output |
| HTML | native | the text in the body of a document |
| CSS | idiom | the content property of a pseudo-element |
Every example file writes Hello, world!, formats a word and a number into a second line, and reports the number of command-line arguments, which is 0 when the examples run. The files show the three shapes of an entry point. Python and JavaScript run a file from the top. Java, Go, C and C++ need a named function in a fixed place, and C# and newer Java accept top-level code and generate that function. Rust makes the output call a macro, which the compiler checks at compile time.
The cost of the first program differs much more than the programs do. A Python, JavaScript or Bash hello world is one line. Java in its classic form needs a class, a method with a fixed signature and a qualified call, which is why the language added a shorter form. C needs an #include and a main, and the build gives a native executable of tens of kilobytes. Go and Rust give a larger executable, because it holds the runtime or the parts of the standard library that the program uses.
import sys
def main(argv):
name = argv[1] if len(argv) > 1 else "world"
print(f"Hello, {name}!")
print(f"{name} has {len(name)} letters")
print("arguments:", argv[1:])
return 0 # the exit status: 0 means success
if __name__ == "__main__": # true when run as a program, false when imported
sys.exit(main(sys.argv))
Hello, world!
world has 5 letters
arguments: []
This code runs but gives a wrong answer on purpose.
import os
print("start", flush=True)
print("Hello, world!") # waits in the output buffer when stdout is a pipe
os._exit(0) # ends the process at once, so nothing flushes the buffer
start
- Verdict: native. A Python program is a file of statements that run from top to bottom, so
print("Hello, world!")alone is a complete program.printwrites the text and a newline to standard output. The testif __name__ == "__main__"runs the main code only when the file runs as a program, not when another module imports it, andsys.exitsets the exit status. - The wrong block prints a line and then ends the process with
os._exit. When standard output is a pipe or a file, Python buffers it, andos._exitends the process without the flush that a normal exit does, so the line is lost. It appears on a terminal, where output is flushed at each newline. Return from the program normally, or flush before a hard exit.
#include <iostream>
#include <string>
int main(int argc, char *argv[]) {
(void)argv;
std::cout << "Hello, world!\n";
std::string name = "world";
std::cout << name << " has " << name.size() << " letters\n";
std::cout << "arguments: " << argc - 1 << '\n';
}
Hello, world!
world has 5 letters
arguments: 0
- Verdict: native. A C++ program starts at
main, as in C, and reaching the end ofmainreturns 0.std::coutwith<<writes values of any type that has an output operator. Newer standards addstd::printandstd::println, which format text in the style of Python and Rust.
public class Main {
public static void main(String[] args) {
System.out.println("Hello, world!");
System.out.printf("%s has %d letters%n", "world", 5);
System.out.println("arguments: " + args.length);
}
}
Hello, world!
world has 5 letters
arguments: 0
- Verdict: native. A Java program starts at a
mainmethod with aString[]parameter for the arguments. In the classic form it ispublic staticand lives in a class, and the class name usually matches the file name.System.out.printlnwrites a line, andprintfformats, with%nfor the newline of the platform. Thejavalauncher compiles and runs a single source file in one step, as the example does. - Newer versions of Java also accept a compact source file with a plain
void main()and no class declaration, which makes the first program shorter.
#include <stdio.h>
int main(int argc, char *argv[]) {
(void)argv;
printf("Hello, world!\n");
printf("%s has %d letters\n", "world", 5);
printf("arguments: %d\n", argc - 1);
return 0;
}
Hello, world!
world has 5 letters
arguments: 0
This code runs but gives a wrong answer on purpose.
#include <stdio.h>
#include <unistd.h>
int main(void) {
printf("start\n");
fflush(stdout);
printf("Hello, world!\n"); /* waits in the buffer when stdout is a pipe */
_exit(0); /* ends the process without flushing stdio */
}
start
- Verdict: native. A C program starts at
int main(void)orint main(int argc, char *argv[]), and the value thatmainreturns is the exit status.printffrom<stdio.h>writes formatted text to standard output, and\nends the line. Reaching the end ofmainreturns 0. - The wrong block writes a line and then calls
_exit, which ends the process without flushing the buffers of<stdio.h>. When the output goes to a pipe or a file, the buffer still holds the line, and it is lost. Return frommainor callexit, which flush the buffers.
using System;
Console.WriteLine("Hello, world!");
Console.WriteLine($"{"world"} has {"world".Length} letters");
Console.WriteLine($"arguments: {args.Length}");
return 0;
Hello, world!
world has 5 letters
arguments: 0
- Verdict: native. C# accepts top-level statements: one file in a project can hold statements outside any class, and the compiler wraps them in a generated
Mainmethod.argsholds the arguments, andreturn 0sets the exit status. The classic form, astatic void Main(string[] args)method in a class, still works and is common in existing code.Console.WriteLinewrites a line, and interpolated strings with$format values.
console.log("Hello, world!");
console.log("%s has %d letters", "world", 5);
process.stdout.write("write adds no newline");
process.stdout.write("\n");
console.log("arguments:", process.argv.slice(2));
process.exitCode = 0;
Hello, world!
world has 5 letters
write adds no newline
arguments: []
- Verdict: native. A JavaScript file runs from top to bottom, so
console.log("Hello, world!")alone is a complete program in Node.js and in a browser console.console.logadds a newline and formats%sand%dplaceholders. In Node.js,process.stdout.writewrites text as it is,process.argvholds the arguments after the paths of the runtime and the script, andprocess.exitCodesets the exit status.
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("Hello, world!")
fmt.Printf("%s has %d letters\n", "world", len("world"))
fmt.Println("arguments:", len(os.Args)-1)
}
Hello, world!
world has 5 letters
arguments: 0
- Verdict: native. A Go program is a package named
mainwith a functionmainthat takes no arguments and returns nothing.fmt.Printlnwrites its arguments and a newline,os.Argsholds the program name and the arguments, andos.Exitsets a status other than 0. The program ends whenmainreturns, even if other goroutines still run.
fn main() {
println!("Hello, world!");
let name = "world";
println!("{name} has {} letters", name.len());
println!("arguments: {}", std::env::args().count() - 1);
}
Hello, world!
world has 5 letters
arguments: 0
This code does not compile, on purpose. The error is E0423.
fn main() {
println("Hello, world!"); // println is a macro, so the call needs a !
}
- Verdict: native. A Rust program starts at
fn main.println!is a macro, not a function, and the compiler checks its format string and arguments at compile time;{name}reads a variable by name.std::env::argsgives the arguments, andmaincan return aResultso that an error gives a status other than 0. - The fails block calls
printlnwithout the!. The name exists, but as a macro, so the compiler rejects the call with E0423 and suggestsprintln!.
Variations and related ideas
- Hello world in other places. On a microcontroller the first program blinks an LED. A web framework's first program answers an HTTP request with the text, and a graphics API's first program draws a triangle. Each tests the smallest complete path through the toolchain.
- Command-line arguments. The next step after a fixed greeting is a greeting by name, from an argument. See parse command-line arguments.
- Reading input. A program that reads a name from standard input and greets it uses the input stream as well. See read from standard input.
- The read-eval-print loop. An interactive interpreter runs
print("Hello, world!")as soon as the user types it, with no file and no build step. - Quines. A quine is a program that prints its own source, a classic puzzle that grew out of the same interest in the smallest programs.
- Programs as processes. The program runs as a process, with its own memory, streams and exit status. See run a subprocess and the stack and the heap.
Pitfalls
- Lost output at exit. Ending a process with
os._exitin Python or_exitin C skips the flush of output buffers, so output to a pipe or a file is lost, while output to a terminal looks correct. The wrong blocks in the Python and C files show this. Return from the program normally, or flush first. - A missing newline. Text without a final newline leaves the shell prompt on the same line, and tools that read lines can drop the last one. End each line of output with a newline.
- Status 0 on failure. A program that prints an error message and then exits with status 0 tells scripts and CI that it worked. Exit with a status other than 0 on failure.
- Errors on standard output. Error messages written to standard output mix with the data, and a pipeline passes them on as if they were data. Write diagnostics to standard error.
- The wrong name.
printlnwithout the!in Rust,Mainin the wrong case in Java, and amainmethod with the wrong signature all fail to compile or to start. The fails block in the Rust file shows the first. - Encoding. Text with letters outside ASCII can print as broken characters when the terminal and the program use different encodings. Use UTF-8 for source files and output. See characters and code points.
Cost
The program itself costs almost nothing: a few system calls to write 14 bytes and to exit. Most of the time goes to starting the program. A native executable from C starts in about a millisecond. A Python or Node.js interpreter takes tens of milliseconds to start, and a JVM or .NET runtime somewhat more, because each loads a runtime and its libraries before the first line runs. Commands that compile and run in one step, such as java Main.java and dotnet run, add the time of the compile, from a fraction of a second to a few seconds. On disk, a C hello world is tens of kilobytes and links to the shared C library, while a Go or Rust executable, which links its standard library statically, is hundreds of kilobytes to a few megabytes.
History
Brian Kernighan wrote the first known hello world in A Tutorial Introduction to the Language B at Bell Labs in 1972. B could hold only a few characters in each constant, so the program printed the text in three pieces: "a 'hell'; b 'o, w'; c 'orld';".6 The same tutorial set out the rule that C kept: "all B programs must have a main. Execution of the program begins at the first statement of main".6 Kernighan used the program again in a 1974 Bell Labs memo on C, and the 1978 book The C Programming Language, by Kernighan and Dennis Ritchie, opened with it and made it the custom for books on every later language.
The first program became a measure of how much a language asks of a beginner. Java's classic hello world of 1996 needed a class and public static void main(String[] args). Later languages and versions cut this down: C# added top-level statements in 2020, Java 25 made compact source files with a plain void main() final in 2025, and Kotlin, Go and Rust started with a short main from their first releases.
References
- Main function, cppreference.com, Explanation
- The Go Programming Language Specification, Program execution
- Hello, World!, The Rust Programming Language, Anatomy of a Rust Program
- Chapter 12, Execution, The Java Language Specification, Java SE 25 Edition, 12.1 Java Virtual Machine Startup
- __main__, Top-level code environment, Python documentation, What is the top-level code environment?
- Brian W. Kernighan, A Tutorial Introduction to the Language B, Bell Laboratories, 1972, 2. General Layout of Programs and 7. External Variables
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag CR89SM Edit this page History Report an error Markdown