Handout written by Nick Parlante
This doc gathers miscellaneous intermediate Java topics needed in CS108. Many of these are topics are not
given full coverage in an introductory Java course such as CS106A.
: read through this
handout once to have familiarity with these topics, as they will all appear somewhere in the CS108 code.
We will review a few of the topics here plus Java Generics in the section Thu eve.
The first part deals with many little topics: arrays, shallowness, packages, command line java, static
variables and methods, file reading, exceptions. The second part concentrates on the Java Collection
classes: List, Map, and Set. The 2nd part has different typography, as I'm preparing it in HTML to be
published on the web.
Pervasive Shallowness in Java / GC
In C++, when you use an "=" for assignment, you always wonder how "deep" the copy is. In Java, = is
always "shallow" -- copying the pointer but not the object. Suppose we have some Foo class:
Foo x = new Foo(1);
Foo y = new Foo(2);
x = y;
// shallow -- just make x point to 2nd Foo, Garbage Collector gets the 1st Foo
// same, just pass a pointer to the Foo object into bar()
The garbage collector (GC) does the deallocation bookkeeping for us, deallocating a heap object when
the number of pointers to it goes to zero. "new" allocates, the GC cleans up.
It is common in Java to have a few objects and proliferate pointers to those few objects all over the place.
Many parts of the program share ownership of the objects. We can afford to have pointers spread all
over, since the GC manages the deallocation bookkeeping.
This pervasive sharing can be a problem if we want to change an object, since many parts of the program
may be pointing to it.
Sharing is not a problem if the object is "immutable" -- having no mutating methods so the object never
changes once it is constructed.
Another solution is to make a copy of the object before changing it. Some classes provides a "copy
constructor" (C++ terminology) -- a constructor that takes a pointer to an existing object as an
argument, and initializes a new object to be a copy. In general, making copies of things is something
more often done in C++ than in Java. I think this is because the GC gives us the freedom to not make
copies in many situations.
Foo x = new Foo(1);
Foo copy = new Foo(x);
// make a copy of x (depends on existence of a copy constructor)
There is also an old java object copying facility called "Cloneable", but it turned out to be a messy design
and has fallen out of favor. I recommend that you never use it.
As a warmup, remember how arrays work in Java:
int a = new
// Allocate array in the heap, a points to the
a = 13;
a = 26;
// read-only access .length -- 100 (not .length(), that's for strings)
a = 13;
// throws ArrayOutOfBounds exception at runtime