Lab 1: Welcome to CS 61BL

A. Introduction to the Labs

Find a Partner

Introduce yourself to a partner - someone you don't already know - to work on activities in this lab session. If you are unfamiliar with using a terminal, try to find a partner that has had some experience with one.

Overview

You'll be doing a lot of collaboration this semester, some online and some offline. The labs consist primarily of three types of activities:

  1. Coding exercises, which ask you to complete a certain task using Java
  2. self-tests, which are multiple choice questions scattered throughout the lab. They aren't graded, and you can check the answer/explanation whenever you want, but you'll be doing yourself a disservice if you don't try your hardest before answering them. Self-tests are meant to allow you to check you understanding of the lab so far.
  3. gated collaboration discussions, in which you post an answer to a free response question and then get to review the answers of your fellow students afterwards.

The next step gives you practice with gated collaboration. Gated collaboration discussions are done through bcourses. Before you add a post to the below discussion, you'll have to sign up for which section you're in, in bcourses.

First, visit the bcourses site for this course. Click on the People link on the left. Click on the Groups tab and add yourself to the lab section you're in. Now you're ready to participate in discussions!

Discussion: Gated Collaboration

Link to the discussion

Discuss with your partner: What do you think make good and bad qualities of a lab partner? Make a post, and make sure you can view the responses of other students in your lab, too.

For this discussion (and all others), you only need to make one post per partnership. In your post, include both your and your partner's names and two-letter logins, as well .

Obtaining the Files

Great, now let's learn some Java and start coding. Download the files for Lab 1. You'll want to unzip them into a folder of the same name.

B. Introduction to Java Compilation & Development

Java Is Compiled

When you write code in Java, you will be writing files with a .java extension. But .java files cannot be run directly, unlike Python's .py files. .java files must be compiled first. The compiled form of a .java file is a .class file. This, then, can be run.

Java is a compiled language rather than an interpreted language like Python. While interpreted languages are translated at runtime, compiled languages are translated before reaching the virtual machine. This means that a program called a compiler translates the Java written by the programmer into Java bytecode which can then be interpreted by the Java virtual machine.

Compilers are quite helpful for several reasons. A few are listed below:

  1. Compilers can check for errors prior to runtime. The Java compiler will catch and report errors like TypeErrors, which can be produced by giving a function the wrong type of object as a parameter (in Java, functions care!), and SyntaxErrors, which can be caused by forgetting syntax arguments like parentheses or braces. Catching these and many other types of errors prior to runtime help catch a large majority of the possible bugs caused by programmer error and make Java programs more stable and bug-free before they are run.
  2. Compilers can help speed up programs. Interpreted languages can be slow because they must parse text that is understandable to humans and translate it into bits that can be understood by the machine. The compiler does this translation work so that it happens before running the program and does not slow down the running time of programs.
  3. Compilers can verify access rights to classes and methods. Java has a lot of built-in security because access rights can be assigned to each class and method that limit what other classes or methods have access to. The compiler checks that every program that uses a class or calls a method has the correct access rights to use or call it. You will learn more about this naming information later in the course.

There are many other benefits of a compiler, some of which you will learn by taking CS 61C. But for now, you will just need to know how to compile and run your program.

Compiling & Running on Command Line

There are many different Java compilers, but we'll be using javac for command line in this class. javac is included in Oracle's Java Development Kit (JDK). If you'd like to run Java programs on your own computer (rather than the lab machines), then you'll have to download and install the JDK at the link above. You can install either Java 8 or Java 7. We recommend Java 8, but this class won't be using any Java 8 specific features, so it doesn't really matter.

If you're not using the lab computers right now, click the button for some more detailed installation instructions:

Toggle Solution

OS X Instructions:

You should be able to download from the above link, follow the installation instructions, and be good to go.

Ubuntu Instructions:

You can download from the above link, or you can also use apt-get. Up to you.

Windows Instructions:

Are a bit complicated. First download and install using the above link. However, this will not immediately allow you to use java and javac on the command line. You'll have to update your environment variables first. Click the button to see a walk through of updating your environment variables.

  1. Windows 8/8.1: Launch the Start Screen by pressing Windows, and type 'Environment Variables'. Select "Edit the system environment variables".

    start_menu

    Windows 7 and earlier: Open the Start Menu and launch the "Control Panel". Search for "Environment Variables", and select "Edit the system environment variables".

    control_panel

  2. Navigate to the "Advanced" tab, and click "Environment Variables...".

    sys_props

  3. Under "System variables", click "New..."

    env_vars

  4. Define the following variables — if the variable already exists, select the variable and click "Edit...", then add the value specified below to the front of the value, followed by a semicolon; otherwise, click "New..." and use the values specified below as the value of the variable:

    • JAVA_HOME: Set this to the location which you installed Java, for instance, C:\Program Files\Java\jdk1.7.0_51 in my case. java_home
    • PATH: Add %JAVA_HOME%\bin; to the beginning of the value of this variable.

Running your First Java Program

Got Java working? Let's try it out. Say you want to run a Java program you wrote called File.java. First you must compile it. In the terminal, you would type the following:

javac File.java

If this command is successful, a file called File.class will appear. This is the compiled version of File.java. Once File.class is present, you can then run the program by typing in the terminal:

java File

Let's practice. In the terminal, go into the lab01 folder you downloaded. Compile and run the HelloWorld.java file. It should print the message Hello, world! to the screen.

Java Documentation

The Java language has incredible API (Application Programming Interface) documentation, which is often very helpful when using classes and methods in packages created by other programmers. Don't worry about understanding how to use or read this documentation yet; just know that it is available and may come in handy in the future.

C. Introduction to the Eclipse Programming Environment

Starting Eclipse

Eclipse is an integrated development environment (IDE) for Java. For now, you can think of an IDE as a text editor with a bunch of extra features. One of Eclipse's most useful feature is that it is constantly automatically compiling your code for you, so you don't have to compile manually anymore. It also provides other useful features like code completion, version control, and debugging. Thus, it is a popular tool for programmers to use to write and test their code.

In this class, we'll be teaching you to use Eclipse to write and run your Java code. You usually won't be expected to run Java from the terminal like we did earlier, though it's important to know nonetheless.

On a lab computer, start Eclipse by typing

eclipse &

in a terminal window or by finding Eclipse in the application menu.

If you're not using the lab machines, you'll want to download Eclipse to your own computer. It shouldn't be much more difficult than installing any other program. Visit the eclipse website download section and download it. Select the Eclipse version for Java Developers.

(OS X users, if you get a warning "can't be opened because it is from an unidentified developer", you'll have to lessen your security requirements, which you can find in System Preferences)

When you first start Eclipse, it will ask you where to maintain its workspace, the location on disk where your programs and other information are stored. Its default choice, the workspace directory in your home directory, is reasonable. (If you click on the check box that says to use the workspace directory by default, it won't ask you again.) After taking some time to get everything initialized, it will present you with a "Welcome" window. Click the button to take you to the Workbench.

You'll see multiple panels in the Eclipse environment. The large panel in the center, currently blank, will contain editors, where you will type your programs. The other panels, titled "Package Explorer," "Outline", etc., are called views and provide helpful information about your overall programs. You can close any view or editor; you'll always be able to get them back. (Select Window > Show View)

Programming in Eclipse

You will now build a Java program in Eclipse. You can either do this from scratch, or load something already created. You'll do both in this class.

In Eclipse, all Java programs must be in a project. Java code lives in files within a project.

Start by selecting New > Java Project from the File menu. Project" wizard. Name your project lab01 with "Use default JRE" and "Use project folder as root for sources and class files" selected. If it asks you about opening the Java perspective, say yes (and tell it not to ask again).

YearStuff1

(If you don't see Java Project under New, you might be in the wrong perspective. Try Window > Open perspective > Java. In this class, the only perspectives we'll use are Java and Debug)

Now select New > Class from the File menu. Provide the class name YearStuff. For the question, "Which method stubs would you like to create?", select public static void main (String[] args) and unselect the other options. Leave the package field blank. Then click "Finish". Eclipse should provide you with a program framework.

YearStuff2

Eclipse automatically provides the structure for this new class: a couple of identifying comments, the header for a class definition, and the header for a main method. We will come back to this Java program later.

(Note: please ignore the package lab01; line above. Please don't put your code in a package.

Format of a Java Program

The Java programs we'll be writing at the beginning each consist of class definitions. A definition provides the name of the class and its variables and methods. Here's an example of a "Hello world" program in Java:

HelloWorld

At least one of the classes in a Java program must contain a method named main. This is called by the operating system to run the program.

Comments in Java

There are two formats for comments in a Java program:

  1. single-line comments: starts with two consecutive slash characters and continues to the end of the line

    // this is one kind of comment
  2. multi-line comments: start with /* and ends with */

    /* This is a multi-line comment */

Some commenting styles add single asterisks at the start of each line in the comment after the first, to improve readability.

/* This is a
 * multi-line
 * comment */

Example: Leap-Year Program

We will now be working with the following lines below from the file lab01/YearCheck.stuff.

Or you can copy the lines directly from here:

} else
if (year % 100 != 0) {
if (year % 4 != 0) {
if (year % 400 != 0) {
int year = 2000;
System.out.println (year + " is a leap year.");
System.out.println (year + " is not a leap year.");

Arrange these lines in the main method of your class, so that it prints out whether the value of the variable stored in the variable year is a leap year. A leap year is either divisible by 400 or divisible by 4 and not by 100. You shouldn't need to add any other lines of code (but you can if you really want), though you will have to add some right braces.

You may need more than one copy of some of the lines. You should work equally with your partner.

Note some Java vocabulary used in this code:

Note some features of Eclipse:

Running a Program

Once you have a syntactically correct program, you run it by selecting Run As > Java Application from the Run menu. The output "2000 is a leap year." should appear in the Console window. If you don't see a Console window, you might have to go to the menu option Window > Show View > Console.

Re-running the program can be done by clicking on the Run button, a circular green button with a white triangle, or by using the "Run" menu again. You should run your program (at least) four times, changing the value of the year variable each time. As one of you types, the other partner should supervise. Test your program on the following year values:

Any errors you encounter are probably due to putting the lines in the wrong order. Fix the errors by reordering the lines (don't change the tested expressions). The editor keeps track of what lines have changed since the program has last saved. Note how it does this as you make the successive changes to year. Try a few other program modifications to see what happens.

Executing a Program under Control of Debugger

The Eclipse environment includes a debugger that we'll practice using now. Switch roles with your partner at this point.

Double-click in the left margin by the first if statement of your program. A blue dot (or red square) should appear, indicating that a breakpoint is set at that statement.

Now rerun the program, selecting Run > Debug As. After saving your program, Eclipse will ask about opening the Debug perspective; click "Remember my decision" and "Yes". It will then display the program with the if statement highlighted; it has suspended execution at that set breakpoint, and is waiting for instructions to proceed.

Observe the "Variables" window, which lists all the values of variables accessible at the point where the program is suspended. At this point, the year variable and its value should appear in the window.

Other actions available when the program is suspended include the following, all accessible through the "Run" menu:

Practice with these, and keep notes if necessary in your notebook. Clicking "Java" in the upper right corner of the Eclipse window gets you back to the Java "perspective", ready for more editing.

Discussion: Eclipse Features

Link to the discussion

Discuss each of these questions with your partner. If you don't know the answer, talk to another pair or test in Eclipse.

  1. What is the purpose of the circle with the minus in it, in the second column of the window displaying program text? Why might this feature be useful?
  2. How can you tell which lines of the program have been changed since the program was last saved?
  3. How do you determine which "}" is the matching brace for a given "{"?
  4. How would you tell that there's a syntax error in your program without trying to run it?
  5. Suppose you set a breakpoint, but the program didn't stop there. What does this mean? Explain what you would do about this.

D. Submission System

Introduction to UNIX Commands

The lab computers run on a linux operating system. As such, you can use terminal commands to make changes to your directory and files. Here are some important ones that you may find useful in this course:

There are some other useful tricks when navigating using the terminal:

Lab Submission System

To submit lab assignments, you have to submit them on the lab computers using a submission system authored by Paul Hilfinger.

Before you submit your lab, you will need to register your class account so that your account is linked to your student ID. You will only need to run this command once for the duration of the whole class (not every time you submit).

register

Go to the directory where your file YearStuff.java is stored. For example, to navigate in terminal to workspace/lab01/, you would type:

cd workspace/lab01

Verify that the file that you want to turn in is in that directory by listing the files in that directory:

ls

Submit the program using the submit command:

submit lab01

It will ask you what your partner's login is. You and your partner should only submit once. It will complain if your file names are different from what we've specified.

Note: If you need to rename your file in Eclipse you can right-click on the file in Eclipse and select Refactor > Rename. Or within terminal you can rename the file by typing:

mv yourfile.java YearStuff.java

If you manually change the name of your file within terminal, make sure that your class name matches so that your code still runs in Eclipse. A Java file must have the same name as the class it contains in order to compile and run.

Submitting this file is a graded part of your first lab assignment.

Working & Submitting Remotely

It may be that you wish to work remotely if you were unable to complete work in the lab.

If you are a Windows user, you will need to use PuTTY to login to your class account from your own computer and WinSCP to transfer files between your computer and class account. This is a helpful video created by the staff of CS 61A.

If you are on an OS X (Mac) or UNIX/linux computer, you can use your Terminal to both transfer files and access your class account remotely.

If you are trying to copy files from school account to your home computer (using your home computer), use the following command:

scp -r cs61bl-**@torus.cs.berkeley.edu:~/path/to/file homecomp/path/to/file

If you are trying to copy files on your home computer to the school account, use this command:

scp -r homecomp/path/to/file cs61bl-**@torus.cs.berkeley.edu:~/path/to/file

To access/login to your class account from your home computer, use the ssh command:

ssh -X cs61bl-**@torus.cs.berkeley.edu

Checking Your Submissions & Grades

The following commands may be useful:

glookup
This command will check and display your grade in the class.

glookup -t
This command will display the timestamps of your group's submissions, as
well as how late your submissions were.

glookup -s ASSIGNMENT1[,ASSIGNMENT2,ASSIGNMENT3,...]
This command will display grade statistics for your whole class on the
specified assignment(s).

glookup-all
This command will display your grade relative to the rest of the class,
with statistics such as mean, class rank, and grade distribution.

E. Provide Information About Yourself

Introductory Survey Questions

You'll have to complete the below survey as part of your first homework assignment.

Link to the survey

F. Conclusion

Submission

For your first homework assignment, make sure you submit YearStuff.java, and that you also complete the introductory survey. These, along with tomorrow's lab, are due before your Thursday lab. In general, all Monday and Tuesday labs will be due before your Thursday lab, and all Thursday and Friday labs will be due before the following Monday lab.

Change Your Password

Before you leave lab today, you might want to change the default password associated with your account. In terminal type the following command:

ssh update

Type in your old password to access the system and then select the menu option to change your password. It will ask you for the old password one more time and then your new password twice.

Readings

Before your next lab, read the following:

Make sure you understand the following vocabulary words about object-oriented programming from your readings before your next lab:

Extra: For additional practice you might want to try some of the exercises at CodingBat to get more familiar with Java.