unfried.
Streak:0 days XP:0

Formula sheet

Java

100 entries in 12 units. Free to use and share.

Jump to a unit (12 units)

Unit 1 Your first Java programs

The shape of a Java program

Also called main method, class header, Main.java.

Running starts at the first statement inside main. The file must be named after its public class: public class Main goes in Main.java.

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

Careful: A statement outside main (or another method) does not compile, and public class Hello in Main.java gives class Hello is public, should be declared in a file named Hello.java.

Taught in The parts of a Java program

print, println and escape sequences

Also called new line, tab, backslash, printing quotes.

WritePrints
print("A")A, line kept open
println("A")A, then the line ends
\"a double quote
\na new line
\ta tab
\\one backslash

Careful: println ends the line after its text, not before it. A single backslash before any other letter, such as "C:\eggs", does not compile.

Taught in print, println and escape sequences

Case and comments

Every name is case-sensitive: System, out, println. Capitals inside quotes are only text.

// a comment to the end of the line
/* a comment between the marks */
System.out.println("HI"); // compiles

Careful: system, Println and System.Out do not compile. A space inside a name breaks it; spaces between names and symbols don't matter.

Taught in Spelling, case and comments

Compile errors and run-time errors

javac Main.java writes Main.class (bytecode) only if the whole file compiles; java Main then runs it.

KindFoundOutput before it
Compile errorby javac, before runningnone
Run-time errorwhile runningthe lines before it
Logic errorby you, from the outputall of it, wrong

Taught in Compiling, then running

Reading a javac message

Also called compiler error, error message.

Main.java:4: error: … names the file and line; the caret ^ marks where javac noticed.

MessageUsual cause
';' expecteda statement with no semicolon
cannot find symbola misspelled or miscapitalized name
unclosed string literala missing closing quote
reached end of file while parsinga { never closed

Careful: The line named is where javac noticed, which can be after the mistake: a missing } is reported at the last line of the file.

Taught in Reading a compiler message

Joining strings and numbers with +

Also called concatenation, string plus number.

A + with a string on either side joins; two numbers add. Java works left to right, with parentheses and * first.

"Sum: " + 2 + 3     // Sum: 23
"Sum: " + (2 + 3)   // Sum: 5
1 + 2 + "3"         // 33

Careful: Once the left side is a string, every later + joins. Put a sum in parentheses to add before joining.

Taught in Joining strings and numbers

Unit 2 Variables and primitive types

Declaring and assigning a variable

Also called declaration, assignment, variable.

= works out the right side, then stores the value in the variable on the left. b = a; copies the value once.

int a = 3;      // declare: type, name, value
a = 7;          // assign: no type
int b = a;      // b gets a copy of 7

Careful: Declaring a name twice does not compile (is already defined), and 5 = x; gives unexpected type. Later changes to a never change b.

Taught in Declaring and assigning

The primitive types

Also called int, double, boolean, char, String.

An int value fits in a double (7 becomes 7.0). A variable's type is fixed when it is declared.

TypeHoldsExample
intwhole numbers42, -7
doublenumbers with a point42.0, 0.5
booleantrue or falsetrue
charone character'x'
String (a class)text"egg"

Careful: A double into an int is refused: possible lossy conversion from double to int. Double quotes always make a String, even around one letter.

Taught in Types: int, double, boolean, char, String

Integer division and remainder

Also called int division, modulo, %.

With two ints, / drops the fraction, toward zero, and % gives the remainder, with the sign of the left side. A double on either side keeps the fraction.

7 / 2      // 3
7 % 2      // 1
-7 / 2     // -3
-7 % 3     // -1
7 / 2.0    // 3.5

Careful: 5 / 9 is 0, so (f - 32) * (5 / 9) is always 0.0. Unlike Python, -7 / 2 is −3, not −4.

Taught in Integer division and remainder

Compound assignment and ++

Also called increment, decrement, +=, i++.

A compound assignment reads the variable's value, works out the new one and stores it.

WriteMeans
x += 5;x = x + 5;
x *= 2;x = x * 2;
x++;add 1
x--;subtract 1
j = i++;j gets the old i
j = ++i;j gets the new i

Careful: x += 1.5; on an int compiles and silently drops the fraction, while x = x + 1.5; does not compile.

Taught in Updating and swapping

Swapping two variables

Save one value before it is overwritten, then hand it to the other variable.

int temp = a;
a = b;
b = temp;

Careful: a = b; then b = a; leaves both holding b's old value.

Taught in Updating and swapping

Casts and precedence

Also called type cast, order of operations, (double), (int).

A cast converts the one value right after it. Order: brackets, casts, then * / %, then + -, each level left to right.

(int) 3.99           // 3
(int) -3.99          // -3
(double) 7 / 2       // 3.5
(double) (7 / 2)     // 3.0
10 / 4 * 4           // 8

Careful: A cast to int never rounds; it cuts toward zero. double d = 10 / 4; is 2.0, because the right side is worked out before it is stored.

Taught in Casting and order of operations

int overflow and long

Also called Integer.MAX_VALUE, integer overflow, long.

Past the end of its range, an int wraps around to the other end with no error. Write L on a number, 1000000L, to make it a long.

TypeRange
int (32 bits)−2,147,483,648 to 2,147,483,647
long (64 bits)about ±9.2 × 10¹⁸

Careful: long big = 1000000 * 1000000; overflows: the ints multiply before the result is stored. Put the L on a factor.

Taught in Limits: overflow and rounding error

Rounding error in doubles

Also called floating point, comparing doubles, 0.1 + 0.2.

A double keeps about 15 to 17 significant digits as a binary fraction, so most decimals are stored as the nearest value.

0.1 + 0.2                  // 0.30000000000000004
0.1 + 0.2 == 0.3           // false
Math.abs(a - b) < 1e-9     // close enough

Careful: Never test computed doubles with ==. Test whether they are within a small tolerance.

Taught in Limits: overflow and rounding error

char codes and constants

Also called Unicode, final, constant.

A char is stored as its code ('A' 65, 'a' 97, '0' 48), and arithmetic on it gives an int. A final variable is assigned once; constants are named in capitals.

'a' + 1              // 98, an int
(char) ('a' + 1)     // b
(int) 'A'            // 65
final double G = 9.81;

Careful: char c = "a"; does not compile (double quotes make a String). Assigning a final variable again gives cannot assign a value to final variable.

Taught in char codes and constants

Compile errors with variables

Names are case-sensitive: Total is not total.

MessageUsual cause
cannot find symbola misspelled name, or a use before the declaration
might not have been initializeddeclared, never given a value
is already defineddeclared twice

Careful: A variable declared in main does not start at 0. Give it a value, int sum = 0;, before reading it.

Taught in Errors with variables

Unit 3 Strings, Math and input

Calling a String method

Also called length, toUpperCase, toLowerCase, trim, dot notation.

The object, a dot, the method and brackets. Each call gives back a value of a fixed type.

Call on "Egg"Gives back
s.length()3, an int
s.toUpperCase()"EGG"
s.toLowerCase()"egg"
" hi ".trim()"hi"

Careful: Without brackets, s.length is not a call: cannot find symbol, symbol: variable length.

Taught in Calling methods on a String

charAt and substring

Also called index, slicing, StringIndexOutOfBoundsException.

Indexes count from 0 to length() - 1. substring(a, b) runs from a up to, not including, b.

String w = "python";
w.charAt(0)         // 'p'
w.substring(1, 4)   // "yth"
w.substring(2)      // "thon"

Careful: The end index is left out, and an index past the end stops the program with StringIndexOutOfBoundsException.

Taught in Characters by position: charAt and substring

Strings are immutable

Also called discarded result, trim does nothing.

String methods build a new string and give it back. Only an assignment changes what a variable holds.

s.trim();        // changes nothing
s = s.trim();    // keeps the result

Careful: A String method called on its own line compiles, and its result is thrown away without any warning.

Taught in Strings don't change

indexOf, lastIndexOf and contains

Also called find, search a string, not found.

indexOf gives the index where a match starts. Use -1 to test for "not found".

CallGives back
"banana".indexOf("an")1, the first match
"banana".lastIndexOf("an")3, the last match
"python".indexOf("z")-1, not found
"egg".contains("gg")true

Careful: A result of 0 is a match at the start, not "not found". Passing -1 on to substring stops the program.

Taught in Searching in a string

Comparing strings

Also called equals, equalsIgnoreCase, compareTo, string equality.

compareTo compares character codes from the left; capitals sort before small letters.

TestAsks
a.equals(b)same text?
a.equalsIgnoreCase(b)same text, any case?
a.compareTo(b)negative, 0 or positive: which sorts first?
a == bthe same object?

Careful: Never test text with ==: two equal strings can be two objects, giving false. compareTo can give any int, not only −1, 0 and 1.

Taught in Comparing strings

Math methods and their types

Also called Math.sqrt, Math.pow, Math.abs, Math.max, Math.round.

Static methods, called on the class Math. sqrt and pow always give a double.

CallGives back
Math.sqrt(16)4.0, a double
Math.pow(2, 10)1024.0, a double
Math.abs(-4), Math.max(3, 8)4, 8, the type given
Math.round(2.5), Math.round(-2.5)3, -2

Careful: int r = Math.pow(2, 3); does not compile (possible lossy conversion from double to int). Math.round rounds halves up, unlike Python's round.

Taught in The Math class

Random int in a range

Also called Math.random, dice roll, random number.

Math.random() gives a double from 0.0 up to, not including, 1.0.

// n values, from a to a + n - 1
(int) (Math.random() * n) + a
// a die: 1 to 6
(int) (Math.random() * 6) + 1

Careful: The brackets around Math.random() * n are needed: (int) Math.random() * 6 is always 0.

Taught in Random integers in a range

Reading input with Scanner

Also called nextInt, nextLine, nextDouble, input.

nextInt and nextDouble read a number, next one word, nextLine the rest of the current line.

import java.util.Scanner;   // above the class
Scanner in = new Scanner(System.in);
int age = in.nextInt();
in.nextLine();              // finish that line
String name = in.nextLine();

Careful: nextLine straight after nextInt gives back an empty string. A typed value of the wrong kind stops the program with InputMismatchException.

Taught in Reading input with Scanner

Format specifiers

Also called String.format, printf, decimal places, padding.

Width before the dot, decimal places after it; f for a decimal number, s for a String, a minus sign to put text on the left.

FormatValueText
%.2f3.141593.14
%6.1f98.6 98.6
%-8s"Bread"Bread, then 3 spaces
%nnoneends the line

Careful: String.format gives back text and leaves the number unchanged. %f with an int stops the program with IllegalFormatConversionException.

Taught in Formatting numbers

Unit 4 Decisions

Relational operators and boolean expressions

Also called == and =, comparison operators.

A comparison gives true or false, which a boolean variable can store. = assigns; == compares.

OperatorTrue when
a == bthe values are equal
a != bthe values differ
a < b, a <= ba is less, or less or equal
a > b, a >= ba is greater, or greater or equal

Careful: A condition must be a boolean: if (x = 5) doesn't compile for an int x. Compare computed doubles with a tolerance and strings with equals.

Taught in Boolean expressions

if and its braces

Also called block, if statement.

The if controls every statement between its braces, which run only when the test is true.

if (temp < 0) {
    System.out.println("Freezing");
    System.out.println("Gloves");
}

Careful: Without braces it controls only the next statement, and indentation changes nothing.

Taught in if and its braces

The stray semicolon

Also called empty statement.

A ; right after if (…) is an empty statement that becomes the whole body, so the block after it runs every time.

if (n > 0); {
    System.out.println("positive");
}

Careful: It compiles without any message. Only the output gives it away.

Taught in The stray semicolon

else-if chain

Also called if else, else if.

The tests are tried from the top, and only the block of the first true one runs; else runs when all are false.

if (score >= 90) {
    System.out.println("A");
} else if (score >= 80) {
    System.out.println("B");
} else {
    System.out.println("F");
}

Careful: Put the narrower test first, or its branch can never run. Separate ifs are each tested, so several can run.

Taught in if, else and else-if chains

Logical operators and short-circuit evaluation

Also called &&, || and !, and, or, not.

Write a range as two comparisons, 0 < x && x < 10. Put a guard on the left: n != 0 && 10 / n > 1 never divides by zero.

ExpressionTrue whenStops early when
a && bboth are truea is false
a \|\| bat least one is truea is true
!aa is false—

Careful: 0 < x < 10 doesn't compile. && binds tighter than ||.

Taught in And, or, not, and short-circuit evaluation

Nested ifs and the dangling else

Also called nested if, dangling else.

Without braces, an else belongs to the nearest if above it that has no else yet. Braces decide the pairing.

if (x > 10) {
    if (x > 20) {
        System.out.println("A");
    }
} else {
    System.out.println("B");
}

Careful: Lining an else up with an if doesn't pair them: Java ignores indentation.

Taught in Nested ifs and the dangling else

De Morgan's laws

Also called negating a condition, truth table.

Negate each side and swap && and ||. Two conditions are equivalent when their truth table columns match on every row.

Thisequals this
!(a && b)!a \|\| !b
!(a \|\| b)!a && !b
!(x > 5)x <= 5

Careful: !(a && b) is not !a && !b. The opposite of > is <=, not <.

Taught in De Morgan's laws

switch, break and fall through

Also called switch statement, case, arrow case.

A switch jumps to the case matching one value (such as an int, char or String), or to default. break; ends the switch.

switch (day) {
    case 1:
        System.out.println("Mon");
        break;
    default:
        System.out.println("Other");
}

Careful: Without break; a colon case falls through into the next. Arrow cases (case 1 -> …) never fall through. A case can't test a range.

Taught in switch

Unit 5 Loops

while loop

Also called loop, iteration, condition tested at the top.

The condition is tested before every pass; the block runs while it is true. This loop prints 3, 2, 1 and makes four tests.

int n = 3;
while (n > 0) {
    System.out.println(n);
    n--;
}

Careful: The test is not checked in the middle of the block, so a block that makes it false still finishes. If nothing in the block can make it false, the loop never ends.

Taught in while loops

Counters and accumulators

Also called running total, sum in a loop, count in a loop.

Declare and start the accumulator once, before the loop; add to it inside; use it after. A sum starts at 0, a product at 1, and a counter adds 1 each time.

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

Careful: Reset inside the loop, it keeps only the last pass. Declared inside the braces, it is gone after the loop: cannot find symbol.

Taught in Counters and accumulators

for loop

Also called loop control variable, counting loop.

The start runs once; the test runs before each pass; the update runs after each pass. This loop prints 0 to 4.

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

Careful: i exists only inside the loop. A ; straight after the header makes an empty loop, and the block below runs once.

Taught in for loops

Counting a loop's passes

Also called off-by-one error, how many times does it run.

Check the first pass (the start value) and the last pass (the largest value that passes the test). With a step other than 1, list the values: i = 3; i <= 12; i += 3 runs 4 times.

HeaderValues of iPasses
i = 0; i < n0 to n − 1n
i = 1; i <= n1 to nn
i = 0; i <= n0 to nn + 1
i = 1; i < n1 to n − 1n − 1

Taught in Off by one

Traversing a String

Also called loop over a string, charAt in a loop.

Indexes run from 0 to s.length() - 1. charAt returns a char, which compares with == against a char literal in single quotes.

for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    if (c == 'e') {
        count++;
    }
}

Careful: i <= s.length() throws StringIndexOutOfBoundsException on the last pass, and c == "e" doesn't compile: a char against a String.

Taught in Walking through a string

Sentinel loop

Also called read until a value, input loop.

Read once before the loop, test, use the value, and read the next one as the last line of the block. while (in.hasNextInt()) reads until the input runs out instead.

int x = in.nextInt();
while (x != -1) {
    total += x;
    x = in.nextInt();
}

Careful: Reading at the top of the block uses the sentinel as data; reading only before the loop never changes x, so the loop never ends.

Taught in Input loops, sentinels and do-while

do-while loop

Also called loop that runs at least once.

The block runs first and the test comes after it, so the block always runs at least once. Note the semicolon after the test.

do {
    tries++;
} while (tries < 0);

Careful: A while loop tests first and can run zero times. Use do-while when there is nothing to test until the block has run once.

Taught in Input loops, sentinels and do-while

Nested loops

Also called loop inside a loop, rows and columns.

The inner loop starts again and runs in full on every outer pass, so the counts multiply: 3 × 5 = 15 stars. With an inner bound j < i, add the inner counts pass by pass.

for (int r = 0; r < 3; r++) {
    for (int c = 0; c < 5; c++) {
        System.out.print("*");
    }
    System.out.println();
}

Careful: The counts don't add. The inner loop needs its own variable name: reusing i gives variable i is already defined.

Taught in Nested loops

break, continue and threshold loops

Also called exit a loop early, skip a pass, loop until.

break leaves the innermost loop at once; continue skips the rest of this pass and goes on to the next test. A threshold loop runs until a quantity crosses a line: $1000 at 7% a year takes 11 years to reach $2000.

while (balance < 2000) {
    balance *= 1.07;
    years++;
}

Careful: A break in an inner loop doesn't end the outer one. A threshold the quantity can never cross (a rate of 0%) makes a loop that never ends.

Taught in break, continue and loops until a threshold

Unit 6 Static methods

Defining and calling a method

Also called static method, method call, void method.

A method is a named block inside class Main. Writing it runs nothing; each call, the name with brackets, runs the whole body once and comes back to the line after the call.

static void greet() {
    System.out.println("Hi");
}

// in main:
greet();
greet();

Careful: The name without brackets, greet;, calls nothing and doesn't compile (not a statement). Unlike Python, the method may be written below the call.

Taught in Defining and calling a method

Parameters and arguments

Also called passing arguments.

Each parameter is declared with its type, separated by commas. A call's arguments are worked out first and copied into the parameters by position.

static void say(String s, int n) {
    for (int i = 0; i < n; i++) {
        System.out.println(s);
    }
}

say("egg", 3);

Careful: Names never have to match, and Java has no keyword arguments. A missing or mistyped argument is a compile error.

Taught in Parameters and arguments

Return type and return statement

Also called return value, return against print.

return ends the call at once, and the call stands for the returned value: square(4) + 1 is 17.

In the methodWhat the caller gets
return n * n; in an int methodthe value, to store, use or print
System.out.println(n * n);nothing: the text only appears on screen
a void methodnothing; storing the call does not compile

Careful: A call alone on a line, square(5);, throws its value away. A returned value is never printed unless the caller prints it.

Taught in Returning a value

missing return statement and unreachable statement

Also called every path must return.

A method with a return type must return on every path. javac checks paths, not values, so end an if chain with a plain else, or put a return after the if or loop.

static int bigger(int a, int b) {
    if (a > b) {
        return a;
    } else {
        return b;
    }
}

Careful: An else if that you know is always true still leaves a path javac sees as open. A statement after an unconditional return is refused as unreachable.

Taught in Every path must return

Pass by value and local variables

Also called scope, cannot find symbol.

A call copies each argument's value into its parameter, and variables declared in a method exist only in that method, during the call.

static int addOne(int n) {
    n = n + 1;
    return n;
}

// in main:
x = addOne(x);

Careful: Assigning to a parameter never changes the caller's variable, and one method can't name another's variables. Return the new value and assign it.

Taught in Pass by value and scope

Overloading

Also called method signature, overloaded methods.

Methods may share a name when their parameter types differ. The signature is the name with the parameter types, and the argument types pick the version: label('A') runs the int one.

static String label(int x) {
    return "int " + x;
}
static String label(double x) {
    return "double " + x;
}

Careful: A different return type or parameter name doesn't make a new signature: method f(int) is already defined in class Main.

Taught in Overloading

Reading a stack trace

Also called call stack, exception trace.

The message says what went wrong. The first at line is where it failed; each line below is the caller, paused at that line, down to main. Start at the first line in your own file.

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at Main.avg(Main.java:3)
    at Main.report(Main.java:6)
    at Main.main(Main.java:12)

Careful: The line named is where the problem was noticed. The bad value may have come from a caller further down.

Taught in The call stack and stack traces

Preconditions and postconditions

Also called method contract, decomposition.

The precondition is what the caller must make true before the call; the postcondition is what the method promises when it returns. Give each job its own small method.

/** n must be at least 0.
    Returns the sum of n's digits. */
static int digitSum(int n) {

Careful: Java doesn't read comments: a call that breaks the precondition compiles and may return a wrong answer with no error.

Taught in Breaking a problem into methods

Unit 7 Arrays

Making an array

Also called new array, initializer list, default values, array length.

new fills every element with a default: 0, 0.0, false, or null for Strings. An initializer list makes an array of exactly the values listed. length has no brackets.

int[] counts = new int[3];
double[] t = {21.5, 22.0, 23.5};
int n = t.length;

Careful: The length is fixed when the array is made: t.length = 4; gives cannot assign a value to final variable length. Make a new, longer array for more room.

Taught in Making an array

Indexes and ArrayIndexOutOfBoundsException

Also called last element, out of bounds, length against length().

Valid indexes run from 0 to a.length - 1. An index outside them compiles and stops the program with ArrayIndexOutOfBoundsException, naming the index and the length.

ExpressionMeaning
a[0]the first element
a[a.length - 1]the last element
a[a.length]out of bounds: stops at run time

Careful: Arrays use length, Strings length() and ArrayList size(). Java has no negative indexes.

Taught in Indexes and bounds

Traversal with an indexed for loop

Also called sum of an array, average of an array, counting.

Declare the total or counter once, before the loop; print it after. The test i < a.length stops after the last index.

int sum = 0;
for (int i = 0; i < a.length; i++) {
    sum += a[i];
}
double avg = (double) sum / a.length;

Careful: sum / a.length with two ints cuts off the fraction. i <= a.length runs one pass too many and throws.

Taught in Walking through an array

The enhanced for loop (for-each)

Also called for-each loop.

Read it as "for each int v in a". Each pass copies the next element into v. Use it for reading: sums, counts, printing.

for (int v : a) {
    System.out.println(v);
}

Careful: Assigning to v changes only the copy, and the loop gives no index. To change elements or find a position, use an indexed loop.

Taught in The for-each loop

Maximum, minimum and linear search

Also called best so far, find a value, return -1.

Start the best so far at the first element; use < for a minimum. A linear search returns i at the first match and -1 after the loop.

int best = a[0];
for (int i = 1; i < a.length; i++) {
    if (a[i] > best) {
        best = a[i];
    }
}

Careful: A start of 0 fails when every element is below it. A search that returns "not found" inside the loop gives up at the first mismatch.

Taught in Maximum, minimum and search

Array references, aliases and copies

Also called Arrays.toString, Arrays.copyOf, printing an array.

An array variable holds a reference. Assigning it copies the reference, so changes through one alias show through the other.

LineResult
int[] y = x;one array, two names
int[] y = Arrays.copyOf(x, n);a separate array of length n
Arrays.toString(x)text such as [9, 2, 3]

Careful: System.out.println(x) prints the type and a code, not the elements. Arrays needs import java.util.Arrays;.

Taught in Arrays are references

Arrays as parameters and return values

Also called passing an array to a method, returning an array.

A call copies the reference, so changes to the elements of an array parameter are seen by the caller. To give the caller a new array, return it.

static int[] squares(int n) {
    int[] s = new int[n];
    for (int i = 0; i < n; i++) {
        s[i] = i * i;
    }
    return s;
}

Careful: Assigning a new array to the parameter changes nothing for the caller.

Taught in Arrays and methods

Reversing and shifting in place

Also called reverse an array, rotate, swap elements.

Swap each element with its partner from the far end, for the first half only. To shift right, copy from the end down; to shift left, copy from the front up.

int n = a.length;
for (int i = 0; i < n / 2; i++) {
    int j = n - 1 - i;
    int t = a[i];
    a[i] = a[j];
    a[j] = t;
}

Careful: Looping to n swaps every pair back. Copying in the wrong direction overwrites values before they are read.

Taught in Shifting, reversing and copying

Unit 8 Writing classes

Class, fields and new

Also called object, instance, field.

A class describes a kind of object. Each new makes a separate instance with its own copy of every field, starting at 0, 0.0, false or null.

class Egg {
    int grams;
}

// in main:
Egg a = new Egg();
a.grams = 60;

Careful: Writing the class makes no object, and the class holds no field values of its own. Name the object: Egg.grams doesn't compile.

Taught in Classes and objects

Constructor

Also called default constructor, new with arguments.

The class's name and no return type. new makes the object, then runs the constructor whose parameters match the arguments.

Point(int x0, int y0) {
    x = x0;
    y = y0;
}

// in main:
Point p = new Point(3, 4);

Careful: void Point(…) is an ordinary method that new never runs. Writing any constructor removes the empty one Java supplies.

Taught in Constructors

this and a parameter that hides a field

Also called shadowing, this.field.

A parameter with a field's name hides the field. this.size is the field of the object being made; the plain size is the parameter.

Egg(int size) {
    this.size = size;
}

Careful: size = size; compiles and changes nothing: both sides are the parameter. With a differently named parameter, size = s; reaches the field without this.

Taught in this, and a parameter that hides a field

private fields and accessor methods

Also called encapsulation, getter, has private access.

A private field can be named only inside its class. Outside code calls methods: a.getBalance() returns a's balance.

class Account {
    private double balance;
    double getBalance() {
        return balance;
    }
}

Careful: Private is per class, not per object: a method of Account may read other.balance. Code in any other class gets balance has private access in Account.

Taught in private fields, accessors and mutators

Mutator methods with a guard

Also called deposit and withdraw, object state.

A mutator changes the object's fields. Test the request first and return before changing anything, so a refused call leaves the state as it was.

boolean withdraw(double amt) {
    if (amt > balance) {
        return false;
    }
    balance -= amt;
    return true;
}

Careful: Subtracting first and testing afterward returns false but has already changed the balance. A void method can change an object too.

Taught in Methods that change an object

toString

Also called printing an object.

println(e) and "Egg: " + e call toString and use the String it returns.

public String toString() {
    return grams + "g";
}

Careful: Without it, an object prints as its class name, @ and a hash code. It must be public, and it must return the text, not print it.

Taught in toString

References, null and NullPointerException

Also called alias, NPE.

An object variable holds a reference: b = a shares one object. null refers to no object, and a method call through it throws NullPointerException.

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Egg.getGrams()" because "e" is null

Careful: Declaring Egg e; as a field, or making new Egg[3], makes no egg: those start as null. Test e != null before calling a method on e.

Taught in References, null and NullPointerException

== and equals on objects

Also called comparing objects, same object.

String writes its own equals, so s1.equals(s2) compares the characters.

ComparisonAsks
a == bdo both refer to the same object?
a.equals(b), class writes no equalsthe same as ==
a.equals(b), class writes equalswhat that method compares, such as the fields

Careful: Two objects made by two news are never ==, however equal their fields.

Taught in == and equals on objects

static fields and class methods

Also called static variable, class method, non-static from a static context.

A static field is one variable for the whole class; a static method is called on the class and runs with no object.

class Egg {
    static int made = 0;
    static int count() {
        return made;
    }
}

// in main:
int n = Egg.count();

Careful: A static method has no this, so it can't use instance fields or methods directly: non-static variable … cannot be referenced from a static context.

Taught in static fields and methods

Unit 9 ArrayList and wrapper classes

Making and printing an ArrayList

Also called ArrayList, type parameter, import ArrayList.

The type in angle brackets is the element type. A new list is empty; add puts an element on the end, add(i, x) at index i. This prints [Cy, Ada] and 2.

import java.util.ArrayList;

ArrayList<String> names =
        new ArrayList<>();
names.add("Ada");
names.add(0, "Cy");
System.out.println(names);
System.out.println(names.size());

Careful: Lists use methods, not brackets: names[0] doesn't compile (array required). Use names.get(0).

Taught in Making an ArrayList

Wrapper classes and autoboxing

Also called Integer, Double, unboxing, ArrayList<int>.

A type parameter must be a class: ArrayList<Integer>, never ArrayList<int>. Java boxes an int when it goes into the list and unboxes it when it comes out.

PrimitiveWrapper class
intInteger
doubleDouble
booleanBoolean
charCharacter

Careful: Boxing never changes the type: add(5) on an ArrayList<Double> fails; write 5.0. Compare two Integers with equals: == asks "the same object?" and usually fails from 128 on.

Taught in Wrapper classes and autoboxing

Integer.parseInt

Also called String to int, NumberFormatException.

Turns a String of digits into an int, so Integer.parseInt("42") + 1 is 43.

int n = Integer.parseInt("42");

Careful: Text that isn't a whole number, such as "3.5", throws NumberFormatException when the program runs.

Taught in Wrapper classes and autoboxing

add at an index, set and remove

Also called insert, replace, remove by index, remove by value.

Inserting moves every later element up one index; removing moves them down one. set moves nothing.

Call on [a, b, c]Leaves
add(1, "x")[a, x, b, c]
set(1, "x")[a, x, c]
remove(1)[a, c]
remove("a")[b, c]

Careful: On an ArrayList<Integer>, remove(1) removes index 1. To remove the value 1, write remove(Integer.valueOf(1)).

Taught in add at an index, set and remove

length, length() and size()

Also called traversing an ArrayList, IndexOutOfBoundsException.

A list's indexes run from 0 to size() - 1. Loop with i < list.size() and list.get(i), or with for (String s : list) when the index isn't needed.

ValueHow many
array aa.length
String ss.length()
ArrayList listlist.size()

Careful: get(list.size()) is one past the end and throws IndexOutOfBoundsException.

Taught in Traversing an ArrayList

Removing elements in a loop

Also called remove while traversing, ConcurrentModificationException.

Loop backward, so a removal moves only elements already checked. Going forward works only if k moves on when nothing was removed.

for (int k = nums.size() - 1; k >= 0; k--) {
    if (nums.get(k) % 2 == 0) {
        nums.remove(k);
    }
}

Careful: A forward loop with k++ on every pass skips the element after each removal. Removing inside a for-each over the list throws ConcurrentModificationException.

Taught in Removing while you traverse

Lists of objects

Also called ArrayList of objects, contains and equals.

Each element is an object, so e.grams reads its field, and printing the list uses each element's toString. Start a best-so-far search at a real element.

Egg best = eggs.get(0);
for (Egg e : eggs) {
    if (e.grams > best.grams) {
        best = e;
    }
}

Careful: contains, indexOf and remove(x) use equals. A class with no equals of its own matches only the very same object, so eggs.contains(new Egg(63)) is false.

Taught in Lists of objects

Array or ArrayList

Also called choosing a collection.

Use an array when the number of values is fixed and known, a list when it changes. A new array starts full of zeros; a new list starts empty.

JobArrayArrayList
reada[i]list.get(i)
replacea[i] = x;list.set(i, x);
counta.lengthlist.size()
grownot possiblelist.add(x);

Careful: set(0, x) on a new, empty list throws IndexOutOfBoundsException: add the first element with add.

Taught in Arrays or ArrayList?

Unit 10 2D arrays, searching and sorting

Making and indexing a 2D array

Also called 2D array, grid, int[][].

g.length is the number of rows (3) and g[0].length the number of columns (4). g[r][c] is row r, column c, each counted from 0, row first.

int[][] g = new int[3][4];
int[][] m = {{1, 2, 3},
        {4, 5, 6}};
m[1][2] = 60;

Careful: The first index is the row, not the column. Indexes run to length - 1; one more throws ArrayIndexOutOfBoundsException.

Taught in 2D arrays

Row-major and column-major traversal

Also called nested loops over a grid, column sums.

Rows outside and columns inside visits the grid row by row (row-major order); columns outside, as here, goes down each column (column-major order). The inner loop runs fully on every outer pass, so a 3 × 4 grid gets 12 visits.

for (int c = 0; c < g[0].length; c++) {
    int sum = 0;
    for (int r = 0; r < g.length; r++) {
        sum += g[r][c];
    }
}

Careful: Bounding the column loop by g.length counts rows. It only works when the grid is square.

Taught in Traversing a 2D array

Linear search

Also called sequential search, find the index.

Returns the index of the first match. Worst case (target last or missing): n comparisons; best case (target first): 1.

static int find(int[] a, int t) {
    for (int i = 0; i < a.length; i++) {
        if (a[i] == t) {
            return i;
        }
    }
    return -1;
}

Careful: An else { return -1; } inside the loop gives up at the first mismatch. Return -1 only after the loop.

Taught in Linear search

Binary search

Also called lo hi mid, halving search.

Each pass halves the range, so n sorted values need at most about log₂ n passes: 7 for 100, 10 for 1,000, 20 for 1,000,000.

int lo = 0;
int hi = a.length - 1;
while (lo <= hi) {
    int mid = (lo + hi) / 2;
    if (a[mid] == t) {
        return mid;
    } else if (a[mid] < t) {
        lo = mid + 1;
    } else {
        hi = mid - 1;
    }
}
return -1;

Careful: The array must be sorted; on unsorted data it may miss a value that is there. lo = mid can loop forever, lo < hi skips the last candidate, and hi = a.length can go out of bounds.

Taught in Binary search

Selection sort

Also called select the smallest, swap into place.

Pass i swaps the smallest value from index i on into index i. After pass k the first k positions are final. {5, 2, 9, 1, 7} becomes [1, 2, 9, 5, 7] after pass 1.

for (int i = 0; i < a.length - 1; i++) {
    int min = i;
    for (int j = i + 1; j < a.length; j++) {
        if (a[j] < a[min]) {
            min = j;
        }
    }
    int t = a[i];
    a[i] = a[min];
    a[min] = t;
}

Careful: One pass places one value, not the whole array. The swap goes after the inner loop; inside it, the sort goes wrong.

Taught in Selection sort

Insertion sort

Also called insert into the sorted part, shift right.

Pass i inserts a[i] into the sorted left part, shifting bigger values one place right. {5, 2, 9, 1, 7} becomes [2, 5, 9, 1, 7] after pass 1. On already sorted data it makes one comparison per pass.

for (int i = 1; i < a.length; i++) {
    int key = a[i];
    int j = i - 1;
    while (j >= 0 && a[j] > key) {
        a[j + 1] = a[j];
        j--;
    }
    a[j + 1] = key;
}

Careful: The left part is sorted but not final: a later, smaller value can still move in front. key goes to a[j + 1]; a[j] can be index -1.

Taught in Insertion sort

Step counts of searches and sorts

Also called growth rate, comparisons, n squared.

For 10, 100 and 1,000 values: linear search 10, 100 and 1,000 steps; binary search 4, 7 and 10 passes; selection sort 45, 4,950 and 499,500 comparisons.

AlgorithmSteps for n valuesWhen n doubles
Linear search, worst casendoubles
Binary search, at mostabout log₂ none more pass
Selection sortn(n − 1)/2 comparisonsabout 4 times
Insertion sort, reverse ordern(n − 1)/2 comparisonsabout 4 times

Careful: Sorting so that binary search can be used pays off only when many searches follow: one sort costs far more than one linear search.

Taught in Counting steps

Arrays.sort and Arrays.binarySearch

Also called library sort, sort Strings.

Arrays.sort puts the array in increasing order in place; Strings sort by character codes, capitals first. Arrays.binarySearch returns the index in a sorted array, or a negative number when the value is missing.

Arrays.sort(a);
int k = Arrays.binarySearch(a, 9);

Careful: Arrays.sort returns nothing, so a = Arrays.sort(a); doesn't compile. On an unsorted array binarySearch may report a value missing that is there.

Taught in Sorting with the library

Unit 11 Inheritance, polymorphism and interfaces

Subclass with extends

Also called inheritance, is-a, superclass.

A Dog has every field and method of Animal, plus bark(). Use extends when the subclass is a kind of the superclass.

class Dog extends Animal {
    String bark() {
        return getName() + ": Woof";
    }
}

Careful: A private field of the superclass can't be named in the subclass: use the inherited accessor. When one class only holds another (a car has an engine), use a field instead.

Taught in extends and is-a

Calling the superclass constructor with super

Also called super constructor, constructor chaining.

Constructors are not inherited. super(…) builds the superclass part and must be the first statement; superclass constructors run before subclass ones.

Dog(String n, int a) {
    super(n);
    age = a;
}

Careful: With no super(…) written, Java calls super(), which fails when the superclass has no constructor without parameters.

Taught in Constructors and super

Overriding and @Override

Also called override, annotation, super.method().

Same name and parameter types as the inherited method: the subclass's version replaces it. @Override makes javac check that it really overrides; super.sound() calls the replaced version.

class Puppy extends Dog {
    @Override
    String sound() {
        return super.sound() + "!";
    }
}

Careful: Different parameter types make an overload, a second method. Without @Override, a misspelled name compiles as a new method.

Taught in Overriding methods

Overriding equals(Object)

Also called equals, Object class, instanceof.

Every class inherits toString() and equals(Object) from Object; Object's equals is ==. Override with the exact header, public included.

@Override
public boolean equals(Object o) {
    if (!(o instanceof Egg)) {
        return false;
    }
    Egg e = (Egg) o;
    return grams == e.grams;
}

Careful: equals(Egg o) overloads instead: contains and other library code still call Object's version. == keeps comparing references.

Taught in The Object class: toString and equals

Polymorphism and dynamic binding

Also called which method runs, superclass variable.

When the call runs, the class of the object decides which override runs, whatever the variable's declared type.

Animal a = new Dog();
System.out.println(a.sound());   // Woof

Careful: The declared type still decides what compiles: only methods the declared type has can be called through it.

Taught in Polymorphism: the object decides

Declared type and casting

Also called cast, instanceof, ClassCastException, downcast.

Calls compile against the declared type. A cast gives the same object a subclass type, so that type's methods compile; instanceof tests the object's class first.

if (a instanceof Dog) {
    Dog d = (Dog) a;
    d.fetch();
}

Careful: A cast changes no object. A wrong one compiles when the classes are related and throws ClassCastException when it runs.

Taught in What the declared type allows, and casting

Abstract classes and abstract methods

Also called abstract, cannot be instantiated.

An abstract method has no body; a class with one must be abstract. It can't be made with new, but can be a variable's type and can hold fields and finished methods.

abstract class Shape {
    abstract double area();
    String describe() {
        return "Area: " + area();
    }
}

Careful: A subclass that doesn't write every abstract method must be abstract itself, or javac refuses it.

Taught in Abstract classes

Interfaces and implements

Also called interface, implements.

An interface lists public abstract methods. A class implements it by writing each one as public; it may implement several, separated by commas.

interface Shape {
    double area();
}
class Rect implements Shape {
    public double area() {
        return w * h;
    }
}

Careful: implements gives no code: every method must be written. Leaving out public gives attempting to assign weaker access privileges. An interface can't be made with new.

Taught in Interfaces

Comparable and compareTo

Also called Collections.sort, sorting objects.

a.compareTo(b) is negative when a comes first, zero for a tie, positive when a comes after. Collections.sort(list) uses it.

class Egg implements Comparable<Egg> {
    public int compareTo(Egg o) {
        return grams - o.grams;
    }
}

Careful: Only the sign matters, not the size: it need not be −1 or 1. Swapping the subtraction sorts the other way.

Taught in Comparable and sorting objects

Unit 12 Exceptions, files and recursion

Common run-time exceptions

Also called unchecked exceptions, exception names.

These are unchecked: javac compiles code that may throw them. Read the message, then the first at Main.… line in your own file.

ExceptionThrown by
ArithmeticExceptionan int divided by zero
ArrayIndexOutOfBoundsExceptiona[5] on an array of length 5
NullPointerExceptiona method called through a null variable
NumberFormatExceptionInteger.parseInt("3.5")
InputMismatchExceptionnextInt() reading abc
ClassCastExceptiona cast to a class the object isn't

Careful: The line a trace names is where the problem was noticed. The bad value may come from a caller further down the trace.

Taught in Exceptions and stack traces

try and catch

Also called catching an exception, catch block.

Lines in the try run until one throws; the rest of the try is skipped, the matching catch runs, and the program carries on below it.

try {
    int v = Integer.parseInt(s);
    total += v;
} catch (NumberFormatException e) {
    System.out.println("skip " + s);
}

Careful: Control never goes back into the try. A try around a whole loop ends the loop at the first exception; put it inside to skip one item. Catch the specific type, not Exception.

Taught in try and catch

Checked exceptions and throws

Also called FileNotFoundException, unreported exception, throws clause.

A checked exception must be caught or declared with throws, or the code doesn't compile: unreported exception FileNotFoundException; must be caught or declared to be thrown.

public static void main(String[] args)
        throws FileNotFoundException {

Careful: throws doesn't handle the exception: if the file is missing at run time, the program still stops with a trace. Each method that may throw it must catch or declare it.

Taught in Checked exceptions and throws

Throwing an exception

Also called throw, IllegalArgumentException, precondition check.

throw makes an exception and throws it at once. The method stops, and the exception passes back through the callers until a catch handles it.

if (x < 0) {
    throw new IllegalArgumentException(
            "negative: " + x);
}

Careful: throw is a statement in a body; throws goes in a header. Returning −1 instead lets a caller use a wrong value without noticing.

Taught in Throwing an exception

Reading a text file line by line

Also called Scanner and File, split, hasNextLine.

hasNextLine() is true while a line is left; nextLine() returns it without the line break; split(",") gives the fields as Strings.

Scanner in = new Scanner(
        new File("scores.txt"));
while (in.hasNextLine()) {
    String line = in.nextLine();
    String[] p = line.split(",");
}

Careful: Fields are Strings until Integer.parseInt reads them. split keeps empty fields, and a line with no comma has no p[1].

Taught in Reading a text file

Base case and recursive case

Also called recursion, StackOverflowError.

The base case is answered without a call; every other call works on a smaller input that moves toward it. Each call has its own parameters.

static int sumTo(int n) {
    if (n == 0) {
        return 0;
    }
    return n + sumTo(n - 1);
}

Careful: A base case that is missing or never reached (an odd n stepping by 2 past 0) fills the stack: StackOverflowError.

Taught in Recursion: a method that calls itself

Work before and after the recursive call

Also called order of output in recursion, call tree.

A line before the recursive call runs on the way down, in call order. A line after it waits until the call returns, so it runs on the way back up, reversed: up(3) that prints after its call prints 1, 2, 3.

Careful: Count calls with the call tree, not the depth: fib(n) makes two calls each time, and fib(10) makes 177 calls.

Taught in Tracing recursion

Merge sort

Also called split and merge.

Split the array in half, sort each half the same way, and merge the two sorted halves by taking the smaller front number each time. A piece of one number is sorted already.

Careful: The halving takes about log₂ n levels (10 for 1,024 numbers), not n levels.

Taught in Recursion on strings and arrays