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 Hellodeclares one. The file must be named after it:Hello.java. public static void main(String[] args)is where the program starts.voidmeans it returns nothing;argsholds any command-line arguments.System.out.printlnprints a line.System.out.printprints 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.
mainis the starting point; statements end with;.javaccompiles,javaruns, orjava File.javadoes both.+joins text, so bracket arithmetic inside a print.
Next: variables and Java's types.