Java Toolkit (Cheatsheet)

Context: FIT2099_MOC · the one-note Java coding surface — code a class from a blank editor after re-reading this. Depth lives in the linked notes.

Quick Revision

  • 🎯 Objective: write correct, well-encapsulated OO Java ➔ class anatomy + modifiers + collections + inheritance/interfaces + contracts, with the exam gotchas inline.
  • ⚡ Key Constraint: Java is statically typed (types fixed at declaration, checked at compile time) and objects are reference types — most FIT2099 bugs come from reference aliasing, == vs .equals(), and access-widening on override.

🧩 Class Anatomy (execution order)

package game.actors;                    // 1. package — namespace, MUST be first line
import java.util.ArrayList;             // 2. imports — bring in other packages
import java.util.List;
 
public class Hero extends Actor implements Speaker {   // 3. class header: one extends, many implements
    public static final int MAX_HP = 100;   // 4. static final constant (class-level, assign-once)
    private int hp;                          // 5. private field — encapsulated state
    private final Armour armour;             // 6. blank final — assigned exactly once (in ctor)
 
    public Hero(Armour armour) {             // 7. constructor — runs on `new`; same name, no return type
        this.armour = armour;                //    `this` disambiguates field from param
        this.hp = MAX_HP;
    }
    public int getHp() { return hp; }        // 8. query (accessor) — no side effect
    public void takeDamage(int d) { hp -= d; }// 9. command (mutator) — changes state, returns void
    @Override public String speak() { return "For honour!"; }  // 10. override (interface/parent method)
}

(Order on the page: package → imports → class → static fields → instance fields → constructors → methods. Compile-time type checking catches type errors before it runs — see Java Static Typing, Java Program Structure.)

🔑 Modifiers & keywords

ToolMicro-syntaxJob / gotcha
public/private/protected/defaultprivate int x;visibility; override can’t narrow access (widening only). Encapsulation and Access Modifiers (Java)
staticstatic int count;one shared class-level copy; access via ClassName.x; static can’t see instance members. Static and Final (Java)
final (field)final int N = 5;assign-once constant; on a reference the object stays mutable (non-transitive).
final (class/method)final class Xblocks inheritance / overriding.
thisthis.x = x;current object; disambiguates field vs parameter. Java Constructors
supersuper(args); super.m();parent constructor / parent method; ctor call must be first line. Inheritance (Java)
@Overrideabove methodcompiler-checks you really override; catches typos.
abstractabstract class, abstract void m();no-body method; class can’t be instantiated. Abstract Classes (Java)
extends / implementsclass C extends B implements I,Jone superclass, many interfaces. Interfaces (Java)
enumenum Suit { HEART, SPADE }type-safe named constants; fixes magic numbers/strings. Enumerations (Java)

🔢 Types, casting, equality

ToolMicro-syntaxJob / gotcha
Primitivesint long double boolean charvalue types, stored directly. Java Data Types, Casting and References
WrappersInteger Double Booleanobject versions; needed for generics; watch autoboxing/null.
Widening castdouble d = anInt;implicit, safe.
Narrowing castint i = (int) aDouble;explicit, may lose data.
==a == breference identity for objects (same object?); value for primitives.
.equals()a.equals(b)value equality; override for your classes. Use for String! (String Pool makes == sometimes work — trap.)
String"text"immutable reference type.

🔁 Control flow & arrays

if (x > 0) {...} else if (...) {...} else {...}
String s = (x > 0) ? "pos" : "neg";          // ternary
switch (day) { case MON: ...; break; default: ...; }   // break to avoid fall-through
for (int i = 0; i < a.length; i++) {...}     // index loop
for (int v : a) {...}                        // for-each (read)
while (cond) {...}   do {...} while (cond);
int[] a = new int[5];  int[] b = {1,2,3};    // .length, 0-based

(Details: Java Control Flow (Conditionals and Loops), Java Arrays.)

📦 Collections + generics

ToolMicro-syntaxJob / gotcha
ListList<T> l = new ArrayList<>();ordered, duplicates OK, index access.
SetSet<T> s = new HashSet<>();no duplicates, no order (needs equals/hashCode).
MapMap<K,V> m = new HashMap<>();key→value, unique keys.
Opsadd / get(i) / contains / size / remove / put / keySetget is get(key) on Map, get(index) on List.
Iteratefor (T x : list) · for (var e : map.entrySet())
Program to interfacedeclare List, instantiate ArrayListswap implementation freely. Java Collections (List, Set, Map)

🧱 Inheritance · polymorphism · abstraction

ToolMicro-syntaxJob / gotcha
Inheritanceclass Dog extends Animalis-a; reuse + override. Inheritance (Java)
Override@Override String speak()runtime dispatch picks the subclass version.
UpcastAnimal a = new Dog();polymorphic variable; base type hides subclass-only methods. Polymorphism (Java)
Dynamic dispatcha.speak() → Dog’sdecided at runtime by actual object.
Downcast((Dog) a).fetch()needs instanceof check; instanceof in logic = smell. SOLID Principles (Java)
Abstract classabstract class Shape { abstract double area(); }shared code + contract; not instantiable. Abstract Classes (Java)
Interfaceinterface Drawable { void draw(); default void hi(){} }pure capability; multiple; default methods. Interfaces (Java)

🛡️ Contracts, errors & robustness

ToolMicro-syntaxJob / gotcha
throwthrow new IllegalArgumentException("msg");fail fast on bad client input (precondition breach). Exceptions, Assertions and Validation (Java)
try/catchtry {...} catch (SpecificException e) {...}catch the specific type; keep follow-up (e.g. i++) inside try.
custom exceptionclass FooException extends Exception {...}carry business message/data.
assertassert cond : "msg";dev-time bug check; disabled in prod — never validate user input with it.
Design by Contractpre/post/invariantclient meets pre, supplier guarantees post; invariant holds between calls. Design by Contract (Java)
Command-Query Separationcommand=void, query=returns, no side effectnever both; keeps contract checks safe. Command-Query Separation (Java)
Scanner trapInteger.parseInt(sc.nextLine())nextInt() leaves \n; mixing with nextLine() “skips”.

🧩 Design constructs (apply the principles)

ToolMicro-syntax / ideaJob / gotcha
Encapsulationprivate field + accessorhide state; expose behaviour. Encapsulation and Access Modifiers (Java)
Compositionclass holds another as a fieldhas-a; prefer over inheritance for reuse. Client-Supplier Relationship (Java)
Dependency Injectionpass collaborators via constructorclient depends on an interface, not a new. Dependency Injection (Java)
Defensive copyingcopy mutable in ctor & getterstops privacy leaks via aliasing. Defensive Copying (Java)
Factory Methodstatic Card create(int age) returns base typecentralise creation; kills instanceof ladders. Factory Method Pattern (Java)
SOLIDSRP·OCP·LSP·ISP·DIPthe design vocabulary. SOLID Principles (Java) · Design Rationale (FIT2099)

🔧 Smell ➔ Java refactoring (quick-map)

SmellJava fix
Type checking (switch(type))Replace Conditional with Polymorphism (subclass + override)
Data clumps / primitive obsessionExtract Class (group fields into an object)
Feature envyMove Method to the class owning the data
Shotgun surgeryconsolidate rule into one private query / Move Method
Long method / God classExtract Method / Extract Class (SRP)
(Full catalogue: Design Smells (Java); discipline: Refactoring (Java).)

✍️ Integration Practice

⚠️ Common Mistakes (top of the deduction list)

  • 💡 == on objects/Strings ➔ compares references; use .equals() for value equality.
  • 💡 Access-widening on override ➔ an override may only keep or widen visibility, never narrow.
  • 💡 instanceof/switch(type) in logic ➔ a smell — replace with polymorphism.
  • 💡 Returning a mutable field directly ➔ privacy leak; return a copy.
  • 💡 assert for user input ➔ disabled in prod; use exceptions for client-facing validation.