1. Introduction

This document provides a brief tour of some Java features that appear in code shown in lecture, in recitation, or which you may encouter in your homework. In general, students taking 15-214 through the normal sequence of prerequisites already know at least two programming languages, and it is our expctation that students can learn the low-level details of a new language fairly independently. Thus, our lectures focus on conceptual elements of object-oriented programming. While we provide this document as a supplement to get you oriented to the rest, you should choose a Java resource that provides more in-depth coverage of any issues you do not fully understand. Some of the Java resources available include:

2. Packages

All Java code exists in a package. Java files optionally start with a package declaration stating what package the code is in; if no package is given, the code is in the un-named default package. All code you will write in this class should be in a package that starts edu.cmu.cs.cs214 and ends with an identifier that reflects the assignment, lecture, or recitatation of which the code is a part. By convention, package names start with the URL of the organization that produced the code, with the dot-separated identifiers in reverse order; this helps to avoid name conflicts.

If a class SimulationDriver is defined in a package edu.cmu.cs.cs214.lect01.trees, the full name of the class is edu.cmu.cs.cs214.lect01.trees.SimulationDriver and you can use this name from anywhere to refer to the class. Within the edu.cmu.cs.cs214.lect01.trees package, though, you can use the short name SimulationDriver. If you type import edu.cmu.cs.cs214.lect01.trees.SimulationDriver after the package declaration in a file that's not in the same package, you can also refer to it by the short name.

If you don't make a class, method, or field public or private, then by default that Java source element is visible from the same package but not from others. In general, you should make everything either public or private unless you have a specific reason to do otherwise. All elements of an interface are public by default, so you don't need to specify that explicitly.

Later, you will use code from Java standard library packages such as java.util, which contains the Java collections classes, or java.io, which contains libraries for performing I/O. In the tree simulation example from lecture 1, we used the class java.util.Random. You can see that we import it in the file Simulation.java, so we can use the short name. If you want to know how to use Random, you can look at the web-based “JavaDoc” documentation, available at http://docs.oracle.com/javase/8/docs/api/. Click on the package java.util and then on the class Random, and you'll find a description of all the methods of this class. If you document your methods by putting a JavaDoc comment before themi.e. a comment that starts with /**you can generate your own documentation in this form using the command-line javadoc tool.

3. Main

The main function of a program is called main in Java, just like in C. While C allows you to optionally get any command-line arguments using argc and argv, in Java you have to declare a single argument of type String[] to hold these arguments. To find out how many arguments there are, use args.length (if args is the name you used for the command-line arguments variable).

The main function is a static method. A static method can be invoked without creating an object, which is good since no code is run and no object is created before main starts. You can invoke a static method as if the class were an object, for example SimulationDriver.main(myArgs). In this class, you should avoid using static methods and fields, except for the special case of main. We will see there are other exceptions later, when we discuss the Singleton design pattern; but even the use of this pattern should be rare.

4. Final fields and constructors

You may have seen final in some of our code. This means that you can only assign to a field once, when it is initialized. You can initialize a final field either by giving it a value when you declare it, like this:

final int DAYS_IN_A_WEEK = 7;

or by assigning to the field in the constructor of the containing class (or the class initializer, for static fieldsbut that's advanced material you shouldn't have to use in this class).

For an example of a constructor, see Location.java in the sample tree simulation code. A constructor is a special method that has the same name as the containing class. It does not have a return type. It's job is to assign values to all the fields of the object, so the object is properly initialized and ready to use. The constructor may have arguments; these are passed to the contrustor from the new statement.

5. Annotations

You'll notice that in the sample tree simulation code, there are @Override annotations on many of the methods in LodgepolePine and InfectedPine. These are methods that were declared in the Agent interface, but no method body was given there. Therefore, the LodgepolePine and InfectedPine classes have to define a method implementation; this is called overriding the method. Whenever you override a method, you should use the @Override annotation. This helps people understand what you are doing, and it also helps Eclipse give you an error message if you intended to override a method but actually didn't (for example if you used the wrong argument signature, this could happen).

6. Enhanced For Loop

In LodgepolePine.java you'll find a for loop that begins:

for (Location loc : emptySpots) {
    ... // body goes here
}

This code is an abbreviation for the loop:

for (int i = 0; i < emptySpots.length; ++i) 
    Location loc = emptySpots[i];
    ... // body goes here
}

7. Printing to standard out

In the recitation 1 code, in Animal.java, the code in speak prints to standard output using the line:

System.out.println(name + ": " + sound);

Here, System is the name of a class that has system functionality, and out is a static field in that class. The static field out holds a PrintStream (click to see its interface) object that you can use to write to the standard output. println as the name suggests writes a string followed by a carriage return. The string is constructed with the ‘+’ operation, which conveniently concatenates Strings together in Java.