Lab 1: Java & Git

Before You Begin

Welcome to CS 61BL! We have a wonderful summer planned for y’all, and we’re so excited that you’re here!

First thing’s first: setup! In this class, you’ll be using real-world tools, and that means that you’ll likely run into real-world problems with configuration and setup these first few days. 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, so if you’re doing this from home, please join us in person instead!

If ever something isn’t working, or a screen that should show up isn’t showing up, make sure you ask for help – do not keep going because this can make it more difficult for us to identify the problem later on when you actually do hit a dead-end.

Partner up!

Your lab TA will assign you a partner to work with today – but don’t worry, you’ll only have to work with them today. In fact, everyday this week, we’ll assign you a new partner to work with so that you have a chance to meet different people in your lab section! For more information, take a look at our Collaboration Guide.

Java and Git Installation

You only need to install Java and Git if you are using your personal computer (which most students choose to do.) If you’d like to use the lab computers instead, then request an EECS Instructional Account and you may continue with today’s lab since this will already be installed. Your instructional account can also be accessed remotely via SSH. Instructional accounts might also be of interest to you if you’d like to take advantage of our complimentary print quota.

If you’d like to use your own computer, follow the setup procedure to install Java, Git, and any other operating system-specific requirements.

GitHub and BeaconTM

We have a wonderful in-house system for centralizing your grades and student information, and it is called BeaconTM (copyright 2019, all rights reserved and patent pending).

We will also setup here our CS 61BL GitHub repository (“repo”), which you will need to submit all coding assignments.

Create an account at GitHub.com. If you already have an account, you do not need to create a new one.

Go to the Beacon website and you’ll be guided through a few steps to complete your GitHub repository registration. Please follow them carefully! You’ll need to be logged in to your Berkeley account to complete the Google Form quiz. Note: this registration website is somewhat new and is subject to catastrophic and unexpected errors. If something terrible happens while you’re working through the steps, please let your TA know immediately.

After completing all of the steps, you should have received an email inviting you to collaborate on your course GitHub repository. Hooray! Don’t follow the instructions that GitHub says you might want to do – instead, follow the instructions given later in this lab.

More details about your repository

Your repository will have a name containing a number that is unique to you! For instance, if your repo is called “su19-s42”, you’ll be able to visit your private repository at https://github.com/Berkeley-CS61B-Student/su19-s42 (when logged into GitHub).

Additionally, the instructors, TAs, and tutors will be able to view your repository. This means you can (and should!) link to your code when asking private debugging questions on Piazza. No other students will be able to view your repository. As a reminder, you may not post code from this course publicly, even after completing the course.

Git

In this course, you’ll be required to use the git version control system, which is wildly popular out in the real world. Unfortunately, the abstractions behind it are fairly tricky to understand, so don’t be frazzled when you encounter significant frustration as you learn to use git.

Towards the middle of the semester, we’ll be learning the inner workings of Git in much greater detail but, for now, let’s just get a working knowledge of how to use git.

Before you proceed, read sections up to the Remote Repositories section of the Using Git Guide.

Do not proceed until you have read sections up to the Remote Repositories section of the Using Git Guide. You do not need to read past that.

Git Exercise

Now that you’ve read the first 3 sections of the Using Git Guide, you’re ready to start using git! As part of your lab checkoff, you will be working through a small git workflow by setting up a git repository and making a couple commits to the repository. An academic intern or staff member will look at your git repository during checkoff to ensure that it is in a good state.

If you need help with creating directories, creating files, changing directories, etc., refer back to Learn to Use the Terminal.

Create a directory called lab01-checkoff. You can put this directory anywhere on your computer (unless you have already cloned your su19-* repository, in which case, you should **not put this directory inside of your su19-*** repo).

Move into the lab01-checkoff directory, and initialize a git repository in this directory.

Create a file called 61b.txt in any way you’d like. In this text file, add the text “61b version 1” into it.

Create another file called 61bl.txt in any way you’d like. In this text file, add the text “61bl version 1” into it.

Begin tracking only61b.txt, and create a new commit containing just this file, with the following commit message: “Add 61b.txt”.

Make a modification in 61b.txt by changing the text in the file to: “61b changed to version 2”.

Make another commit, this time containing both 61b.txt and 61bl.txt. The commit message should be: “Update 61b.txt and add 61bl.txt”.

Finally, make one more modification to 61b.txt by changing the text in the file to: “61b changed to version 3”. Don’t commit this version.

At this point, if you were to type in git status, something like this should show:

Also, if you were to run git log, something like this should show:

Be sure to save this repository and directory until you get checked-off by a lab assistant.

Along with other short conceptual questions involving git, you will be asked to revert 61b.txt back to the version in the most recent commit, as well as back to the earliest version of the file, so make sure you know how to do this!

Hint: Look into the checkout command. But be careful when using the checkout command, as your repo might end up in an unexpected state. Make sure to always specify a file (or directory) when you use checkout.

Specifically, if you see something about your repository being in a detached HEAD state as a result of a checkout command, that is something we don’t want. Read the git-WTFS guide for more on what it is and how to fix it.

Git & Remote Repos

In this course, you’ll be required to submit your code to your course GitHub repository. This is for several reasons:

To spare you the incredible agony of losing your files.

To submit your work for grading and to get results back from the autograder.

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.

To dissuade you from posting your solutions on the web in a public GitHub repository. This is a major violation of course policy!

To expose you to a realistic workflow that is common on every major project you’ll ever work on in the future.

To enable safer, more equitable partner collaborations.

Setting up your Git Repository

Clone your su19-*** git repository.

Navigate to the spot in your folders on your computer that you’d like to start your repository. In the example below, we’re assuming you want all your stuff in a folder named cs61bl, but you can pick a different name if you’d like.

Your terminal might use a different prompt than $. Type out or paste only the part after the prompt.

$ cd cs61bl

Enter the following command to clone your GitHub repo. Make sure to replace the *** with your class repository number.

$ git clone https://github.com/Berkeley-CS61B-Student/su19-***.git

If you’d like to setup SSH access so you don’t need to type in your GitHub password every time you use your repository, feel free to follow the relevant instructions on GitHub instead. If you don’t know what that means, just use the command above.

If you use macOS and you’ve previously logged into GitHub, your computer may have remembered your username and password from before. If it’s not the same login information as you’re using now, you may need to update keychain credentials.

Move into your newly created repo! (Make sure you do this part, or the rest of the steps below will not work correctly.)

$ cd su19-***

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-su19.git

Listing the remotes should now show both the origin and skeleton remotes.

$ git remote -v

If you get an error that says “Not a git repository”, make sure you’re in the su19-*** directory.

Change your Git name and email

Every time a commit is made, your name and email address is recorded as part of the commit. Change your Git name and email by running the following commands, substituting your own name and email address where appropriate.

If you were prompted to do this after making a commit (as part of the Git Exercise), make sure to amend the commit to update the commit’s username and email.

$ git commit --amend--reset-author

Change your Git text editor

We’ll also change the text editor associated with Git. Sometimes, Git needs your help when inputting things like commit messages, so it will open a text editor for you. We recommend using Atom or Sublime Text, though you’re welcome to use your preferred text editor. Instructions differ based on your platform.

Working on the Skeleton

You must now pull from the skeleton remote in order to get the starter code for lab 1. 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 (which is located at https://github.com/cs61bl/skeleton-su19.git) and copies them into your current folder.

If you get an error similar to “fatal: refusing to merge unrelated histories”, you can fix this by, for this time only, running:

$ git pull --rebase--allow-unrelated-histories skeleton master

If you list the files in your current directory, you’ll see that there is now one folder: lab01. Look in the lab01 folder and you’ll see files called LeapYear.java and magic_word.txt that you’ll work with in later parts of this lab.

Move the HelloWorld.java file that you previously created in the set up portion of this lab into the lab01 directory.

You can verify that this was successful by checking your repository online at GitHub.com.

Checkoff: Git Exercise

Once you’ve verified that your code was pushed to GitHub, add your and your partner’s name to the queue on the whiteboard, or if there isn’t one, then just raise your hand to get your git exercise checked off.

A staff member or academic intern, upon completion of the lab checkoff, will tell you what to put into the magic word file in order to pass the autograder. If there’s a wait, feel free to move on until your name is called.

Java

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 implementations, 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 again in Java. Don’t worry about understanding it for now - we’ll deconstruct it later in this lab.

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 a int)

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.

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 BaconEggs.java. To compile BaconEggs.java, you would type the following command into your terminal:

$ javac BaconEggs.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 BaconEggs.java. This would generate a new file called BaconEggs.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 BaconEggs

This would begin execution of the program. Note that you do not type BaconEggs.class. That is a common mistake that will cause an error message like this:

Error: Could not find or load main class

You can give this a try by compiling and running your HelloWorld.java file that you just added to your lab01 folder.

$ javac HelloWorld.java
$ java HelloWorld

Just like when we ran this the first time earlier today, you should see Hello world! printed out in your terminal.

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

In the lab01 folder, you should see a file called LeapYear.java. This program is supposed to test whether or not a given year is a leap year. The user will give a year as a command line parameter (examples given below), and then print out whether or not that year is a leap year, e.g.

Style

In this course, we’ll work hard to try to keep our code readable. Some of the most important features of good coding style are:

Consistent style

Spacing, variable naming, brace style, etc.

Size

Lines that are not too wide, source files that are not too long.

Descriptive naming

As applied to variables, functions, classes. We prefer meaningful names like year or getUserName instead of x or f.

Avoidance of repetitive code

Strive to never have two significant blocks of code that are nearly identical except for a few changes. We’ll teach you a number of large-scale design and small-scale style techniques for working around these situations.

Comments where appropriate

Line comments in Java use the // delimiter. Block (or multi-line comments) comments use /* and */. Make sure to update the Javadoc comment (“Update this comment…”) and provide a short description of the method’s behavior.

In addition, if you used any external resources, please cite it in the Javadoc comment using the @source tag like in the example above. It’s not necessary to cite anything from the course staff, but you should cite any other resources like StackOverflow by pasting in a link.

We have a more formal style guide available for you to read at your own leisure, but the golden rule is this: Write your code so that it is easy for a stranger to understand.

Java Tips

The && operator computes the boolean and of two expressions, while || computes boolean or.

The % operator implements remainder. Thus, the value of year % 4 will be 0, 1, 2, or 3.

The != operator compares two values for inequality. The code fragment if (year % 4 != 0) reads as “if the remainder when dividing year by 4 is not equal to 0.”

When one of the arguments of the + operator is a String, the arguments are concatenated as Strings. For example, 2 + "horse" + "battery" would return "2horsebattery". This is different from Python which doesn’t perform this automatic conversion.

Discussion: Compilation Errors

Throughout this lab, you may have run into some errors like the one below after running javac LeapYear.java.

Please report any issues you may have to Piazza. Entire error messages and/or screenshots are welcome.

Today and even when partnerships are locked down, everybody must submit to Gradescope to receive credit (both you and your partner). In the case of a partnership, you may have the same code and you can even submit from the same repository, but you both are reponsible for making your own submission before the deadline.

We strongly encourage you to make frequent commits! Lack of proper version control will not be considered an excuse for lost work, particularly after the first few weeks.

Recap

Java is a compiled language. You can use javac and java to compile and run your code. Our first programs reveal several important syntax features of Java:

All code lives inside a class.

The code that is executed is inside a function, a.k.a. method, called main.

Curly braces are used to denote the beginning and end of a section of code, e.g. a class or method declaration.

Statements end with semi-colons.

Variables have declared types, also called their “static type”.

Variables must be declared before use.

Functions must have a return type. If a function does not return anything, we use void,

The compiler ensures type consistency. If types are inconsistent, the program will not compile.

Java is also statically-typed. Static typing gives us a number of important advantages over languages without static typing:

Types are checked before the program is even run, allowing developers to catch type errors with ease.

If you write a program and distribute the compiled version, it is (mostly) guaranteed to be free of any type errors. This makes your code more reliable.

Every variable, parameter, and function has a declared type, making it easier for a programmer to understand and reason about code.

There are downside of static typing, to be discussed later.

We also discussed briefly how to comment code and coding style. Coding style is very important in this course and in the real world. Code should be appropriately commented as described in the textbook and lectures. We haven’t learned what good style is yet, nor when to use comments.

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 so it’s easy for the future-you to find what the change you’re looking for. Pull from the skeleton remote repository to get or update starter code for assignments and use Gradescope to submit labs and projects.