Java

Java is an object-oriented, statically-typed language developed by Sun Microsystems. Programmers compile Java to bytecode that's executed by the Java Virtual Machine (JVM).

Hello World

Place the following code in a file called Main.java.

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

Compile and execute with the following commands.

javac Main.java
java Main

Types

Primitive Types

Primitive types begin with a lowercase letter.

Type Size Example
byte 1 byte byte b = 1;
short 2 byte short s = 2;
int 4 byte int i = 3;
long 8 byte long l = 4L;
float 4 byte float f = 5.6f;
double 8 byte double d = 7.8;
char 2 byte char c = 'c';
boolean 1 bit boolean b = true;

Note that String is sometimes considered a primitive type.

Arrays

// Array of size 10.
int[] array = new int[10];

// Arrays can also be declared literally.
String[] numbers = {"One", "Two", "Three"};

Custom Types

public interface Animal {
    public void speak();
    public void setPosition(int x, int y);
}

public class Dog implements Animal {

    private String name;

    private int x;

    private int y;

    public Dog(String name) {
        this.name = name;
        this.x = 0;
        this.y = 0;
    }

    public String getName() {
        return this.name;
    }

    @Override
    public void speak() {
        System.out.println("Bark!");
    }

    @Override
    public void setPosition(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

Control Flow

If statements are c-like.

if (test) {
    // Ran if test is true.
} else {
    // Ran if test is false.
}

Java has standard for loops. for...each provides iteration over 'Iterable' types.

for (int i = 0; i < 10; i++) { }

for (String item: items) { }

Java also has while and do...while loops.

Standard Library

ArrayList

ArrayList implements the List interface.

import java.util.ArrayList;

ArrayList<Integer> items = new ArrayList<>();

items.add(1);
items.add(2);
items.get(0); // 1
items.size(); // 2

for (int item : items) {
    System.out.println(item);
}

HashMap

HashMap implements the Map interface.

import java.util.HashMap;

HashMap<String, Integer> map = new HashMap<>();

map.put("One", 1);
map.put("Two", 2);
map.size();             // 2
map.containsKey("One"); // true

HashSet

HashSet implements the Set interface.

import java.util.HashSet;

HashSet<Integer> set = new HashSet<>;

set.add(1);
set.add(2);

set.size();      // 2
set.contains(1); // true

Random

int number = (int)(Math.random() * 10) // Number between 0 and 10

Random gives another approach.

import java.util.Random;

Random rand = new Random();
rand.nextInt(10); // Number between 0 and 9.

Sorting

import java.util.Arrays;
import java.util.Collections;

// Array
int[] array = new int {4, 3, 2, 4, 1};
Arrays.sort(array);

// List
List<Integer> = List.of(4, 3, 2, 4, 1);
Collections.sort(array);