Values, references, loops and making objects.
Key points, notes and past questions
Core Java and the Runtime Memory Model
References, the call stack and what == compares.
- Loops, step by step
whileandfortest first.do-whileruns once before its first test.- A counter declared outside an inner loop is not reset.
- Arrays and references
- A parameter is a copy of the caller's value.
- For arrays that value is a reference.
- Writes through a reference are shared; reassignment is local.
clone()of a 2-D array shares the rows.
- Activation records
- One record per unfinished call.
- It holds parameters, locals and the links back.
- Last called, first finished.
- Recursion only means many records for the same method.
- Same object or same value
==on references asks "one object?".- Equal literals are one object;
newand run-time joining make others. - Boxes from -128 to 127 are shared.
Integer == intcompares numbers.
Notes3 past questions in this topic
Cloning and Copy Constructors
Shallow and deep copies, seen as arrows between objects.
- A second name or a second object
b = amakes no object.super.clone()makes one new object and copies each field's value or arrow.- No constructor runs during
super.clone(). - A clone holds the values that existed at the moment of the call.
- What a shallow clone shares
super.clone()copies references, never the objects behind them.- Writing into a shared object is seen from both sides.
- Assigning a field changes one object only.
array.clone()andnew ArrayList<>(list)are shallow.
- Cutting the shared arrows: deep cloning
- Deep clone =
super.clone()plus a new object for each mutable field. - A skipped field stays shared.
- Copying a list or a 2-D array does not copy its elements or rows.
- A
finalreference field cannot be replaced aftersuper.clone(). - Guard
nullfields before callingclone()on them.
- Deep clone =
- Who may be cloned: the contract and inheritance
Cloneablehas no methods; it is tested while the program runs.Object.cloneisprotectedand declares a checked exception.- The clone has the runtime class of the original.
- A subclass inherits
Cloneableand the parent'sclone. - A child's new mutable field is shared unless the child's code copies it.
- Copy constructors
- Java writes no copy constructor for you.
- Each assignment decides: value, shared arrow or new object.
new Parent(child)builds aParent.- A constructor may fill
finalfields;clone()cannot reassign them.
Notes9 past questions in this topic
Week 1: Java basics, memory, OOP ideasWeek 3: Inheritance, polymorphism, class hierarchy, modifiersAll Java topics and weeks