Hello, World!

Programming Languages · Java Basics · 8 min

Write your first Java program: print lines of text and leave notes for humans.

Your first line of code

A program is a list of instructions for the computer. In Java, System.out.println() prints a line of text on the screen.

Text goes inside double quotes, and every instruction ends with a semicolon ;, like a full stop at the end of a sentence:

System.out.println("Hi there");
  • Print Hello, World!

The Main class and main method

Look at the code around your line. Java keeps all code inside a class, a named box of code. Ours is called Main.

Inside it, main is a method: a named list of steps. Java always starts running at main and goes top to bottom. For now, just write your code between main's curly braces { }.

public class Main {
    public static void main(String[] args) {
        // your code goes here
    }
}
  • Print Java starts in main on the first line.

  • On the next line, print and runs top to bottom.

println vs print

println prints the text and then starts a new line. print (no ln) prints the text but stays on the same line, so the next thing printed comes right after it.

System.out.print("Hel");
System.out.println("lo");
// prints: Hello
  • Use System.out.print twice: once for "Ready, " and once for "set, ".

  • Finish with System.out.println("go!") so one line reads Ready, set, go!

Comments are notes for humans

// starts a comment: Java ignores everything after it on that line. Programmers use comments to explain why the code does something.

Handy trick: put // in front of a line of code to switch it off without deleting it.

// This note is ignored
System.out.println("This line runs");
  • Add a comment above the first line that says what the program does.

  • Put // in front of the line that prints Oops, so it no longer runs.

Put it together: a name badge

Time to combine everything. Make a name badge that prints three lines. Use print and println together for the middle line. You can use your own name.

  • Print HELLO on the first line.

  • Use print for "my name is " and println for a name, so the second line reads like my name is Ada.

  • Print Nice to meet you! on the last line.

More in Java Basics

Previous: Functional Patterns · Next: Variables