Comment on page

1.1 Basic Java Features

Hello World

The classic first program when introducing any new language is Hello World, or a program that prints Hello World to the console. In Java, Hello World can be written as such:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
As compared to other languages like Python, this may seem needlessly verbose. However, there are several reasons for the verbosity of Java, which will be covered in the next few chapters. For now, notice some key syntatical features of the code snippet above:
  • The class declaration public class HelloWorld: in Java, all code lives within classes.
  • The main function: all the code that runs must be inside of a method declared as public static void main(String[] args). Future chapters will cover the exact meaning of this declaration.
  • Curly braces {} enclose sections of code (functions, classes, and other types of code that will be covered in future chapters).
  • All statements must end with a semi-colon.

Static Typing

Java is a statically typed language, which means that all variables, parameters, and methods must have a declared type. After declaration, the type can never change. Expressions also have an implicit type; for example, the expression 3 + 5 has type int.
Because all types are declared statically, the compiler checks that types are compatible before the program even runs. This means that expressions with an incompatible type will fail to compile instead of crashing the program at runtime.
The advantages of static typing include:
  • catching type errors earlier in the coding process, reducing the debugging burden on the programmer.
  • avoiding type errors for end users.
  • making it easier to read and reason about code.
  • avoiding expensive runtime type checks, making code more efficient.
However, static typing also has several disadvantages; namely:
  • more verbose code.
  • less generalizable code.