</>CodexBash
Java
JavaBeginner8 min

Your first Java program

What Java is, why every program starts in a class, compiling and running with javac and java, printing, and reading error messages.

Java runs much of the world's business software, Android apps and large web services. It is typed and structured: the compiler checks a great deal before your program ever runs, which catches mistakes early and makes large programs manageable.

Hello, world#

public class Hello {
    public static void main(String[] args) {
        System.out.println("Hello, world");
    }
}

There is more ceremony than in Python, and every word has a job:

  • Everything lives in a class. public class Hello declares one. The file must be named after it: Hello.java.
  • public static void main(String[] args) is where the program starts. void means it returns nothing; args holds any command-line arguments.
  • System.out.println prints a line. System.out.print prints without ending the line.
  • Statements end with ;, and braces { } group code.

Compiling and running#

Java compiles to bytecode, which the Java Virtual Machine (JVM) then runs. That is what lets the same compiled program run on any operating system.

javac Hello.java      # produces Hello.class
java Hello            # runs it: no .class on the end

Since Java 11 you can also run a single file directly, which is handy while learning:

java Hello.java

Printing values#

+ joins text and values:

int age = 21;
System.out.println("Age: " + age);
System.out.println("Sum: " + (2 + 3));   // brackets: otherwise "Sum: 23"

Without the brackets, Java reads left to right: "Sum: " + 2 is the text "Sum: 2", and adding 3 gives "Sum: 23".

For formatted output, printf works like C's:

double price = 99.456;
System.out.printf("Price: %.2f%n", price);    // Price: 99.46

%n is a new line.

Comments#

// to the end of the line
/* across
   several lines */
/** A documentation comment, read by tools that generate API docs. */

Reading an error#

Compile errors name the file and line:

Hello.java:3: error: ';' expected
        System.out.println("Hello, world")
                                           ^

The caret points at the spot. Errors while running look different, with the exception's name and a stack trace:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5
    at Hello.main(Hello.java:6)

Read the first line for what and the first at line in your own file for where.

Key points#

  • Every Java program is in a class, in a file of the same name.
  • main is the starting point; statements end with ;.
  • javac compiles, java runs, or java File.java does both.
  • + joins text, so bracket arithmetic inside a print.

Next: variables and Java's types.

Create a free account to track your progress