05: Namespaces, Packages and the CLASSPATH; Intro to Lists

Welcome

Announcements

Remember, there’s lots of places to get help: Piazza, office hours, and ExSEL. But we can’t help you if you don’t ask for help. If you’re having trouble come see us, please!

Grades are showing up in Moodle: Make sure that what you see in Gradescope and Moodle is what you expect to see! In particular, if you were a late add, make sure that the excused items are marked as “Excluded.”

If you’re a late add, you must add yourself to Piazza and Gradescope, and ask us to be excused from whatever you missed. SPIRE does not notify me about late adds. If you used SPIRE to add yourself and not done anything else, you’re gonna start seeing zeros for grades soon.

Namespaces

Many programming languages, including Java incorporate the idea of a “namespace”. A namespace is a way to provide context to a particular name.

For a real-world analogy, you might think of a person’s name, say, “Nicholas”. There might be more than one in this class, so we add some context (a surname, or a student ID, or an address, or all of the above) to disambiguate which we mean.

This is very similar to the idea of a variable’s scope in Java, but slightly different, as it’s how we precisely name and identify classes.

For example, we all write System.out.println() all the time, and we all know that System is probably a class, since it starts with a capital letter. Where does it come from, though?

Packages

It’s part of the java.lang package. Java organizes classes into packages; which are a hierarchical sequence of tokens (words), separated by dots. The built-in parts of the Java standard library all are part of the “java.” package, though it’s further subdivided.

For example, the aforementioned java.lang package defines the classes that are fundamental to the design of the language itself: things like System and String are defined here.

http://docs.oracle.com/javase/8/docs/api/java/lang/package-summary.html#package.description

By default, things in this namespace are automatically “imported” into the local namespace. That is, you don’t have to type java.lang.String to declare a String (though you can); String suffices.

Interestingly, it’s not against the rules to define your own System class. But it’s like if you have both an instance variable named x and a local variable named x. By default, Java assumes you want to “more local” one.

int x = 5;

void test() {
  x = 3;
  System.out.println(x);
  System.out.println(this.x);
}

To get the “outer” one, you need to prefix it with this., which tells Java you want the current instance variable with the same name.

In-class Exercise

private String x = new String("Jane");

public void printStrings() {
  String x = new String("Ren");

  System.out.println(x);
  System.out.println(this.x);
}

What are the lines output by printStrings()?

Another exercise:

private String x = new String("Jane");

public void printEquals() {
  String x = new String("Jane");

  System.out.println(x == this.x);
  System.out.println(x.equals(this.x));
}

What are the lines output by printEquals()?

Similarly, with a class, you need to fully specify the class if you want access to it. Inside your custom System class, if you want to access the “normal” System.out.println, you’ll need to refer to it by its full name, java.lang.System.out.println.

java and javax are reserved by the JVM for built-in and extensions classes, but much like anyone can register a domain name on the Internet, anyone can declare a package namespace. There’s a loose convention that you should use your reverse domain name as a prefix (for example, if our department released a package for autograding, we might put it in the edu.umass.cs.autograder package). But many modern java packages declare a top-level namespace – you see this in most assignments for this class, where we just define a similar top-level namespace. In practice, projects that do similar things don’t usually have the same name, and/or agree to avoid namespace collisions.

Importing packages

Sometimes you want to use something not in the current namespace. Then you need to “import” it.

For example, if I want to print a random number between one and six:

public class Die {
  public static void main(String[] args) {
    Random r = new Random();
    System.out.println(r.nextInt(6) + 1);
  }
}

it won’t compile, because Random is not in the namespace. But I can use an import statement: import java.util.Random; to add it to the namespace.

Eclipse will do this for you in one of its “quick fixes” but beware: there’s sometimes more than one class with the same name! If you import the wrong one, it likely won’t have the behavior you expect!

Finding packages

Where does Java look for packages? By default the JVM has access to a set of “built-in” packages, that form the Java Platform API:

https://docs.oracle.com/javase/8/docs/api/index.html?overview-summary.html

Again, mostly in the java and javax namespace, but also some others.

But where do the compiled classes, that is, the virtual machine code for them, actually live? On my machine, a big chunk of them live in /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib in the JARs there.

JARs are essentially ZIPfiles of compiled Java classes with some extra stuff (a Java-specific manifest, describing their contents, that the JVM knows how to read). Let’s take a look in rt.jar. Hey look! Our friends System and String!

You may have noticed that the file, say String.class (which is the compiled representation of String.java) lives in a directory java/lang/. That looks a lot like java.lang., doesn’t it?

Not a coincidence! The JVM requires that packages map to (that is, directly correspond to) directories with the same name(s), and that classes map to .class files within those directories.

But there’s still a piece of the puzzle missing. How does the JVM know where to look for these directories? How did it know, for example, that /Library/Java/JavaVirtualMachines/jdk1.8.0_102.jdk/Contents/Home/jre/lib/rt.jar was a place to search?

CLASSPATH and friends

There are three mechanisms the JVM uses. One is under your control: the “CLASSPATH”. The other two you can’t (easily) change – there is a “bootstrap CLASSPATH” and an “extensions directory”.

The latter two are configured when your JVM is installed, and they contain classes that are part of the JRE, JDK platform, and vendor-distributed extensions.

But the CLASSPATH you do control. If you run from within Eclipse, you can add JARs (and directories) to the CLASSPATH by selecting the appropriate menu items, either “Build Path -> Add to Build Path” for JARs or “Build Path -> Use as Source Folder” for a directory. You can also manage the Build Path (“Configure Build Path”) and view what’s on it, which is how I found the rt.jar I showed you earlier.

Putting your own classes into packages

If you want to put a class into a package, like, for example, you want to move our Die class into the nerdy.gaming package, you need to explicitly declare the package at the top of the file, and move it into an appropriate directory, in order for it to compile and be recognized by the JVM. Eclipse will prompt you to do one if you do the other.

Notice that now the top of the file has a nerdy.gaming package declaration; it lists just the package, not the classname (unlike imports, which list a full class name). Also notice that the package is rooted at a directory that’s in our CLASSPATH; in this case, the src/ directory in the Eclipse project. You can tell it’s in the CLASSPATH due to the little “target” on the folder; it’s on the so-called “build path” which Eclipse uses as one component of the CLASSPATH.

In-class exercise

(first, on board:) Suppose I had the following directory hierarchy:

src/marc/liberatore/Banana.java
support/marc/liberatore/Smoothie.java

and the following code in Smoothie.java:

class Smoothie {
  public static void main(String[] args) {
    System.out.println("Add a " + new Banana());
  }
}

and I intended the two classes to both live in the marc.liberatore package.

Questions:

  1. What directories need to be on the classpath in order for this to compile?
  2. What package should we declare at the top of this file?
  3. Do we need to import anything? If so, what?

Review: arrays

In our review of 121 material so far, we’ve exclusively used a single container type, the array. Container types are types that “hold” other types, and the array is probably the most basic: a fixed-size sequence of values (that are themselves either primitive types or references to objects) that can be read or written in approximately “constant time”. We call these values “cells” or “elements” in the array.

Constant time means that no matter how big the array is, (to a first approximation) it takes the same amount of time to access (read or write) an element. We expect each of these statements to execute in about the same amount of time:

array[0] = 5;
System.out.println(array[1]);

array[1000000] = 12;
System.out.println(123456789);

(modulo some caching effects, which are COMPSCI 230/335 material).

But arrays have some downsides, as well. For example, they’re fixed size: you need to know how many elements you want in advance. You can cheat here by allocating a giant array, but that’s wasteful for small inputs, and potentially won’t work anyway if your data is of size (giant array + 1).

Instead, we might use a higher-level abstraction; that is, a more general “container type” than an array. This week we’ll describe the List:

  • which is like (but not the same as) an array, and
  • which can be implemented in terms of an array.
  • we’ll do an array-based implementation of the List in lecture (though this is the only data structure where we’ll do this in detail)
  • we’ll briefly discuss but not fully implement a linked-list, an alternative to the array-based list, and talk about its pros and cons

We’ll show how our List compares to the Java API’s List, and this will lead into generics and container types, two topics that will come up again and again in material this semester.

Operations on arrays

To recap, what can you do with an array? You can declare it, allocate it, read or write individual elements, and determine its length at runtime.

Declare an array of Strings called strings.

Allocate a String array of size 50 and assign it to strings.

Set the zeroth element of strings to “Hi”.

Print the zeroth element of strings.

Print the length of strings.

String[] strings;
strings = new String[50];
strings[0] = "Hi";
System.out.println(strings[0]);
System.out.println(strings.length);

That’s it for builtins of the array. If you want to do much else, you gotta build it yourself. (Note that there is a java.util.Arrays that has some helpful methods you can call on arrays, in particular the static Arrays.toString method is helpful when caveman debugging arrays of primitive types; otherwise the debugger can be helpful.)

So let’s talk about the List abstract data type.

Lists

Note I said “abstract data type.” First we’ll talk about the properties and assumptions we might expect from a List, in the abstract. Then we’ll do an actual, concrete implementation of the data type and see how it measures up.

“List” is a very overloaded term; we’ll simplify this by choosing a specific set of assumptions, that implicitly define an abstraction:

  • lists are unbounded, that is they don’t have a fixed size (if implemented with arrays, the arrays dynamically resize)
  • duplicate elements are allowed (when searching for an element, one of several equal elements is as good as any other)
  • lists can contain null elements (I hope you like NullPointerExceptions! though note some implementations might forbid null elements)
  • lists support an add operation, either to the end of the list or to a specific place (sometimes called an “insert”)
  • lists support a remove operation, either of a specific value or of an element at a particular index
  • lists support a get operation to return the element at a specific index
  • lists support a size operation to determine how many elements are currently in the list
  • lists can be in sorted order, but by default are not (you can imagine a SortedList that enforces this property)
  • and many more, but we’ll get to them later when we look at the full API that Java supplies.

How could we adapt our previous code?

Declare an List of Strings called strings.

Allocate a String List and assign it to strings.

Insert the string “Hi” at the front of the list strings.

Append the string “Bye” at the end of the list strings.

Print the zeroth element of strings.

Print the length of strings.

List<String> strings;
strings = new ArrayList<>();
strings.add(0, "Hi");
strings.add("Bye");
System.out.println(strings.get(0));
System.out.println(strings.size());

Some things to notice:

The type of strings is List<String>. It’s a variable of type List; we could also make it of type ArrayList or LinkedList, but what we care about is that it satisfies the List interface (see the javadocs).

Further, it’s a parameterized type. Much like methods can take arguments, so can types! Usually, we see this with container classes (like Lists), where the argument (in <>s) is the type of thing it’s holding. More on this later.

Sorta-like arrays, Lists have an add operation that either appends, or inserts at a specified point – we illustrate both here. They also have a set operation, but it can only replace existing items, not insert new ones. And a get, which is much like array lookups.

More next class.