Java, lesson 1
Every program needs a way to show you what it is doing. In Java you print a line of text with
System.out.println. Here is a complete program:
That is more ceremony than some languages need, so here is what each piece does:
public class Main declares a class called Main. In Java, all code lives inside a class.
On this site the file is called Main.java, so the public class must be named Main.public static void main(String[] args) is the main method, the entry point. When the
program starts, Java calls main and runs its statements in order.{ } group code into blocks. Every statement ends with a semicolon .2 exercises to try what you just read.
;Text in double quotes is a string. Java is case sensitive: System.out.println works,
system.out.Println does not.
System.out is the standard output stream. It has three methods you will use all the time:
printf takes a format string with placeholders: %s for text, %d for whole numbers,
%.2f for a decimal number with two digits after the point, and %n for a line break. The
values after the format string fill the placeholders in order.
The compiler ignores comments. Write them for people, including future you.
Java is compiled. First the compiler javac checks the whole file and turns it into
bytecode. Then the Java Virtual Machine (JVM) runs that bytecode. If the compiler finds a
mistake, such as a missing semicolon, nothing runs at all: you get an error message with the file
name and line number, like Main.java:3: error: ';' expected. Fix the first error first; later
errors are often caused by it.
The JVM takes a moment to start, so even a tiny Java program feels a little slower to launch than a script. That cost is paid once per run.
Write a program that prints exactly these two lines:
The program reads no input.
Print a little scoreboard. The first line is a countdown printed with three System.out.print
calls (3 , 2 , 1 , each followed by a space) and then System.out.println("Go!"). The
second line uses one printf call to show the player Mia with 42 points and an accuracy
of 87.456, rounded to one decimal place.
Expected output:
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
System.out.println("Java runs the statements in main from top to bottom.");
}
}System.out.print("Loading"); // no line break afterwards
System.out.print("...");
System.out.println("done"); // Loading...done, then a line break
System.out.println("Total: " + 42); // + joins text and numbers: Total: 42
System.out.printf("%s scored %d points%n", "Ana", 17); // Ana scored 17 points// A line comment runs to the end of the line.
System.out.println("This runs"); // it can follow code
/* A block comment
can span several lines. */Hello, World!
I am learning Java.3 2 1 Go!
Mia: 42 points, 87.5% accuracy