THINK FIRST·CODE LATER

← Java Programming
Appendix B

Java Syntax and API Quick Reference

A compact reference for use while working through the question banks. Nothing here replaces the chapter reviews; it is a place to check a signature or a rule quickly.

B1. Program skeleton

import java.util.Scanner;                  // imports come first

public class ClassName {                   // file must be ClassName.java
    public static final double RATE = 0.19;   // class constant
    private int field;                        // instance variable

    public ClassName(int field) { this.field = field; }        // constructor

    public int getField() { return field; }                    // accessor
    public void setField(int field) { this.field = field; }    // mutator

    public static void main(String[] args) {                   // entry point
        ClassName obj = new ClassName(5);
        System.out.println(obj.getField());
    }
}

B2. Primitive types

Type Size Default Notes
byte 8 0 −128 … 127
short 16 0 −32768 … 32767
int 32 0 default type of an integer literal
long 64 0L literal suffix L
float 32 0.0f literal suffix f
double 64 0.0 default type of a decimal literal
char 16 '\u0000' single quotes
boolean false true or false only

Widening (automatic): byteshortintlongfloatdouble; charint. Narrowing needs a cast: int n = (int) 9.99; gives 9.

B3. Operator precedence (high to low)

  1. ()
  2. ++ -- (unary), unary + -, !, (type)
  3. * / %
  4. + - (and + as string concatenation)
  5. < <= > >=, instanceof
  6. == !=
  7. &&
  8. ||
  9. ?:
  10. = += -= *= /= %=

Binary operators associate left to right; assignment associates right to left.

B4. Control structures

if (c) { } else if (c2) { } else { }

switch (x) {                     // byte, short, char, int, String, enum
    case 1: ...; break;
    default: ...;
}

while (c) { }
do { } while (c);                // note the semicolon
for (int i = 0; i < n; i++) { }
for (Type v : collectionOrArray) { }

break;      // leave the innermost loop or switch
continue;   // skip to the next iteration
return v;   // leave the method

B5. Arrays

int[] a = new int[5];             int[] b = {1, 2, 3};
a.length                          // FIELD, no parentheses
a[i]                              // 0 <= i <= a.length - 1
int[][] m = new int[3][4];        m.length      // rows
                                  m[0].length   // columns of row 0
System.arraycopy(src, srcPos, dest, destPos, count);
Arrays.toString(a)  Arrays.deepToString(m)  Arrays.sort(a)
Arrays.fill(a, v)   Arrays.copyOf(a, len)   Arrays.equals(a, b)

B6. String

length() number of characters (a method)
charAt(i) character at i, 0 ≤ i < length()
substring(a), substring(a,b) from a; from a inclusive to b exclusive
indexOf(s), lastIndexOf(s) position, or −1
equals, equalsIgnoreCase content comparison (never ==)
compareTo negative, zero or positive (dictionary order)
toUpperCase, toLowerCase, trim return NEW strings
replace(c1,c2), concat(s), contains(s)
split(regex) array of pieces, e.g. split(",")
isEmpty() length is 0

String objects are immutable. For repeated modification use StringBuilder: append, insert(i,s), delete(a,b), reverse, length, toString.

B7. Math, wrappers and Character

Math.abs  Math.pow  Math.sqrt  Math.max  Math.min
Math.round(d) -> long     Math.ceil / Math.floor -> double
Math.random() -> [0.0, 1.0)      Math.PI   Math.E
(int)(Math.random() * (hi - lo + 1)) + lo        // random int, lo..hi inclusive

Integer.parseInt(s)   Double.parseDouble(s)   String.valueOf(x)
Integer.MAX_VALUE     Integer.MIN_VALUE
Character.isDigit / isLetter / isUpperCase / isWhitespace
Character.toUpperCase / toLowerCase

B8. Console input and formatted output

Scanner in = new Scanner(System.in);
in.nextInt()  in.nextDouble()  in.next()  in.nextLine()
in.hasNextInt()  in.hasNextLine()         // validation / end of data
// after nextInt(), call in.nextLine() once before the next nextLine()

System.out.printf("%-10s %5d %8.2f%n", name, qty, price);
// %d integer   %f decimal   %s string   %c char   %b boolean
// %n newline   %%  literal percent
// %8.2f = width 8, two decimals;  %-10s = width 10, left aligned

B9. ArrayList

import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add(v)        list.add(i, v)     list.get(i)      list.set(i, v)
list.remove(i)     // BY INDEX        list.remove(obj) // BY VALUE
list.size()        list.contains(v)   list.indexOf(v)  list.isEmpty()  list.clear()
for (String s : list) { ... }

Elements are objects: ArrayList<Integer>, not ArrayList<int>.

B10. Classes, inheritance and interfaces

public class Sub extends Super implements Iface1, Iface2 {
    public Sub(int x) {
        super(x);            // FIRST statement; this(...) is the alternative
    }
    @Override public void method() { super.method(); }
}

public abstract class Shape {           // cannot be instantiated
    public abstract double area();      // no body; subclasses must implement
}

public interface Drawable {
    int MAX = 10;                       // public static final
    void draw();                        // public abstract
    default void hint() { }             // Java 8+
}
private declaring class only
(default) same package
protected same package and subclasses
public everywhere
static belongs to the class, one copy, no this
final variable: assign once; method: no overriding; class: no extending

Overloading: same name, different parameter list, resolved at compile time. Overriding: same name and same parameter list in a subclass, resolved at run time.

B11. Exceptions

try { ... }
catch (SpecificException e) { e.getMessage(); }   // most specific FIRST
catch (TypeA | TypeB e)     { ... }               // unrelated types only
finally { ... }                                   // always runs

throw new IllegalArgumentException("message");    // raise now
public void load() throws IOException { }         // declare for callers

class MyChecked   extends Exception        { public MyChecked(String m)   { super(m); } }
class MyUnchecked extends RuntimeException { public MyUnchecked(String m) { super(m); } }

Unchecked (no declaration required): everything under RuntimeExceptionNullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException, NumberFormatException, InputMismatchException, ClassCastException, IllegalArgumentException. Checked (handle or declare): IOException, FileNotFoundException, and your own subclasses of Exception that do not extend RuntimeException.

B12. Text files

try (Scanner in = new Scanner(new File("in.txt"));
     PrintWriter out = new PrintWriter("out.txt")) {          // overwrites
    while (in.hasNextLine()) out.println(in.nextLine());
} catch (IOException e) { ... }

new PrintWriter(new FileWriter("log.txt", true));             // appends
new File(name).exists()   .length()   .getName()   .delete()

B13. Checklist before you submit any program

  1. Does it compile from a clean build, with the public class in a file of the same name?
  2. Are all fields private, with accessors and mutators where needed?
  3. Does every non-void method return on every path?
  4. Are loop bounds right at the edges (0, 1, length - 1)?
  5. Are Strings compared with equals?
  6. Is division by zero (including an empty list or array) impossible?
  7. Are files closed, and checked exceptions handled or declared?
  8. Are names meaningful, indentation consistent, and each method doing one job?
  9. Have you tested with ordinary, boundary and invalid input?