Java: reference

A language for large applications and Android: classes, variables, conditions and loops.

Program structure

Minimal program

The file is named the same as the public class: Main.java. Every statement ends with a semicolon.

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

Compiling and running

Commands are run in the terminal.

javac Main.java    # compile
java Main          # run

Variables and types

Primitive types

The type is given at declaration. String is not a primitive but a class.

int age = 16;
double price = 24.5;
boolean ok = true;
char letter = 'A';
long big = 10_000_000_000L;
String name = "Alex";

var and constants

var works only for local variables.

var count = 10;           // the type is inferred (Java 10+)
final double PI = 3.14;    // final: cannot be changed

Type conversion

Dividing two int values drops the fractional part.

int n = (int) 3.9;                 // 3
double d = 5 / 2;                  // 2.0 (integer division)
int x = Integer.parseInt("12");
String s = String.valueOf(42);

Strings

String methods

Strings are compared with the equals method, not ==.

String s = "Java";
System.out.println(s.length() + " " + s.charAt(0));
System.out.println(s.toUpperCase() + s.substring(1, 3));
System.out.println("a".equals("a"));
System.out.printf("%.2f%n", 3.14159);

Input

Scanner

nextInt, nextDouble, next (a word), nextLine (a line).

import java.util.Scanner;

Scanner in = new Scanner(System.in);
System.out.print("Age: ");
int age = in.nextInt();
String name = in.next();

Conditions

if and switch

The arrow switch (Java 14+) does not need break.

if (age < 12) {
    System.out.println("child");
} else if (age < 18) {
    System.out.println("teenager");
} else {
    System.out.println("adult");
}

switch (day) {
    case "sat", "sun" -> System.out.println("weekend");
    default -> System.out.println("weekday");
}

Ternary operator

A short form of a condition that returns a value.

String kind = age >= 18 ? "adult" : "minor";

Loops

for, while, for-each

break leaves the loop, continue moves on to the next iteration.

for (int i = 0; i < 3; i++) {
    System.out.println(i);
}
int n = 0;
while (n < 3) { n++; }

int[] nums = {1, 2, 3};
for (int x : nums) {
    System.out.println(x);
}

Arrays and collections

Array

The array length is fixed. You need to import java.util.Arrays.

int[] a = new int[3];     // [0, 0, 0]
int[] b = {5, 2, 9};
Arrays.sort(b);
System.out.println(b.length + " " + Arrays.toString(b));

ArrayList and HashMap

Imports: java.util.List, ArrayList, Map, HashMap.

List<String> names = new ArrayList<>();
names.add("Amy");
System.out.println(names.get(0) + names.size());

Map<String, Integer> ages = new HashMap<>();
ages.put("Amy", 16);
System.out.println(ages.getOrDefault("Ivan", 0));

Methods

Declaration and call

void means the method returns nothing. A method can be overloaded: the same name, different parameters.

static int add(int a, int b) {
    return a + b;
}

static void hello(String name) {
    System.out.println("Hello, " + name);
}

int sum = add(2, 3);

Classes and objects

Class, constructor, method

Make fields private and provide access through methods.

class Dog {
    private String name;

    Dog(String name) { this.name = name; }

    String speak() { return name + ": woof!"; }
}

Dog rex = new Dog("Rex");
System.out.println(rex.speak());

Inheritance and interface

extends is for inheriting from a class, implements is for an interface.

interface Shape { double area(); }

class Square implements Shape {
    double side;
    Square(double s) { side = s; }
    public double area() { return side * side; }
}

Errors

try / catch / finally

Checked exceptions must either be caught or declared with throws.

try {
    int n = Integer.parseInt("abc");
} catch (NumberFormatException e) {
    System.out.println("Not a number: " + e.getMessage());
} finally {
    System.out.println("Done");
}

Learn Java with practice

Want to learn step by step? Your account has 110 lessons organised by chapter (80 core and 30 advanced, you can switch the level at any time) and tasks with code checking.