Before You Begin
- If you do not yet have an account with GitHub, please make an account now.
- If you haven't yet signed up with the class autograder, visit ag.cs61bl.org.
- If you plan on using your own computer for this course, you should check out lab01b to set up everything you'll need for the semester.
- You can request an EECS instructional account here.
- Be aware that there are a large number of setup steps this first week. Don't be discouraged, and make sure to ask for help if you're stuck! The best place to ask for help is in the actual lab.
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:
- Reading, which will give you background information on new topics.
- Coding exercises, which ask you to complete a certain task using Java.
- 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.
A. Java Compilation & Development
Java 1.8 is currently installed on the instructional machines. You may need to install it on your personal computer. You can find instructions to do this in lab01b.
Java Is Compiled
Java is sometimes called a "compiled language" while Python is called an "interpreted language". Neither of these terms, however, make any sense. What is true is that in most Java implementatons, programs are compiled (translated into a form that is easily executed) in a separate, user-visible step from being executed, while most Python implementations give users the impression that the actual programs that they write are executed directly.
The Java implementations we use compile Java source code (what is written by the programmer) into Java class files containing virtual byte code, which then may be executed by a separate program.
Let's see an example. Here is the Hello World program in Java. Don't worry about understanding it for now - we'll deconstruct it later in this lab.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
Here is what the corresponding compiled Java code (called bytecode) looks like. The Java virtual machine can interpret this to run the program.
Why Compilation?
At this point, you may be wondering why Java is (usually) compiled. Compilers are quite helpful for several reasons:
They can check for errors prior to runtime (program execution). The Java compiler will catch and report errors like:
- type errors, which can be produced by giving functions the wrong objects as parameters (like a
String
instead of aint
) - syntax errors, which can be caused by forgetting syntactical elements like parentheses or braces
Catching these and many other types of errors prior to runtime help catch many of the possible bugs caused by programmer error and make Java programs more stable before they are run.
- type errors, which can be produced by giving functions the wrong objects as parameters (like a
- Compilers can help speed up programs. Programs run by interpreters can be slow because interpreters must parse text that is understandable to humans and translate it into an executable form. Furthermore, for various engineering reasons, this executable form is generally not actual machine code (directly executable by the hardware), but some other intermediate form that another program (the interpreter) then executes. A compiler does this translation work once and saves the instructions to a file variously called a binary, object file, or (in the case of Java) a class file.
There are many other reasons some languages have compilers, 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 Java program.
Compiling Java Programs
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), so you can set it up
on your own computer if you'd like. It's also pre-installed on the lab machines.
Let's pretend you have a Java file called FranceSimulator.java
. To compile FranceSimulator.java
, you
would type the following command into your terminal:
$ javac FranceSimulator.java
Note that every time you make changes to your Java source code, you will need to save and recompile it in order for the changes to have effect at runtime (think about why that is so).
Running Java Programs
Compiling your program using the command above should generate .class
files. For example, let's pretend that you've compiled FranceSimulator.java
. This would generate a new file called
FranceSimulator.class
.
If you were to open this .class
file in a text editor, you'd see something like the bytecode in the
image earlier in this lab. Instead, you'll typically use the Java bytecode interpreter to run the class file. We could invoke the Java bytecode interpreter on our new class file by typing the following command in a terminal:
$ java FranceSimulator
This would begin execution of the program. Note that you do not type FranceSimulator.class
. That is a common mistake that will
cause an error message like this:
Error: Could not find or load main class
Exercise: Compiling & Running Hello World
Using your favorite text editor, create a new Java file called HelloWorld.java
and type in the HelloWorld
program below.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
When you're done, compile and run it using the following commands:
$ javac HelloWorld.java
$ java HelloWorld
You should see Hello world!
printed out in your terminal.
A Note on IDEs
An IDE (integrated development environment) is a program that can be used to write and run programs without using command line. They provide useful features like debugging and are popular tools for programmers to write and test their code. There exist many popular IDEs for Java such as:
We will learn more about IDEs in Thursday's lab. For this lab, we'll be sticking with command line.
IMPORTANT: The course staff will only officially be supporting IntelliJ. If you want to use a different IDE, the course staff may be unable to offer assistance.
B. Writing Java Programs
Java Is Object-Oriented
Java is an object-oriented programming (OOP) language. What this means is that you'll want to think of your programs in terms of objects that you can manipulate and how these objects will interact with each other. If you've never seen such a language before, this will seem a little overwhelming at first, but we'll be exploring this more in future labs and projects.
Format of a Java Program
Every Java file contains a class, interface, or enum. For now, let's just discuss class definitions. A class definition provides the name of the class and serves as a template of an object. In addition, a class definition contains methods that define the behavior for a particular class and variables that help to define this behavior.
Here is a deconstruction of the aforementioned "Hello World" program:
A Java program consists of a collection of one or more of these Java files
containing classes, interfaces, or enums. At least one of the classes in a Java
program must contain a method called main
. This main method is called in order
to run the program.
This is why running the HelloWorld
program prints out Hello world!
. The
main
method in the HelloWorld
class is being run when you type
java HelloWorld
into the terminal.
Exercise: Leap-Year Program
For your next Java program, you'll be solving a small problem. We'll be writing a program that prints out whether or not a year is a leap year or not. A leap year is either:
- divisible by 400 or
- divisible by 4 and not by 100.
For example, 2000 and 2004 are leap years. 1900, 2003, and 2100 are not leap years.
Your Java file should be called LeapYear.java
. These lines should go into the
main
method of the LeapYear
class. Remember that your class name should
match the name of your file. Your program should include the line:
int year = 2000;
If you're not sure where to start, you can copy and paste lines from below. Note that you may not need all the lines, and you may use a particular line multiple times.
} else {
if (year % 100 != 0) {
if (year % 4 != 0) {
if (year % 400 != 0) {
if (year % 100 == 0) {
if (year % 4 == 0) {
if (year % 400 == 0) {
System.out.println (year + " is a leap year.");
System.out.println (year + " is not a leap year.");
}
Some Java Vocabulary in Leap Year
- The
%
operator implements remainder. Thus, the value ofyear % 4
will be 0, 1, 2, or 3. - The
!=
operator compares two values for inequality. The code fragmentif (year % 4 != 0)
reads as "if the remainder when dividingyear
by 4 is not equal to 0." - The method
System.out.println
prints its argument to "standard output" (which in this case is your terminal window) when called. - When one of the arguments of the
+
operator is a string, the arguments are concatenated as strings. String concatenation is the operation of joining two character strings end-to-end.
Testing Leap Year
When you've arranged the lines properly and compiled successfully, running the program should print out the following line:
2000 is a leap year.
You can test your program with other year
values by changing the line
int year = 2000;
to other integer values. Once your program is correct, save it as LeapYear.java
.
Documentation and Comments in Java
Writing easy-to-understand code is one of the most important skills a programmer can have! We encourage
you to write code that is self-documenting by picking variable names and
function names that make it easy to know exactly what's going on! Don't name
your variables a
, b
, and your functions f
, g
, etc. Instead, give them nice descriptive names
like year
or getUserName
.
Sometimes variable and method names are not enough. For example, if you are implementing a complex algorithm, you may need to add comments to describe your code.
There are two formats for comments in a Java program:
Single-line comments start with two consecutive slash characters and continues to the end of the line:
// This is one kind of comment
Multi-line comments start with
/*
and end 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 */
C. Git and Local Repositories
Here it comes, the part of the lab that brings pain.
In 61BL, you'll be required to use the git version control tool, which is wildly popular out in the real world. Unfortunately, the abstractions behind it are fairly tricky to understand, so it is likely that you will encounter significant frustration at some point as you learn to use git.
That being said, we promise that this will become one of the most important tools you can teach yourself in your journey of becoming a computer programmer.
Before you proceed, read sections A-C of the Using Git Guide.
Git Exercise
Now that you've read the first 3 sections of the git guide, you're now ready to start using Git! Follow along with the example below. If you typed out all the commands from the tofu example, you may skip this exercise.
... and if you'd like more of a challenge, read the direction for each step and guess what the command should be before looking at the screenshots/running the command.
Initialize a Git repository called
learning-git
.Add a file called
HELLO.txt
.Suppose we want to save the state of this file in git. First we stage it:
Now that we have staged
HELLO.txt
, it will be included in our commit. Commit the file with a message of your choice.Let's update our
HELLO.txt
. Here I used a text editor called vim to add some text to the file, and a tool called cat to show the file to you in the screenshot. You can use any text editor of your choice.If we want to save the change we made in git, first we'll have to stage it. Stage it with the
add
command. Then, suppose we decide we no longer like the change we made, and we don't want to save it in Git. Unstage the file with thereset
command.Important: The reset command does NOT change the actual HELLO.txt file. In terms of our panorama analogy, it only deletes the picture we took of this file!
Now suppose we dislike the changes we made so much, we want to return the file to its state the last time we committed it -- that is, before we added the extra lines. Discard your changes to
HELLO.txt
since your first commit with thecheckout
command. Here, instead of specifiying a commit ID, we'll use the -- command, which uses the most recent commit by default.
It is important that you understand every step of this example. Please ask for help if you are confused about any step.
D. Git and Remote Repositories
We're now ready to finish off the lab. But first...
STOP! Before you proceed, read section D of the Using Git Guide.
For this class, you'll be required to submit your code for assignments to your personal or group GitHub repositories in our class' organization. This is for several reasons:
- To spare you the incredible agony of losing your files.
- To save you from the tremendous anguish of making unknown changes to your files that break everything.
- To ensure that we have easy access to your code so that we can help if you're stuck, and so that we can grade your code.
- To dissuade you from posting your solutions on the web in a public GitHub repository.
- To expose you to a realistic workflow that is common on every major project you'll ever work on again.
- To enable safer, more equitable partner collaborations.
Before beginning this section, ensure that you received access to a GitHub personal repo in our class organization. You can check this by visiting the cs61bl organization. This repo should be a natural number: your class ID. Memorize this ID, for we'll ask you to write it down during exams.
For the first week of class, you and your partner will _both_ need to submit your work to your personal repos. After the first week of class, you will be expected to select a partner with whom you'll work for the remainder of the summer session. From that point on, you'll be submitting to a repository that you and your partner share.
Note: You'll need to perform this series of steps to set up your Git repo on each computer you use (e.g. instructional computer, personal computer). If you know that you'll only be using your personal computer, feel free to do this only on your personal computer (and not your lab account).
Clone the repo that you were given in the cs61bl organization.
Navigate to the spot in your folders on your computer that you'd like to start your repository.
$ cd cs61b # Note: This may be different on your computer.
Enter the following command to clone your GitHub repo. Make sure to replace the
***
with your own class ID/repo name.$ git clone https://github.com/cs61bl/***.git
If you'd like to SSH instead of HTTP (and set up your own SSH key), feel free to also do that instead. If you don't know what we're saying, then using https is fine. The advantage of SSH is that you won't have to type in your GitHub password every time you use your repository, so it may be worth looking into.
Move into your newly created repo! (Make sure you do this part, or the rest of the steps below will not work correctly.)
$ cd *** # Note that *** refers to your own class ID.
Add the
skeleton
remote repository. You will pull from this remote repository to get starter code for assignments. (Make sure that you are within the newly created repository folder when the continue with these commands.)Enter the following command to add the
skeleton
remote.$ git remote add skeleton https://github.com/cs61bl/skeleton.git
Again, if you set up your own SSH key, you can use SSH here rather than HTTPS.
Listing the remotes should now show both the
origin
andskeleton
remotes.$ git remote -v
Working on the Skeleton
You must now pull from the
skeleton
remote in order to get the starter code for lab01. You will also do this when new projects and assignments are released. To do this, use the spookiest command in the whole git toolbox:$ git pull skeleton master
What this does is grab all remote files from the repo named skeleton, and copies them into your current folder.
- Move the
LeapYear.java
that you created earlier in this lab into thelab01
directory. Stage and commit
LeapYear.java
.$ git add lab01/LeapYear.java $ git commit -m "Completed LeapYear.java"
Push these changes to the
master
branch on theorigin
remote repo.$ git push origin master
You can verify that this has been successful by checking your repo on GitHub.
Note: With power comes responsibility. Now that you know how to push to remote repositories, make sure that you are never pushing your class work to a public repo. (The class repository we assigned to you is private.) Pushing your work to a public repo is a violation of the academic honesty policy as it potentially enables other students to see your work.
E. Complete and Submit Lab 1
Now that you have the skeleton, you should see a file in the lab01 directory
called Year.java
.
This program is very similar to LeapYear.java
. The difference is that in Year.java
, the user will specify a year using a command line argument, e.g.
$ java Year 2000
2000 is a leap year.
You should fill it out, using your code in LeapYear.java
. Test it out and make sure it works by compiling and running it (as you learned in the beginning of this lab). After you have finished working on Year.java
, you should add, commit, and push it, just like you did for LeapYear.java
.
Autograder
At the beginning of this lab, you created an account with ag.cs61bl.org. If you log in now and click on lab01
on the Assignments page, you should see that the code you pushed to your GitHub repo was automatically graded. Even if your most recent push has not been graded, you can trigger a "build" (ask the autograder to test your code) by clicking on the Run Autograder
button.
Important: We highly encourage you to make frequent commits and pushes (every time you make significant progress and/or finish a logical component of your project). Having commits means that you will not lose your work (unless you happen to delete your Git repositories on both your local computer and GitHub). Note that lack of proper version control will not be considered an excuse for lost work, particularly after the first few labs.
Conclusion
A Quick Recap
- You can use javac and java to compile and run your code.
- Java is an object-oriented language. Every Java file must contain either a class, interface, or enum.
- When running a Java program, the
main
method runs. Thismain
method can call other methods/classes in the program. - Git is a version control system that tracks the history of a set of files in the form of commits.
- Commit often and use informative commit messages.
- Pull from the
skeleton
remote repository to get or update starter code for assignments. - Push your commits to your GitHub repository to submit labs and projects.
Deliverables
Here's a quick summary of what you need to do to complete this lab:
- Create a GitHub account and sign up with the class autograder by visiting ag.cs61bl.org
- Setup your development environment for this class by following the lab1b guide
- Read through the Git Guide and work through the git exercises in section C and D. This includes setting up your personal repository and adding
skeleton
as a remote. - Write code for
LeapYear.java
then move it over toYear.java
. - Git add, commit and push your changes for
Year.java
and run the autograder on your submission.