Dayrvia
Jv

Java

Trace objects and references, overloading and overriding, collections, generics and exception handling.

Take the full quiz

Objects and variablesPrimitives and references

Primitives and references

An int variable holds an integer. An array variable holds a reference to an array object. Assigning this variable to another copies the reference.

Code example

int[] a = {2, 4};
int[] b = a;
b[0] = 9;

Walkthrough

Both b[0] and a[0] address the same array element. Writing 9 through b changes a[0] too.

Objects and variablesStrings

Comparing strings

For reference types, == checks whether both references point to the same object. String.equals compares the character sequence. Strings are immutable. Keep the returned value when using operations such as concat that produce another string.

Code example

String a = new String("day");
String b = new String("day");

Walkthrough

Two new expressions create separate objects. a == b is false while a.equals(b) is true.

ClassesOverriding

Choosing an overridden method

When a subclass overrides an instance method, the runtime type of the object determines which implementation is called.

Code example

class Note { String text() { return "note"; } }
class Memo extends Note {
    @Override String text() { return "memo"; }
}
// inside a method
Note n = new Memo();

Walkthrough

The variable has type Note but holds a Memo. Calling n.text() returns "memo".

Objects and variablesArgument passing

What is copied into a method?

Java passes arguments by value. Passing an array copies its reference, so both variables initially refer to the same array. Distinguish modifying an element from reassigning the parameter.

Code example

static void edit(int[] xs) {
    xs[0] = 8;
    xs = new int[]{99};
}
// inside main
int[] data = {2};
edit(data);

Walkthrough

xs[0] = 8 updates the shared array. The following assignment points only local xs to a new array. The caller still reads 8 from data[0].

ClassesOverloading

Overloads use the declared argument type

Overloading gives methods the same name and different parameter lists. The compiler chooses a signature using the types at the call site. For overridable instance methods, runtime dispatch can then select an implementation of that signature.

Code example

class Labels {
    static String tag(Object x) { return "object"; }
    static String tag(String x) { return "string"; }
}
// inside main
Object x = "day";
String result = Labels.tag(x);

Walkthrough

x refers to a string, but its declared type is Object. The compiler chooses tag(Object), so result is "object".

ClassesInterfaces

Swapping implementations with an interface

An interface defines operations available to a caller. A variable typed as an interface can hold different implementing objects, keeping the call independent of a particular implementation.

Code example

interface Fee { int apply(int price); }
class Half implements Fee {
    public int apply(int price) { return price / 2; }
}
// inside main
Fee fee = new Half();
int total = fee.apply(80);

Walkthrough

The caller uses Fee.apply. The object is a Half, so total becomes 40. Another implementation could supply a different pricing rule.

CollectionsList, Set and Map

Choosing List, Set or Map

Use a List for ordered entries and duplicates, a Set for unique values, and a Map to retrieve a value by key. For hash-based collections, objects that compare equal must return the same hash code.

Code example

List<String> log = new ArrayList<>();
Set<String> seen = new HashSet<>();
for (String s : List.of("A", "B", "A")) {
    log.add(s);
    seen.add(s);
}

Walkthrough

log.size() is 3 and seen.size() is 2. HashSet does not guarantee insertion order. These collection types are in java.util.

CollectionsGenerics and unboxing

Generics and unboxing

List<Integer> restricts elements to Integer. Assigning a retrieved Integer to int unboxes it. A List<? extends Number> view lets you read a Number without knowing the exact element type.

Code example

List<Integer> values = new ArrayList<>();
values.add(3);
int n = values.get(0);
List<? extends Number> numbers = values;
Number first = numbers.get(0);

Walkthrough

n is 3. Code using numbers may read a Number but cannot add an arbitrary numeric value because its specific element type is unknown.

ExceptionsException handling

Following an exception

A thrown exception skips the rest of the try block and transfers control to a matching catch. Here the finally block runs both after normal completion and after the catch.

Code example

StringBuilder trace = new StringBuilder();
try {
    trace.append("A");
    Integer.parseInt("x");
    trace.append("B");
} catch (NumberFormatException e) {
    trace.append("C");
} finally {
    trace.append("D");
}

Walkthrough

Parsing "x" throws before B is appended. The resulting string is "ACD".

Further reading