Reference · module 1
First program
Everything this module explains, on one page.
Hello, Java
Read the shape of a Java program and print a line.
- Every Java program lives in a class, and it starts running in a method called main: public static void main(String[] args). For now, treat that line as the fixed door in.
- System.out.println("Hello"); prints Hello and moves to a new line. System.out.print does the same without the new line, so the next print continues on the same line.
- Every statement ends with a semicolon, and text goes in double quotes. Single quotes are only for one character: 'A'. Forgetting a semicolon stops the program from compiling.
The mistake you are about to make
System.out.println('Hello');
System.out.println("Hello");
Many languages accept either kind of quote, so single quotes feel fine. In Java single quotes mean one char; a word needs double quotes, or it does not compile.
Variables and types
Declare variables with the right type.
- Java is statically typed: each variable is declared with its type. int count = 3; holds a whole number, double price = 4.5; holds a number with a fraction.
- String name = "Ana"; holds text, with a capital S because String is a class. boolean done = false; holds true or false. char letter = 'A'; holds one character.
- The type cannot change later. After int count = 3; the line count = "three"; does not compile. var count = 3; lets Java infer int, but it is still fixed as int.
The mistake you are about to make
int price = 4.5;
double price = 4.5;
A price is a number, and int sounds like the default number type. int holds only whole numbers, so 4.5 does not fit and the line does not compile.
Working with strings
Join strings and compare them correctly.
- + joins strings: "Hi " + name. If one side is a String, the other is turned into text: "Total: " + 5 gives "Total: 5". Left to right still applies: 1 + 2 + "x" is "3x".
- name.length() gives the number of characters, with brackets because it is a method. name.charAt(0) gives the first character; counting starts at 0.
- Compare strings with equals: name.equals("Ana"). The == operator checks whether two variables point to the same object, and can be false for identical text.
The mistake you are about to make
if (answer == "yes")
if (answer.equals("yes"))
== compares numbers perfectly, so it seems right for text too. For objects like String it compares identity, not content, and fails for text read from input.