Introduction

Getting Started · Java 1

What Java Is

Java is a compiled, object-oriented, strongly typed language. You write source code in a .java file, the compiler turns it into bytecode (a .class file), and the Java Virtual Machine (JVM) runs that bytecode on any computer. That is why the same program runs on Windows, Mac and Linux without changes.

What you need
Three words you will hear constantly
  • The JDK (Java Development Kit), free from Oracle or as OpenJDK. It includes the compiler javac and the runner java.
  • An editor or IDE: VS Code with the Java extension, IntelliJ IDEA Community, or Eclipse. An IDE compiles for you and underlines mistakes as you type.
  • Source code — what you type, in .java files
  • Bytecode — what the compiler produces, in .class files
  • JVM — the program that runs the bytecode

Your First Program

Every Java program is made of classes. The one you run must have a main method with exactly this signature. The file name must match the class name, capital letters included: this class goes in HelloPrinter.java.

HelloPrinter.java

public class HelloPrinter
{
    public static void main(String[] args)
    {
        // Display a greeting in the console window
        System.out.println("Hello, World!");
    }
}

Compile and run from a terminal

javac HelloPrinter.java
java HelloPrinter
Hello, World!

Read it line by line

  • public class HelloPrinter declares a class everyone can use.
  • public static void main(String[] args) is where the program starts. static: no object needed; void: returns nothing.
  • System.out.println(...) calls the println method of the System.out object.
  • Braces { } group statements. Every statement ends with a semicolon.

Comments and Style

Comments

// One line, to the end of the line

/* Several lines,
   between the markers */

/**
 * A documentation comment, read by the javadoc tool.
 * Put one above every class and method.
 */

Conventions

  • Class names in UpperCamelCase: BankAccount
  • Variables and methods in lowerCamelCase: totalScore, printBalance
  • Constants in ALL_CAPS: MAX_SIZE
  • One statement per line, indent the body of every brace pair, and use blank lines between methods.

Three Kinds of Errors

KindWhen it shows upExample
Compile-time (syntax) errorWhen you compile; the program will not run until it is fixedA missing semicolon, system.out.println with a small s, a misspelled variable
Run-time error (exception)While the program runs; it stops with a messageDividing an integer by zero, reading past the end of an array
Logic errorNever announced; the program runs and gives the wrong answerAdding when you meant to subtract, an off-by-one in a loop

What the messages look like

Average.java, line 6 missing its semicolon

Average.java:6: error: ';' expected
        System.out.println(total / count)
                                         ^
1 error

The same program, fixed, run with count still 0

Exception in thread "main" java.lang.ArithmeticException: / by zero
        at Average.main(Average.java:6)
  • 1. A compiler message names the file and line (Average.java:6), says what it expected, and puts a caret under the spot. Fix the first error and recompile; later ones are often echoes of it.
  • 2. A run-time message names the exception (ArithmeticException), its detail (/ by zero), and then a list of at lines. The top at line is where it happened; the ones below are the calls that led there.
  • 3. No message at all but a wrong answer is a logic error: trace the code by hand with a tiny input, or print intermediate values.

Java is case sensitive. String, string and STRING are three different names, and only the first one exists. system.out.println fails with error: package system does not exist.

Programming with Numbers and Strings

Getting Started · Java 1

Variables and Types

A variable has a type, a name and a value. You must declare the type before you use the variable, and the type never changes.

int cansPerPack = 6;          // whole number
double canVolume = 0.335;     // number with a fractional part
boolean done = false;         // true or false
char grade = 'A';             // a single character, in single quotes
String name = "Harry";        // text, in double quotes
final int MAX_SIZE = 100;     // a constant: cannot be changed later
TypeHoldsRange or notes
intWhole numbersAbout ±2.1 billion; overflow wraps around silently
longBig whole numbersAbout ±9 × 1018; write literals with an L: 10000000000L
doubleDecimal numbersAbout 15 significant digits; 0.1 + 0.2 is not exactly 0.3
booleantrue or falseThe result of every comparison
charOne characterSingle quotes: 'a'; really a number (its Unicode value)
StringTextA class, not a primitive type, so its methods use dot notation

Arithmetic

Operators

OperatorMeaningExample
+ - *Add, subtract, multiply7 * 3 → 21
/Division. Integer ÷ integer drops the fraction7 / 3 → 2, but 7.0 / 3 → 2.333…
%Remainder (modulus)7 % 3 → 1; n % 2 == 0 tests for even
++ --Add or subtract 1count++; is count = count + 1;
+= -= *= /=Combine and assigntotal += price;

Casts and Math

double price = 19.99;
int dollars = (int) price;        // 19: the cast truncates
int rounded = (int) Math.round(price);   // 20

double r = Math.sqrt(2);          // 1.4142...
double p = Math.pow(2, 10);       // 1024.0
int big = Math.max(3, 9);         // 9
double a = Math.abs(-4.5);        // 4.5
int dice = (int) (Math.random() * 6) + 1;   // 1 to 6

The classic mistake: double average = sum / count; with two int variables divides first, as integers, and then stores a whole number in the double. Fix it with a cast: (double) sum / count.

Strings

String greeting = "Hello";
int n = greeting.length();            // 5
char first = greeting.charAt(0);      // 'H'  (positions start at 0)
String sub = greeting.substring(1, 3);   // "el" (from 1 up to, not including, 3)
int where = greeting.indexOf("l");    // 2, or -1 if not found
String loud = greeting.toUpperCase(); // "HELLO"
String both = greeting + ", World";   // concatenation
String mixed = "Total: " + 3 + 4;     // "Total: 34"  (left to right!)
String sum = "Total: " + (3 + 4);     // "Total: 7"
boolean same = greeting.equals("Hello");   // compare with equals, never ==

Converting between numbers and text

int count = Integer.parseInt("42");
double price = Double.parseDouble("3.95");
String text = String.valueOf(42);      // or "" + 42

Escape sequences

WriteGet
\"a double quote inside a string
\\one backslash
\na new line
\ta tab

Input and Formatted Output

Volume.java

import java.util.Scanner;

public class Volume
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("Please enter the number of bottles: ");
        int bottles = in.nextInt();
        System.out.print("Price per bottle: ");
        double price = in.nextDouble();
        double total = bottles * price;
        System.out.printf("Total: $%.2f for %d bottles%n", total, bottles);
    }
}
FormatMeaningExample
%dInteger%5d right-aligns in 5 columns
%fDecimal%.2f shows 2 decimals; %8.2f in 8 columns
%sString%-10s left-aligns in 10 columns
%nNew lineUse instead of \n in printf

in.nextLine() reads a whole line, including spaces; in.next() reads one word. Mixing nextInt() and nextLine() is a common trap: the leftover newline after the number is read as an empty line. Call in.nextLine() once to consume it.

Decisions

Control Flow · Java 1

The if Statement

if (floor > 13)
{
    actualFloor = floor - 1;
}
else if (floor == 13)
{
    System.out.println("There is no 13th floor.");
}
else
{
    actualFloor = floor;
}
Relational operators
Boolean operators
JavaMathNote
> >=> ≥
< <=< ≤
===Two equals signs. One = assigns.
!=≠
OperatorTrue when
a && bboth are true (and)
a || bat least one is true (or)
!aa is false (not)

&& and || short-circuit: in x != 0 && 1 / x > 2, the division is skipped when x is 0, so it is safe.

Comparing Strings and Decimals

if (word.equals("quit"))           // not word == "quit"
if (word.equalsIgnoreCase("Quit"))
if (word.compareTo(other) < 0)     // word comes first alphabetically

final double EPSILON = 1E-12;
if (Math.abs(x - y) < EPSILON)     // decimals: compare with a tolerance
String typed = new Scanner(System.in).next();   // user types quit
System.out.println(typed == "quit");             // false: a different String object
System.out.println(typed.equals("quit"));        // true: same letters
System.out.println(0.1 + 0.2 == 0.3);            // false
System.out.println(0.1 + 0.2);                   // 0.30000000000000004

== on strings compares addresses, not letters. It sometimes appears to work (two identical literals in the source share one object) and then fails later, typically on text read from the user or a file. Always use equals. Comparing strings with < does not compile at all: error: bad operand types for binary operator '<'; use compareTo.

The switch Statement

Classic form

switch (digit)
{
    case 1: name = "one"; break;      // break: leave the switch here
    case 2: name = "two"; break;      // drop it and digit 2 would also run default
    default: name = "many"; break;    // runs for every other value
}

Arrow form (Java 14 and later)

String name = switch (digit)
{
    case 1 -> "one";
    case 2 -> "two";
    default -> "many";
};

In the classic form a missing break falls through into the next case. The arrow form has no fall-through and can return a value, so prefer it when your course allows it.

Mistakes to Watch For

  • if (x = 5) does not compile in Java (good): error: incompatible types: int cannot be converted to boolean. But if (done = true) does compile, and it always runs. Write if (done).
  • A semicolon right after the condition, if (x > 0);, ends the if. The block below always runs.
  • Dangling else: an else belongs to the nearest if. Use braces every time and this cannot bite you.
  • Testing 0 < x < 10 is not Java: error: bad operand types for binary operator '<', because 0 < x is a boolean that cannot be compared with 10. Write 0 < x && x < 10.
  • Using a variable that is only assigned inside the branches: error: variable grade might not have been initialized. Give it a value before the if, or make sure every branch, including else, assigns it.
  • Ranges: order the tests so each one only has to check one boundary, from largest down or smallest up.
// Letter grade: each test assumes the earlier ones failed
if (score >= 90) { grade = "A"; }
else if (score >= 80) { grade = "B"; }
else if (score >= 70) { grade = "C"; }
else { grade = "F"; }

Loops

Control Flow · Java 1

The Three Loops

LoopUse it whenShape
whileYou do not know how many times; stop when a condition changeswhile (balance < TARGET) { ... }
forYou count: a known number of times, or over the positions of an array or stringfor (int i = 0; i < 10; i++) { ... }
doThe body must run at least once, such as asking for input until it is validdo { ... } while (value <= 0);
// while: years until the balance doubles
int year = 0;
while (balance < 2 * initial)              // tested before every turn
{
    year++;
    balance = balance + balance * RATE / 100;   // moves toward the exit
}

// for: the count is known
for (int i = 1; i <= 10; i++)
{
    System.out.println(i + " squared is " + i * i);
}

// do: at least once
int value;
do
{
    System.out.print("Enter a positive number: ");
    value = in.nextInt();
}
while (value <= 0);                         // tested AFTER the body
1 squared is 1
2 squared is 4
...
10 squared is 100

Choosing a loop

  • 1. Do you know before the loop starts how many times it runs (a count, a.length, s.length())? Use for.
  • 2. Do you want every element of an array or list and never its position? Use the enhanced for (int v : values).
  • 3. Otherwise, when the stop depends on something computed as you go (a balance, input, a guess), use while, and make sure the body changes a variable named in the condition.
  • 4. Must the body run at least once before the test makes sense (read, then check)? Use do. Forgetting the semicolon after its while (...) gives error: ';' expected.

Common Loop Algorithms

Sum, average, count

double total = 0;
int count = 0;
while (in.hasNextDouble())
{
    double input = in.nextDouble();
    total = total + input;
    count++;
}
double average = 0;
if (count > 0) { average = total / count; }

Maximum and minimum

double largest = in.nextDouble();   // start with the first value
while (in.hasNextDouble())
{
    double input = in.nextDouble();
    if (input > largest)
    {
        largest = input;
    }
}

Sentinel value

// Stop at a value that cannot be real data
System.out.print("Enter salaries, -1 to finish: ");
double salary = in.nextDouble();
while (salary != -1)
{
    sum += salary;
    salary = in.nextDouble();
}

Prompting until a flag is set

boolean done = false;
while (!done)
{
    String input = in.next();
    if (input.equals("Q")) { done = true; }
    else { process(input); }
}

Nested Loops and Loop Control

Nested loops: a table

for (int row = 1; row <= 3; row++)
{
    for (int col = 1; col <= 4; col++)
    {
        System.out.printf("%4d", row * col);
    }
    System.out.println();   // end the row
}
   1   2   3   4
   2   4   6   8
   3   6   9  12

break and continue

for (int i = 0; i < n; i++)
{
    if (values[i] < 0) { continue; }  // skip this turn
    if (values[i] == target) { break; }   // leave the loop
    total += values[i];
}

Both are legal, but many courses ask you to express the exit in the condition instead. break leaves only the innermost loop.

Off-by-One and Other Traps

  • Counting from 0 to n - 1 with <, or from 1 to n with <=. Mixing them runs one time too many or too few. Trace a tiny case (n = 2) by hand.
  • A loop whose condition never changes is infinite. Make sure the body moves toward the exit.
  • Floating-point counters drift: for (double x = 0; x != 1; x += 0.1) never stops. Count with an integer and compute the double inside.
  • i++ inside for (...; ...; i++) runs after each body, so i is already one past the end when the loop finishes.
  • The variable declared in a for header exists only inside that loop. Using i after the closing brace gives error: cannot find symbol.
  • for (int i = 0; i <= a.length; i++) compiles, then stops on the last turn with ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5. Valid positions end at a.length - 1, so the test is <.
  • A semicolon after the header, for (int i = 0; i < n; i++);, is an empty loop; the block below runs once with i == n.
  • Reading with in.nextInt() when the next token is not a number throws java.util.InputMismatchException; guard the loop with in.hasNextInt().

Functions (Methods)

Control Flow · Java 1

Why Methods

In Java a function is called a method. A method packages a computation under a name so you can call it from many places, test it on its own, and read the program at a higher level. Static methods belong to the class; you call them by name inside the same class, or as ClassName.method(...) from elsewhere.

/**
 * Computes the volume of a cube.
 * @param sideLength the length of one side
 * @return the volume
 */
public static double cubeVolume(double sideLength)
{
    double volume = sideLength * sideLength * sideLength;
    return volume;
}

public static void main(String[] args)
{
    double result = cubeVolume(2);      // the call; 2 is the argument
    System.out.println(result);         // 8.0
}
PartIn the exampleRules
Return typedoubleThe type of the value the method gives back; void for none
NamecubeVolumelowerCamelCase, usually a verb or what it computes
Parametersdouble sideLengthVariables that receive the arguments, each with its own type
Bodybetween the bracesMust return a value of the declared type on every path, unless void; otherwise error: missing return statement

Writing a method, step by step

  • 1. Say in one sentence what it computes, and name it for that: cubeVolume, isValidScore, printReport.
  • 2. The parameters are the values that differ from call to call, each with a type. Anything you can compute from them belongs in the body.
  • 3. Pick the return type from what comes back: double for a computed number, boolean for a test, void when the method only prints. Do not mix printing and returning in one method.
  • 4. Write the documentation comment, then the body, ending in return (unless void).
  • 5. Test it alone from a small main with inputs whose answers you know: cubeVolume(1) is 1.0, cubeVolume(2) is 8.0.

Parameters Are Passed by Value

Numbers are copied

public static void addInterest(double balance, double rate)
{
    balance = balance + balance * rate / 100;   // changes the copy only
}
// caller:
double savings = 1000;
addInterest(savings, 5);
System.out.println(savings);   // still 1000

Objects: the reference is copied

public static void addInterest(BankAccount account, double rate)
{
    account.deposit(account.getBalance() * rate / 100);  // changes the object
}
// caller:
BankAccount acct = new BankAccount(1000);
addInterest(acct, 5);
System.out.println(acct.getBalance());   // 1050.0

A method can never change which variable the caller passed, but it can change the inside of an object that variable refers to. Return the new value when you need to update a number.

Scope, Overloading and Stepwise Refinement

Scope

public static void main(String[] args)
{
    int sum = 0;                  // visible in main only
    for (int i = 1; i <= 10; i++) // i exists only in this loop
    {
        sum += square(i);
    }
    // i is gone here
}

public static int square(int x)   // x and result exist only here
{
    int result = x * x;
    return result;
}

Overloading

public static double area(double radius)
{
    return Math.PI * radius * radius;
}

public static double area(double width, double height)
{
    return width * height;
}
// Same name, different parameter lists: the compiler picks by the arguments.

Stepwise refinement: write main as a list of calls to methods that do not exist yet, each named for one job (readScores, computeAverage, printReport), then write each method. Keep methods short enough to read without scrolling, and give every one a documentation comment.

Mistakes to watch for

  • Wrong number or type of arguments: cubeVolume() gives error: method cubeVolume in class Demo cannot be applied to given types; followed by the required and found lists. Read those two lines.
  • Calling an instance method from static main without an object: error: non-static method deposit(double) cannot be referenced from a static context. Either make the method static or create an object and call it on that.
  • Using a method’s local variable from the caller: error: cannot find symbol. Locals vanish when the method returns; return the value instead.
  • Returning a double from a method declared int: error: incompatible types: possible lossy conversion from double to int. Change the return type or cast on purpose.
  • Declaring without assigning and then using: error: variable sum might not have been initialized. Locals have no default value; write int sum = 0;.
  • A return inside the for loop ends the method on the first turn. Move it after the loop.

Lists: Arrays and ArrayList

Data · Java 1

Arrays

An array holds a fixed number of values of one type. Positions (indexes) start at 0 and end at length - 1.

double[] values = new double[10];       // ten zeros
int[] primes = { 2, 3, 5, 7, 11 };      // filled on creation
values[0] = 32;                         // first element
values[9] = 3.5;                        // last element
int n = values.length;                  // 10 (no parentheses: a field, not a method)
values[10] = 1;   // ArrayIndexOutOfBoundsException: 10 is past the end

Visiting every element

// With an index, when you need the position
for (int i = 0; i < values.length; i++)
{
    System.out.println(i + ": " + values[i]);
}

// Enhanced for, when you only need the value
double total = 0;
for (double v : values)
{
    total += v;
}

Common array algorithms

// maximum
double largest = values[0];
for (int i = 1; i < values.length; i++)
{
    if (values[i] > largest) { largest = values[i]; }
}

// linear search
int pos = -1;
for (int i = 0; i < values.length && pos == -1; i++)
{
    if (values[i] == target) { pos = i; }
}

// swap two elements
double temp = values[i];
values[i] = values[j];
values[j] = temp;

Partially filled arrays

final int CAPACITY = 1000;
double[] values = new double[CAPACITY];
int currentSize = 0;      // how many are in use
while (in.hasNextDouble() && currentSize < CAPACITY)
{
    values[currentSize] = in.nextDouble();
    currentSize++;
}
// loop to currentSize, never to values.length

Two-dimensional arrays

int[][] board = new int[3][4];     // 3 rows, 4 columns
board[1][2] = 7;
for (int r = 0; r < board.length; r++)
{
    for (int c = 0; c < board[r].length; c++)
    {
        System.out.print(board[r][c] + " ");
    }
    System.out.println();
}

ArrayList: a List That Grows

import java.util.ArrayList;

ArrayList<String> names = new ArrayList<>();
names.add("Emily");               // append
names.add("Bob");
names.add(1, "Cindy");            // insert at position 1
String first = names.get(0);      // "Emily"
names.set(0, "Ann");              // replace
names.remove(2);                  // remove by position, later ones shift down
int size = names.size();          // a method, with parentheses
for (String name : names) { System.out.println(name); }

Arrays vs ArrayList

ArrayArrayList
SizeFixed at creationGrows and shrinks
Lengtha.lengthlist.size()
Reada[i]list.get(i)
Writea[i] = x;list.set(i, x);
Element typesPrimitives or objectsObjects only: ArrayList<Integer>, not <int>

Wrapper classes and autoboxing

ArrayList<Integer> scores = new ArrayList<>();
scores.add(95);            // int 95 is boxed into an Integer
int top = scores.get(0);   // unboxed back to int
double sum = 0;
for (int s : scores) { sum += s; }

Integer, Double, Boolean and Character wrap the primitive types so they can live in collections. Java converts back and forth automatically.

Useful Library Calls

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

System.out.println(Arrays.toString(primes));   // [2, 3, 5, 7, 11]
Arrays.sort(values);                            // ascending, in place
int[] copy = Arrays.copyOf(primes, primes.length);   // a real copy
Collections.sort(names);                        // sorts an ArrayList
Collections.reverse(names);
boolean has = names.contains("Bob");
int where = names.indexOf("Bob");               // -1 if absent

Assigning an array does not copy it. int[] b = a; makes two names for the same array; change one and the other changes. Use Arrays.copyOf for a copy.

Mistakes to watch for

  • System.out.println(primes) prints [I@1b6d3586, the array’s type and address. Use Arrays.toString(primes). An ArrayList prints nicely on its own.
  • ArrayList<int> gives error: unexpected type. Type parameters must be classes: ArrayList<Integer>, ArrayList<Double>.
  • names.get(names.size()) is one past the end: IndexOutOfBoundsException: Index 3 out of bounds for length 3. The last element is at size() - 1.
  • On an ArrayList<Integer>, v.remove(1) removes position 1; to remove the value 1 write v.remove(Integer.valueOf(1)).
  • Removing from a list inside its own enhanced for loop throws java.util.ConcurrentModificationException. Loop with an index backwards, or collect what to remove and call removeAll afterwards.
  • Arrays.sort(names) on an ArrayList: error: no suitable method found for sort(ArrayList<String>). Arrays use Arrays, lists use Collections.

Files and Exceptions

Data · Java 1

Reading and Writing Text Files

LineNumberer.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;

public class LineNumberer
{
    public static void main(String[] args) throws FileNotFoundException
    {
        Scanner in = new Scanner(new File("input.txt"));
        PrintWriter out = new PrintWriter("output.txt");   // creates or overwrites

        int lineNumber = 1;
        while (in.hasNextLine())
        {
            String line = in.nextLine();
            out.println("/* " + lineNumber + " */ " + line);
            lineNumber++;
        }
        in.close();
        out.close();    // without close, the last part may never be written
    }
}

Reading patterns

CallReads
in.nextLine()the rest of the current line
in.next()the next word (whitespace-separated)
in.nextInt(), in.nextDouble()the next number
in.hasNextLine(), in.hasNext(), in.hasNextInt()tests before reading, so the loop stops at the end; reading past the end throws NoSuchElementException

Reading a file safely, step by step

  • 1. Get the name from args[0] or the user; it is relative to the working directory.
  • 2. Open it inside try, catching FileNotFoundException where you can tell the user. The compiler insists: without try or throws you get error: unreported exception FileNotFoundException; must be caught or declared to be thrown.
  • 3. Loop with while (in.hasNextLine()) (or hasNextDouble for numbers) so the loop stops at the end of the file by itself.
  • 4. Convert each line yourself with Integer.parseInt or Double.parseDouble inside a try that catches NumberFormatException, so one bad line is reported and skipped.
  • 5. Close the Scanner, or open it in a try-with-resources header (try (Scanner in = new Scanner(file))) and it closes itself.
double total = 0;
try (Scanner in = new Scanner(new File(filename)))   // closed automatically
{
    while (in.hasNextLine())
    {
        String line = in.nextLine().trim();
        if (line.isEmpty()) { continue; }              // skip blank lines
        try
        {
            total += Double.parseDouble(line);
        }
        catch (NumberFormatException e)
        {
            System.out.println("Skipping bad line: " + line);
        }
    }
    System.out.println("Total: " + total);
}
catch (FileNotFoundException e)
{
    System.out.println("No such file: " + filename);
}

Scanner on a string

// Split one line into words or numbers
Scanner lineScanner = new Scanner(line);
while (lineScanner.hasNextDouble())
{
    double x = lineScanner.nextDouble();
}
// or: String[] parts = line.split(",");

File names are relative to the working directory, which in an IDE is usually the project folder. Command-line arguments arrive in args: java LineNumberer input.txt output.txt gives args[0] and args[1].

Mistakes to watch for

  • java.io.FileNotFoundException: input.txt (No such file or directory) almost always means the working directory is not the folder the file is in. Print new File(".").getAbsolutePath() to see where Java is looking.
  • in.nextInt() followed by in.nextLine() returns "": nextInt leaves the newline behind. Call nextLine() once to throw it away, or read everything with nextLine and parse.
  • Integer.parseInt("3.5") throws NumberFormatException: For input string: "3.5"; so does any stray space. Use Double.parseDouble or trim() first.
  • Forgetting out.close() leaves the output file empty or cut short: the last buffer is only written on close.
  • new PrintWriter("input.txt") erases the file you meant to read. Open output files under a different name.

Exceptions

When something goes wrong at run time, Java throws an exception: an object that describes the problem. If nothing catches it, the program prints a stack trace and stops. You can throw your own and catch the ones you can recover from.

Throwing

public void withdraw(double amount)
{
    if (amount > balance)
    {
        throw new IllegalArgumentException("Amount exceeds balance");
    }
    balance = balance - amount;
}

Catching

try
{
    Scanner in = new Scanner(new File(filename));
    String input = in.next();
    int value = Integer.parseInt(input);
    // ...
}
catch (FileNotFoundException exception)
{
    System.out.println("File not found: " + filename);
}
catch (NumberFormatException exception)
{
    System.out.println("Not a number: " + exception.getMessage());
}
KindExamplesRule
CheckedFileNotFoundException, IOExceptionThe compiler makes you deal with it: catch it, or declare throws on the method
Unchecked (RuntimeException)IllegalArgumentException, NumberFormatException, ArrayIndexOutOfBoundsException, NullPointerExceptionUsually a programming error; you may catch them but need not declare them

Cleaning Up and Custom Exceptions

try-with-resources

// Any resource opened here is closed automatically,
// even when an exception is thrown
try (Scanner in = new Scanner(new File("input.txt"));
     PrintWriter out = new PrintWriter("output.txt"))
{
    while (in.hasNextLine())
    {
        out.println(in.nextLine().toUpperCase());
    }
}

Your own exception class

public class InsufficientFundsException extends RuntimeException
{
    public InsufficientFundsException() {}

    public InsufficientFundsException(String message)
    {
        super(message);
    }
}
// throw new InsufficientFundsException("Balance is " + balance);
  • Throw early: check arguments at the top of a method and throw with a clear message.
  • Catch late: catch where you can actually do something, often in main or the user interface, not in the method that found the problem.
  • Never leave a catch block empty. At least print the message.
  • finally runs whether or not an exception happened; with try-with-resources you rarely need it.

Sets and Dictionaries: HashSet and HashMap

Data · Java 1

Sets

A set holds values with no duplicates and no positions. Adding a value that is already there does nothing. Use a set when the question is only “is it in there?”

import java.util.HashSet;
import java.util.Set;
import java.util.TreeSet;

Set<String> names = new HashSet<>();   // fastest; no particular order
names.add("Romeo");
names.add("Juliet");
names.add("Romeo");                    // ignored: already present
System.out.println(names.size());      // 2
boolean there = names.contains("Juliet");   // true
names.remove("Romeo");

Set<String> sorted = new TreeSet<>(names);  // iterates in sorted order
for (String name : sorted) { System.out.println(name); }
HashSetTreeSet
Order when you iterateUnpredictableSorted (natural order or a Comparator)
Speed of add / contains / removeConstant on averageLogarithmic
Elements mustHave sensible equals and hashCode (Strings, Integers do)Be comparable

Set operations: a.addAll(b) is the union, a.retainAll(b) the intersection, a.removeAll(b) the difference. Each changes a, so copy first if you need the original.

Maps (Dictionaries)

A map stores key → value pairs. Each key appears once and looks up its value directly, like a dictionary looks up a word. In Java the dictionary type is Map, usually a HashMap.

import java.util.HashMap;
import java.util.Map;

Map<String, Integer> scores = new HashMap<>();
scores.put("Harry", 90);              // add or replace
scores.put("Sally", 95);
int s = scores.get("Harry");          // 90
Integer missing = scores.get("Fred"); // null when the key is absent!
int safe = scores.getOrDefault("Fred", 0);   // 0 instead of null
boolean has = scores.containsKey("Sally");
scores.remove("Harry");

for (String key : scores.keySet())            // every key
{
    System.out.println(key + " -> " + scores.get(key));
}
for (Map.Entry<String, Integer> e : scores.entrySet())   // key and value together
{
    System.out.println(e.getKey() + " -> " + e.getValue());
}

Counting with a map

// How many times does each word occur?
Map<String, Integer> counts = new HashMap<>();
while (in.hasNext())
{
    String word = in.next().toLowerCase();
    counts.put(word, counts.getOrDefault(word, 0) + 1);
}

Grouping with a map of lists

Map<String, ArrayList<String>> byLetter = new HashMap<>();
for (String name : names)
{
    String key = name.substring(0, 1);
    if (!byLetter.containsKey(key))
    {
        byLetter.put(key, new ArrayList<>());
    }
    byLetter.get(key).add(name);
}

get on a missing key returns null. Unboxing that into an int throws a NullPointerException. Use getOrDefault or check containsKey first.

Choosing a Collection

You needUse
Values in order, by position, possibly repeatedArrayList
A fixed count of values of one type, fastest possiblean array
Membership only, no duplicatesHashSet (or TreeSet for sorted output)
Look up a value by a keyHashMap (or TreeMap for sorted keys)
First in, first outQueue / LinkedList or ArrayDeque
Last in, first outStack or ArrayDeque

Deciding, in order

  • 1. Will you look values up by a name, id or other key? A Map.
  • 2. Is the only question “have I seen this before?” A Set.
  • 3. Does position matter, or can the same value appear twice? An ArrayList, or an array if the count is fixed from the start.
  • 4. Do you need the output sorted? Switch Hash to Tree; otherwise Hash is faster.

A list works where a set or map belongs, but list.contains(x) checks every element while set.contains(x) is one step. Declare variables with the interface type (List, Set, Map) and create the concrete class on the right: Map<String, Integer> m = new HashMap<>();. Switching implementations is then a one-word change.

Objects and Classes

Objects and Algorithms · Java 1

Classes Describe, Objects Are

A class is a blueprint: it lists the data each object carries (instance variables) and what each object can do (methods). An object is one instance, made with new. String, Scanner and ArrayList are classes you have been using; now you write your own.

BankAccount.java

/**
 * A bank account has a balance that can be changed by deposits and withdrawals.
 */
public class BankAccount
{
    private double balance;               // instance variable: one per object

    /** Constructs a bank account with a zero balance. */
    public BankAccount()
    {
        balance = 0;
    }

    /** Constructs a bank account with a given balance. */
    public BankAccount(double initialBalance)
    {
        balance = initialBalance;
    }

    /** Deposits money. @param amount the amount to deposit */
    public void deposit(double amount)
    {
        balance = balance + amount;
    }

    public void withdraw(double amount)
    {
        balance = balance - amount;
    }

    /** Gets the current balance. @return the balance */
    public double getBalance()
    {
        return balance;
    }
}

Using the class

BankAccount harrysChecking = new BankAccount();      // constructor call
BankAccount momsSavings = new BankAccount(5000);
harrysChecking.deposit(2000);
momsSavings.withdraw(500);
System.out.println(harrysChecking.getBalance());     // 2000.0
System.out.println(momsSavings.getBalance());        // 4500.0

The Pieces of a Class

PieceLooks likeNotes
Instance variableprivate double balance;Always private; each object has its own copy; numbers start at 0, objects at null
Constructorpublic BankAccount(double initialBalance)Same name as the class, no return type; runs once when new is called; several may exist with different parameters
Mutator methodpublic void deposit(double amount)Changes the object; usually void
Accessor methodpublic double getBalance()Reports without changing; returns a value
thisthis.balance = balance;The object the method was called on; needed when a parameter has the same name as an instance variable
toStringpublic String toString()What println(account) prints; override it in every class

Encapsulation

  • Private data plus public methods. Callers use the methods and never see or depend on how the data is stored.
  • You can change the inside later (store cents as a long, add a transaction log) without touching the callers.
  • Methods can check their arguments: deposit can reject a negative amount; a public variable could not.

Object references

BankAccount a = new BankAccount(1000);
BankAccount b = a;        // b refers to the SAME object
b.deposit(500);
System.out.println(a.getBalance());   // 1500.0

BankAccount c = null;     // refers to nothing
c.deposit(1);             // NullPointerException

A variable of class type holds a reference (an address), not the object itself. Two references to one object see every change.

Static Members and Design

Static

public class BankAccount
{
    private static int lastAssignedNumber = 1000;  // shared by all accounts
    private int accountNumber;
    private double balance;

    public BankAccount()
    {
        lastAssignedNumber++;
        accountNumber = lastAssignedNumber;
    }

    public static double round(double x)   // no object needed
    {
        return Math.round(x * 100) / 100.0;
    }
}

Designing a class, step by step

  • 1. Write one sentence saying what an object of the class is and what it is responsible for. If that takes two sentences, you have two classes.
  • 2. Start with the public interface: what should callers be able to do? Write the method headers and comments first.
  • 3. Then pick the instance variables that make those methods possible. Fewer is better. Make every one private.
  • 4. Write the constructor so that every instance variable has a sensible value, then toString, so printing an object during testing shows its data.
  • 5. Every method should leave the object in a valid state. Test the class alone with a small main or a tester class before using it elsewhere.
  • 6. A class should be about one thing. If you cannot say what an object of the class is in a sentence, split it.

Mistakes to watch for

  • Giving the constructor a return type: public void BankAccount(double b) compiles as an ordinary method, so new BankAccount() never runs it and the balance stays 0.0. Constructors have no return type, not even void.
  • balance = balance; in a constructor whose parameter is also called balance assigns the parameter to itself. Write this.balance = balance;.
  • Using an object variable you never created: BankAccount c; c.deposit(1); is error: variable c might not have been initialized, and BankAccount c = null; compiles but throws NullPointerException: Cannot invoke "BankAccount.deposit(double)" because "c" is null.
  • No toString: println(acct) prints BankAccount@1b6d3586. Write one before you debug anything else.
  • Touching an instance variable from a static method: error: non-static variable balance cannot be referenced from a static context. There is no object there; pass one in.

Static methods belong to the class and cannot touch instance variables (there is no object). Static variables are shared by every object; use them for counters and constants, not for data that belongs to one object.

Inheritance and Interfaces

Objects and Algorithms · Java 1

Extending a Class

Inheritance builds a new class from an existing one. The subclass gets every method and variable of the superclass and adds or changes what it needs. Read extends as “is a special kind of”: a SavingsAccount is a BankAccount.

SavingsAccount.java

public class SavingsAccount extends BankAccount
{
    private double interestRate;          // added to what BankAccount has

    public SavingsAccount(double rate)
    {
        super();                          // call the superclass constructor first
        interestRate = rate;
    }

    /** Adds the earned interest to the balance. */
    public void addInterest()
    {
        double interest = getBalance() * interestRate / 100;
        deposit(interest);                // inherited methods, called directly
    }
}

What the subclass can see

ModifierWho can use it
publicEveryone
protectedSubclasses and the same package
(none)The same package
privateThe class itself only. A subclass cannot read its superclass’s private variables; it goes through the inherited methods.

Overriding

public class CheckingAccount extends BankAccount
{
    private int transactionCount;

    @Override
    public void deposit(double amount)
    {
        transactionCount++;
        super.deposit(amount);   // then do what the superclass does
    }
}

@Override makes the compiler check that a method with that exact header exists above. Without it a typo in the name quietly creates a new method instead.

Polymorphism

BankAccount[] accounts = new BankAccount[3];
accounts[0] = new BankAccount(100);
accounts[1] = new SavingsAccount(2.5);      // a SavingsAccount IS a BankAccount
accounts[2] = new CheckingAccount();

for (BankAccount acct : accounts)
{
    acct.deposit(10);   // the version that runs depends on the actual object
}

Rules of thumb

  • A superclass variable may hold a subclass object; the reverse needs a cast.
  • The variable’s type decides which methods you may call; the object’s type decides which version runs (dynamic dispatch).
  • To call a subclass-only method you must cast: ((SavingsAccount) acct).addInterest();, guarded by instanceof. Without the cast: error: cannot find symbol, because BankAccount has no addInterest. With a wrong cast: ClassCastException: class CheckingAccount cannot be cast to class SavingsAccount at run time.

Mistakes to watch for

  • The superclass has a constructor with parameters and the subclass constructor does not call it: error: constructor BankAccount in class BankAccount cannot be applied to given types;. Add super(...) as the first line; anywhere else gives error: call to super must be first statement in constructor.
  • Trying to new an abstract class: error: Shape is abstract; cannot be instantiated. Create a concrete subclass instead.
  • Overriding with a typo (tostring, Deposit) silently adds a new method and the old one still runs. Put @Override above every override so the compiler checks the name.

instanceof and casting

if (acct instanceof SavingsAccount)
{
    SavingsAccount s = (SavingsAccount) acct;
    s.addInterest();
}
// Java 16+: pattern matching
if (acct instanceof SavingsAccount s) { s.addInterest(); }

Abstract Classes, Interfaces and Object

Abstract class

public abstract class Shape
{
    private String name;
    public Shape(String name) { this.name = name; }
    public String getName() { return name; }
    public abstract double area();   // no body: subclasses must supply it
}

public class Circle extends Shape
{
    private double r;
    public Circle(double r) { super("circle"); this.r = r; }
    public double area() { return Math.PI * r * r; }
}

Interface

public interface Measurable
{
    double getMeasure();   // implicitly public and abstract
}

public class BankAccount implements Measurable
{
    public double getMeasure() { return getBalance(); }
}
// A class extends ONE class but may implement MANY interfaces.
// Measurable m = new BankAccount(50); works.
Method every class inherits from ObjectOverride it whenShape
toString()Always; it is what println printspublic String toString() { return "BankAccount[balance=" + balance + "]"; }
equals(Object other)Two objects with the same contents should count as equalCheck other instanceof your class, cast, compare fields
hashCode()Whenever you override equals, so hash sets and maps workreturn Objects.hash(field1, field2);

Recursion

Objects and Algorithms · Java 1

A Method That Calls Itself

A recursive method solves a problem by solving a smaller version of the same problem, then doing one more step. Every recursion needs two things: a base case that is answered directly, and a recursive case that moves toward the base case.

Factorial

public static long factorial(int n)
{
    if (n <= 1)                   // base case
    {
        return 1;
    }
    return n * factorial(n - 1);  // recursive case: smaller n
}
// factorial(4) = 4 * factorial(3) = 4 * 3 * factorial(2) = 4 * 3 * 2 * 1 = 24

Sum of digits

public static int digitSum(int n)
{
    if (n < 10) { return n; }
    return digitSum(n / 10) + n % 10;
}
// digitSum(1729) = digitSum(172) + 9 = (digitSum(17) + 2) + 9 = ((1 + 7) + 2) + 9 = 19

Palindrome

public static boolean isPalindrome(String s)
{
    if (s.length() <= 1) { return true; }
    char first = s.charAt(0);
    char last = s.charAt(s.length() - 1);
    if (first != last) { return false; }
    return isPalindrome(s.substring(1, s.length() - 1));
}

Thinking recursively

  • Trust the recursive call. Assume isPalindrome works for shorter strings; your job is only the first and last letter.
  • Make sure each call is strictly smaller and that the smallest case is handled before any recursive call.
  • Trace tiny inputs by hand: the empty string, one character, two characters.

Writing a recursive method, step by step

  • 1. State the contract in one line: “digitSum(n) returns the sum of the digits of n”. Everything below relies on it.
  • 2. Find the smallest input(s) and return the answer directly. For digitSum that is a single digit; for strings and arrays it is usually length 0 or 1.
  • 3. For any bigger input, peel off one piece (n % 10, s.charAt(0), a[n - 1]) and assume the method already works on what is left.
  • 4. Combine the piece with that result, and return it.
  • 5. Check that every recursive call is strictly smaller and cannot skip past the base case (negative numbers, odd lengths).
  • 6. Test the base case first, then one step above it, then something larger.

Mistakes to watch for

  • No base case, or one the input never reaches (factorial(-1) with if (n == 0)): Exception in thread "main" java.lang.StackOverflowError, after a few thousand calls.
  • Forgetting return before the recursive call: with a non-void method the compiler says error: missing return statement, which is why Java catches this one for you.
  • Overflow: factorial(13) as an int prints 1932053504, not 6227020800. Use long, which lasts until factorial(20).
  • Calling with the same argument (digitSum(n) instead of digitSum(n / 10)). The input must shrink on every call.

When Recursion Is Slow

// Fibonacci the obvious way: correct, but fib(40) makes over 300 million calls
public static long fib(int n)
{
    if (n <= 2) { return 1; }
    return fib(n - 1) + fib(n - 2);
}

// The same numbers with a loop: n steps
public static long fibLoop(int n)
{
    if (n <= 2) { return 1; }
    long older = 1, old = 1, result = 1;
    for (int i = 3; i <= n; i++)
    {
        result = old + older;
        older = old;
        old = result;
    }
    return result;
}
  • When the recursive case calls itself twice on overlapping problems, the work doubles at every level. Use a loop, or remember results you have already computed (memoization).
  • Each call uses a stack frame. Recursing a hundred thousand levels deep throws StackOverflowError; a loop would not.
  • Recursion shines when the problem is naturally nested: permutations, subsets, folders inside folders, trees, and “try every choice” searches.

Permutations and Mutual Recursion

All permutations of a string

public static ArrayList<String> permutations(String word)
{
    ArrayList<String> result = new ArrayList<>();
    if (word.length() == 0)
    {
        result.add(word);        // one permutation of the empty string
        return result;
    }
    for (int i = 0; i < word.length(); i++)
    {
        String shorter = word.substring(0, i) + word.substring(i + 1);
        for (String p : permutations(shorter))
        {
            result.add(word.charAt(i) + p);
        }
    }
    return result;
}

Towers of Hanoi

// Move n disks from peg "from" to peg "to", using "via" as the spare
public static void hanoi(int n, String from, String to, String via)
{
    if (n == 0) { return; }
    hanoi(n - 1, from, via, to);
    System.out.println("Move disk " + n + " from " + from + " to " + to);
    hanoi(n - 1, via, to, from);
}
// hanoi(3, "A", "C", "B") prints 7 moves; n disks take 2^n - 1

Mutual recursion is two methods that call each other, such as an expression evaluator where expression calls term, which calls factor, which calls expression again for a parenthesized part. The base case is still a method that returns without calling the other.

Sorting and Searching

Objects and Algorithms · Java 1

Selection Sort and Insertion Sort

Selection sort

public static void selectionSort(int[] a)
{
    for (int i = 0; i < a.length - 1; i++)
    {
        int minPos = i;                      // find the smallest in a[i..]
        for (int j = i + 1; j < a.length; j++)
        {
            if (a[j] < a[minPos]) { minPos = j; }
        }
        int temp = a[minPos];                // swap it into position i
        a[minPos] = a[i];
        a[i] = temp;
    }
}

Insertion sort

public static void insertionSort(int[] a)
{
    for (int i = 1; i < a.length; i++)
    {
        int next = a[i];                     // a[0..i-1] is already sorted
        int j = i;
        while (j > 0 && a[j - 1] > next)     // slide bigger ones right
        {
            a[j] = a[j - 1];
            j--;
        }
        a[j] = next;                         // drop next into the gap
    }
}

Watch them work

Add System.out.println("pass " + (i + 1) + ": " + Arrays.toString(a)); as the last line of the outer loop of selection sort (and "pass " + i in insertion sort) and run each on {11, 9, 17, 5, 12}:

selection sort           insertion sort
pass 1: [5, 9, 17, 11, 12]   pass 1: [9, 11, 17, 5, 12]
pass 2: [5, 9, 17, 11, 12]   pass 2: [9, 11, 17, 5, 12]
pass 3: [5, 9, 11, 17, 12]   pass 3: [5, 9, 11, 17, 12]
pass 4: [5, 9, 11, 12, 17]   pass 4: [5, 9, 11, 12, 17]

Selection sort grows the sorted part from the left by picking the smallest remaining value each pass; insertion sort grows it by sliding the next value into place. Both make about n²/2 comparisons: doubling the array quadruples the time. Insertion sort is fast on data that is already nearly sorted; selection sort always does the same work.

Mistakes to watch for

  • Inner loop with j <= a.length: ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 5 on the first pass.
  • Swapping without the temporary: a[i] = a[minPos]; a[minPos] = a[i]; copies one value into both slots. Three assignments, always.
  • Sorting strings with <: error: bad operand types for binary operator '<'. Use a[j].compareTo(a[minPos]) < 0.
  • Expecting Arrays.sort(a) to return the sorted array: it sorts in place and returns nothing, so int[] b = Arrays.sort(a); gives error: incompatible types: void cannot be converted to int[].

Merge Sort

public static void mergeSort(int[] a)
{
    if (a.length <= 1) { return; }
    int[] first = Arrays.copyOfRange(a, 0, a.length / 2);
    int[] second = Arrays.copyOfRange(a, a.length / 2, a.length);
    mergeSort(first);                 // sort each half
    mergeSort(second);
    merge(first, second, a);          // then merge them into a
}

private static void merge(int[] first, int[] second, int[] a)
{
    int i = 0, j = 0, k = 0;
    while (i < first.length && j < second.length)
    {
        if (first[i] < second[j]) { a[k] = first[i]; i++; }
        else { a[k] = second[j]; j++; }
        k++;
    }
    while (i < first.length) { a[k] = first[i]; i++; k++; }
    while (j < second.length) { a[k] = second[j]; j++; k++; }
}
AlgorithmComparisons for n itemsBig-ODoubling n makes it
Selection sortabout n²/2O(n²)4 times slower
Insertion sortn²/4 average; n if already sortedO(n²)4 times slower
Merge sortabout n log2 nO(n log n)a little more than 2 times slower
Linear searchn/2 average, n worstO(n)2 times slower
Binary search (sorted data)about log2 nO(log n)one more step

Big-O keeps only the fastest-growing term and drops constants: 3n² + 20n + 7 is O(n²). It describes how the work scales, not how many seconds it takes.

Searching

Linear search

// Works on any array; checks each element
public static int linearSearch(int[] a, int value)
{
    for (int i = 0; i < a.length; i++)
    {
        if (a[i] == value) { return i; }
    }
    return -1;
}

Binary search (the array must be sorted)

public static int binarySearch(int[] a, int value)
{
    int low = 0;
    int high = a.length - 1;
    while (low <= high)
    {
        int mid = (low + high) / 2;
        if (a[mid] == value) { return mid; }
        else if (a[mid] < value) { low = mid + 1; }
        else { high = mid - 1; }
    }
    return -1;
}
// 1,000,000 sorted items: at most 20 steps

The library does it faster: use these in real programs

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

Arrays.sort(values);                                  // arrays of numbers or Strings
int pos = Arrays.binarySearch(values, 42);            // negative if absent
Collections.sort(names);                              // ArrayList<String>
names.sort(Comparator.comparing(String::length));     // by another rule
accounts.sort(Comparator.comparingDouble(BankAccount::getBalance).reversed());

Sorting your own objects

public class Country implements Comparable<Country>
{
    private String name;
    private double area;

    public int compareTo(Country other)
    {
        return Double.compare(area, other.area);   // negative, zero or positive
    }
}
// Then Collections.sort(countries) or Arrays.sort(countryArray) just works.

Comparable vs Comparator

  • Comparable: the class itself defines its one natural order in compareTo.
  • Comparator: a separate object defines an order, so you can sort the same objects by name today and by area tomorrow.
  • Double.compare and Integer.compare avoid the overflow and rounding bugs of subtracting.