## FAQ#

Each assignment will have an FAQ linked at the top. You can also access it by adding “/faq” to the end of the URL. The FAQ for Lab 1 is located here.

## Learning Goals #

In this lab, we will set up the software that we will use throughout the course: the terminal, git, java, IntelliJ, etc. We will also look at a small Java program and learn a little bit about Java syntax.

## Before You Begin #

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

First things 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 during your actual lab time. If you attempt to do this outside of that time and run into any problems, please come ask then through our ticketing system.

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 might make it more difficult for us to identify the problem later on if you do hit a dead-end.

### Partners #

For all labs, partners are optional, and you can change partners for every lab. If you’d like to work with a partner but don’t have one, your lab TA will assign you one to work with today. For more information, take a look at our Collaboration Guide.

## Personal Computer Setup #

### Task: Installing a Text Editor #

If you don’t already have a favorite text editor, we recommend installing one.

The most popular GUI text editors these days seem to be:

1. Sublime Text (free but nags you until you pay): https://www.sublimetext.com/
2. Atom (free): https://atom.io/
3. Visual Studio Code (free): https://code.visualstudio.com/

See this text editor review for a more thorough look at these and other text editors.

The choice isn’t very important, as we will only be using a text editor a few times throughout the course. Later in this lab, and for the rest of the course, we will be using an IDE.

You do not need to pick one of the options above. You’re welcome to use a different text editor entirely (built-in text editors, vim, emacs, etc).

You should be able to use the default installation recommendations, but if you run into problems, do not hesitate to ask for help!

Depending on your operating system, there are a few things we need to do to set your computer up for 61B(L).

The precise steps to take depend on your operating system.

Move on to the next section only once you’ve completed the instructions above for your operating system.

Advanced users on Windows may also use the new WSL feature, but we will not be providing official directions or support. Note that if you use WSL, you’ll need to do the setup on both Windows and WSL (Linux), following the instructions above.

## The Terminal #

### Learn to use the Terminal #

In CS 61BL we will be using the terminal extensively, even more than you likely did in previous classes. Bash commands can be pretty powerful and will allow you to create folders or files, navigate through your file system, etc. To jump start your knowledge we have included a short guide of the most essential commands that you will be using in this class. Please carefully read this and try to familiarize yourself with the commands. We will help you as you get started, but by the end of the class we hope that you will have become a proficient user of the bash terminal!

• cd: change your working directory

cd hw


This command will change your directory to hw.

• pwd: present working directory

pwd


This command will tell you the full absolute path for the current directory you are in if you are not sure where you are.

• .: means your current directory

cd .


This command will change your directory to the current directory (aka. do nothing).

• ..: means one parent directory above your current directory

cd ..


This command will change your directory to its parent. If you are in /workspace/day1/, the command will place you in /workspace/.

• ls: list files/folders in directory

ls


This command will list all the files and folders in your current directory.

ls -l


This command will list all the files and folders in your current directory with timestamps and file permissions. This can help you double-check if your file updated correctly or change the read-write- execute permissions for your files.

• mkdir: make a directory

mkdir dirname


This command will make a directory within the current directory called dirname.

• rm: remove a file

rm file1


This command will remove file1 from the current directory. It will not work if file1 does not exist.

rm -r dir1


This command will remove the dir1 directory recursively. In other words, it will delete all the files and directories in dir1 in addition to dir1 itself. Be careful with this command!

• cp: copy a file

cp lab1/original lab2/duplicate


This command will copy the original file in the lab1 directory and and create a duplicate file in the lab2 directory.

• mv: move or rename a file

mv lab1/original lab2/original


This command moves original from lab1 to lab2. Unlike cp, mv does not leave original in the lab1 directory.

mv lab1/original lab1/newname


This command does not move the file but rather renames it from original to newname.

There are some other useful tricks when navigating on a command line:

• Your shell can complete file names and directory names for you with tab completion. When you have an incomplete name (for something that already exists), try pressing the tab key for autocomplete or a list of possible names.

• If you want to retype the same instruction used recently, press the up key on your keyboard until you see the correct instruction. This saves typing time if you are doing repetitive instructions.

### Task: Terminal Test Run #

Let’s ensure that everything is working.

1. First open up your terminal. Check that git is a recognized command by typing the following command:

git --version


The version number for git should be printed. If you see “git: command not found”, or similar, try opening a new terminal window, restarting your computer, or installing git again.

2. Second, let’s check that javac and java are working. javac and java allow Command Line Compilation, or in other words, the ability to run Java programs directly from the command line. In practice, most developers run Java programs through an IDE like IntelliJ, so we won’t be using command line compilation for much this semester other than testing your setup. Start by running the following commands at your terminal.

mkdir ~/temp
cd ~/temp

1. Then, open your operating system’s file explorer in this directory. You can do this from the command line:

• Mac: open .
• Windows: explorer .
• Ubuntu: gnome-open .
• Linux Mint: xdg-open . or mate .
2. In this newly opened directory, create a file HelloWorld.java with these contents:

public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}

3. In your terminal, enter ls (list the files/folders in this directory). You should see HelloWorld.java listed.

4. Run javac HelloWorld.java. If this produces any output, then something may be wrong with your setup. Try opening a new terminal window or restarting your computer. If that still doesn’t work, see the Troubleshooting section under the directions for your operating system.

5. Type ls, you should see both HelloWorld.java and a freshly created HelloWorld.class (the javac command created this file).

6. Run java HelloWorld. It should print out “Hello world!” for you. If it didn’t, something is wrong with your setup!

7. You’re done! You can also delete the “temp” folder and its contents as you please.

The screenshot below shows what we’re hoping for when we do steps 4-7. If you see something similar to this, your java setup is complete.

## GitHub and Beacon #

Instead of bCourses, CS 61BL uses an in-house system for centralizing your grades and student information called Beacon.

In this section, we’ll set up your Beacon account as well as your CS 61B GitHub repository (“repo”), which you will need to submit all coding assignments.

1. Create an account at GitHub.com. If you already have an account, you do not need to create a new one.
2. 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 must be logged in to your Berkeley account to complete the Google Form quiz. If any errors occur while you’re working through the steps, please let your TA know immediately.
3. After completing all of the steps, you should receive an email inviting you to collaborate on your course GitHub repository; accept the email invitation from both emails and you should be good to go. This email will be sent to the email that you used to create your GitHub account, which may not necessarily be your Berkeley email. Hooray! Don’t follow the instructions that GitHub says you might want to do – instead, follow the instructions given later in this lab.

Your repository will have a name containing a number that is unique to you! For instance, if your repo is called “su22-s42”, you’ll be able to visit your private repository at https://github.com/Berkeley-CS61B-Student/su22-s42 (when logged into GitHub). If your repo number is not “42” this link will not work for you. Replace “42” with your own to see your repo on 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 in the ticketing system. 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. Doing so is a violation of our course policies and you might be subject to disciplinary action.

## Git #

In this course, you’ll be required to use the Git version control system, which is wildly popular out in the real world. Since the abstractions behind it are fairly tricky to understand, don’t be worried if 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.

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.

If at some point during this exercise git prompts you to update your username and email, now is a good time to change your git name and email

1. Create a directory called lab01-checkoff. You can put this directory anywhere on your computer (unless you have already cloned your su22-s*** repository, in which case, you should not put this directory inside of your su22-s*** repo).
2. Move into the lab01-checkoff directory, and initialize a git repository in this directory.
3. Create a file called 61b.txt in any way you’d like. In this text file, add the text “61b version 1” into it.
4. Create another file called 61bl.txt in any way you’d like. In this text file, add the text “61bl version 1” into it.
5. Begin tracking only 61b.txt, and create a new commit containing just this file, with the following commit message: “Add 61b.txt”.
6. Make a modification in 61b.txt by changing the text in the file to: “61b changed to version 2”.
7. Make another commit, this time containing both 61b.txt and 61bl.txt. The commit message should be: “Update 61b.txt and add 61bl.txt”.
8. 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. For this exercise 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.

You can and should continue doing the lab if there is a queue to get checked off.

### Git and Remote Repos #

First, read the Remote Repositories section of the Using Git Guide.

In this course, you’ll be required to submit your code using Git to your course GitHub repository that you created in Account Setup. 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.
• 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.

#### Clone your su22-s*** 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.

cd cs61bl


Enter the following command to clone your GitHub repo. Make sure to replace the *** with your class repository number (this should be the repo number you were assigned through Beacon, not your lab section number).

git clone https://github.com/Berkeley-CS61B-Student/su22-s***.git


After cloning your terminal will report “warning: You appear to have cloned an empty repository.” This is not an issue, it is just git letting you know that there are no files in the repo, which is what we expect here.

Alternatively, you can also set up 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 without the Github Credentials Manager, 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!

cd su22-s***


Now we will 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 you continue with these commands.) Enter the following command to add the skeleton remote.

git remote add skeleton https://github.com/cs61bl/skeleton-su22.git


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

git remote -v


If you see an error like fatal: not a git repository make sure you have properly moved into the cs61bl 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.

git config --global user.name "<your name>"
git config --global user.email "<your email>"


#### 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. Follow the instructions here and make sure that you follow the correct instructions for your operating system.

### Task: Working on the Skeleton #

You must now pull from the skeleton remote in order to get the starter code for this lab. You will also do this when new projects and assignments are released (or if there is ever an update to an assignment). To do this, use the spookiest command in the whole git toolbox.

git pull skeleton main


What this does is fetch all remote files from the repo named skeleton (which is located at https://github.com/cs61bl/skeleton-su22.git) and copy 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 main


If you list the files in your current directory, you’ll see that there are two new folders: lab01 and proj0. proj0 is your first project, but isn’t the focus of this lab, so ignore that as well. Look in the lab01 folder and you’ll see files called LeapYear.java, gradescope_word.txt, and magic_word.txt that you’ll work with in later parts of this lab.

This lab will continue with the installation of IntelliJ. While this is taking time to download, feel free to read / skim our Using IntelliJ Guide. You don’t need to read or internalize all of this to complete the lab. IntelliJ is complicated, but the core features should feel somewhat familiar to text editors you have used in the past. When you do have more time, we strongly suggest going through the linked guides and videos to maximize your ability to use the IDE.

Note that IntelliJ will be utilized more in later labs, but we highly recommend downloading it now to use for the project and gain familiarity.

## IntelliJ Setup #

IntelliJ is an Integrated Development Environment or IDE. An IDE is a single program which combines typically a source code editor, tools to compile and run code, and a debugger. Some IDEs like IntelliJ contain even more features such as an integrated terminal and a graphical interface for Git commands. Finally, IDEs also have tools like code completion which will help you write Java faster.

We will not be forcing you to use IntelliJ if you choose not to, but we highly recommend that you do use it. The debugger and other features will make it well worth the time it takes to learn as they should make you a more efficient programmer and one that can solve problems on your own. Additionally, IntelliJ is an industry-standard tool that you will almost certainly encounter if you work with Java again in the future.

From this point forward we will assume that you are using IntelliJ and if you do not we will not necessarily be able to offer the same support (e.g. if you use another program like VSCode for this class, our staff will not be able to help you with any problems like we would had you chosen to use IntelliJ).

Be prepared to use a real world software development package. It will seem very complicated for a while, but we’ll lead you down the narrow path to success. Ask for help if you are stuck! It can be very hard to guess the right thing to do in IntelliJ. We also offer the IntelliJ WTFS Guide to solve some of the common problems.

### Prerequisites #

1. You have installed Java 14 or higher.
2. You have successfully created your local repo for the class on your own machine. This is the su22-s*** repository you earlier.
3. You have pulled from the skeleton, and you have a lab01 directory.

1. Download the Community Edition of IntelliJ from the JetBrains website. As a student you can actually get a student license for the Ultimate version, but there are not any additional features that we will use for this class. It is recommended and assumed that you proceed with the Community Edition.

If you have an M1 Mac, select “.dmg (Apple Silicon)”. If you have a non-M1 Mac, select “.dmg (Intel).”

2. Run the installer. If you have an older version of IntelliJ, you should uninstall it at this time and replace it with this newer version. You can use all of the default installation options, with one exception, if you are on Windows, make sure you check the box “Add launchers dir to the PATH”. If you accidentally missed it, the easiest fix is to uninstall intelliJ, and running the installer again, making sure you check that box the second time around. The image below only applies to Windows.

Begin the setup process by starting up IntelliJ. Then follow the steps below.

Make sure you’re running IntelliJ Version 2020.3.1 or later before continuing. We are using IntelliJ Version 2022.1.2. Older versions may also work but we haven’t tried them ourselves.

1. In the Welcome window, click the “Plugins” button in the menu on the left.

1. On the window that appears, click “Marketplace” and enter “CS 61B” in the search bar at the top. The CS 61B plugin entry should appear. If you click the autocomplete suggestion, a slightly different window from what is shown below may appear – this is okay.

2. Click the green Install button, and wait for the plugin to download and install.

3. Now, search for “Java Visualizer”, and click the green Install button to install the plugin.

4. Finally, search for “Python Community Edition”, and click the green Install button to install the plugin.

5. If it appears, click the green Restart IDE button to finalize the installation. If you don’t see a Restart IDE button, just continue.

### Task: Setting Up Java Libraries #

Like in Python, we sometimes want to use libraries that others wrote. Java dependency management is a bit of a hellscape, so we will instead provide a Git repo that contains all the dependencies that we will use in this course.

First, move out of your repo with cd ... Then, run:

git clone https://github.com/cs61bl/library-su22


Below is shown the directory structure of library-su22. Look inside the folder and make sure you see the six .jar files listed below. If you’re using your operating system’s file explorer, the jar part might not show up in the filenames, and that’s OK.

library-su22
├── algs4.jar
├── hamcrest-core-1.3.jar
├── jh61b-junit.jar
├── junit-4.13.2.jar
├── ucb.jar
└── xchart-3.8.1.jar


The following instructions apply for both this lab and for future assignments. Each time after pulling from skeleton to get new lab or project files, you will need to run through the following steps again.

1. Start up IntelliJ.

2. Upon opening IntelliJ, click on the “Open” option.

3. Find and choose the directory of your current assignment (for today’s lab, it should be the lab01 directory), then press the OK button.

4. You should at this point be greeted with the main screen of IntelliJ which should look like the following. If you are greeted with any additional screens when setting up the project you can go ahead and select the default options for now.

5. Now we will set up the SDKs. Navigate to the “File -> Project Structure” menu,

and then make sure you are in Project tab. Afterwards, set your project SDK to 17, or any version greater than 14. If 17 isn’t available in the dropdown, make sure you downloaded the Java SDK earlier in the setup steps, and then execute the following:

6. Finally we will add the Java libraries. Note that you don’t need the libraries for this lab, but it is good practice walking through these steps going forward. Navigate to the “File -> Project Structure” menu, then select “Libraries” in the sidebar. You should be greeted with a screen that looks like this.

7. Click the “+ -> Java” button, which should prompt you to select the file location. Navigate to your su22-s*** repo and then find the library-su22/javalib folder within it. Select all of the *.jar files (i.e. select all of the files that end in .jar in the library-su22/javalib folder).

Next, if prompted to add the library to the lab01 module, select “Ok”. After these steps the libraries tab should look like the following with all of the .jar files listed here.

At this point if things have been configured correctly each Java file should have a blue circle next to its name, and when you open the file LeapYear.java file you should see a green triangle near the line numbers on line 5. Further, none of the code should be higlighted in red.

To test if everything is working correctly, run the LeapYear class, as shown below:

Since you haven’t implemented this function yet, the code should error as shown below, which is expected!

Now we will show you what submitting files will be like using Git! Open the file magic_word.txt in whatever your favorite text editor is (both you and your partner should do this). Discuss with your partner what your favorite flavor of ice cream is, then edit your magic_word.txt file to contain your partner’s favorite flavor (this is not the magic word you need to get credit).

Now stage and commit magic_word.txt (make sure you’re in your repo!).

git add lab01/magic_word.txt
git commit -m "My partner's favorite ice cream"


Finally, push these changes to the main branch on the origin remote repo.

git push origin main


Note if your default branch is master, we recommend changing it to main by asking your lab TA, though you can also replace main with master and execute the above.

You can verify that this was successful by checking your repository online on Github’s website.

### Checkoff: Git Exercise #

You will need to get your git exercise checked off by a staff member or academic intern. Your lab TA will tell you how to queue for help. It may be using a a whiteboard queue (for in-person labs), the online OH queue (for in-person and online labs), or a Discord queue (for online labs). Please ask your lab TA if you are unsure what queue they are using.

A staff member or academic intern, upon completion of the lab checkoff, will tell you what to put into the magic_word.txt file in order to pass the autograder. Make sure to delete the ice cream flavor from earlier.

If there’s a wait, feel free to move on until your name is called.

If the lab section is about to end and you have not been checked off yet, please submit a ticket in the ticketing system, or get checked off on Thursday.

## Java #

Java is sometimes called a “compiled language” while Python is called an “interpreted language”. Neither of these terms, however, make any sense yet. What is true is that in most Java implementations, programs are compiled (translated into a form that is more easily executed by computers) 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 implementation we use compiles Java source code (what is written by the programmer, typically in *.java files) into Java class files containing virtual byte code, which may then 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.

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:

1. 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 helps to prevent many of the possible bugs caused by programmer error, making Java programs more stable before they are run.

2. 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. As such, Java programs do not have to translate the code at runtime decreasing the overall runtime of the code.

There are many other reasons some languages have compilers, some of which you will learn if you take CS 61C or CS 164. 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 the Java Development Kit (JDK) and should be accessible to you now if you setup your computer correctly.

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


Every time you make changes to your Java source code, you will need to save and recompile it in order for your 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 (java) 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, but you do not type BaconEggs.class. If you ever try to run java <class name> command without creating a <class name>.class file with javac, it will cause an error message like this:

Error: Could not find or load main class


### Writing Java Programs #

#### Java Is Object-Oriented #

Java is an object-oriented programming (OOP) language. What this means is that you’ll organize your programs around the types of data that it manipulates. Each of these data types describes a class of objects and how these objects will interact with each other. Those of you who took 61A may recognize that term as having been applied to Python, but Java takes OOP a step further. In Java, all functions (or methods) and all variables reside in some class definition.

#### Format of a Java Program #

Every Java source file contains a class, interface, or “enum” (a special kind of class). For now, let’s just discuss class definitions. A class definition provides the name of the class and serves as a template for objects. In addition, a class definition contains variables and methods that define the behavior of that class.

Here is a deconstruction of the aforementioned “Hello World” program:

A Java program consists of a collection of one of more of these Java files. At least one of the classes in a complete Java program must contain a method called main having the header shown in the HelloWorld code above. This main method is where execution of your program begins.

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.

$java LeapYear 2000 2000 is a leap year.$ java LeapYear 1999
1999 is not a leap year.
$java LeapYear 2004 2004 is a leap year.$ java LeapYear 2100
2100 is not a leap year.


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.

To implement this you will have to implement the isLeapYear function in the file LeapYear.java. You can open your code in a text editor of your choice. You should be replacing the // TODO with your solution. Some additional guidelines for style and tips for Java can be found below.

### 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, methods, and 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.
Line comments in Java use the // delimiter. Block (or multi-line) 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.

### General Git Workflow: Saving Your Work #

As you are making changes to your code, it is good practice to save your work often. We have briefly discussed the commands, but now we will explain how they should be used in practice. In the case that you ever want to go back to another version of your code, it is better to have more options to roll back to. The next set of instructions will talk you through Git’s version of saving work through snapshots of your file system called commits.

1. After you have made some changes to the code within our local repository, Git will take notice of these changes. To get a report of the current state of your local repository use the command git status. Run this and try to interpret the results. Do they make sense to you or do they match your intuition? It is helpful to run this before running other git commands so you know what the state of things are.

2. If we want to save work that we have completed on a file, we must first stage the file and then we can commit it. Staging a file is achieved with the command git add; this does not save the file but it marks it to be saved the next time you commit. The two below commands show what saving work looks like in a git repository. For git add depending on what directory you are in, the path to the file you are adding might differ (hint: use git status if it’s not clear). Additionally the -m "Completed Year.java" part of the commit command specifies a message to be attached to this snapshot. It is useful to have descriptive messages in case you ever do need to revert to a previous version.

git add lab01/LeapYear.java
git commit -m "lab01: Completed LeapYear.java"

3. Once again, we want to push these changes to the Github repository so that your changes can be seen by us and graded. Your changes will also be available to pull if you had your repo initialized in other places or other computers.

git push origin main


Get into the habit of saving your files and doing the git commit step often (i.e. every 15 minutes). It will be incredibly helpful when you mess things up, since it allows you to back out of changes and to see what you have changed recently.

Basically, right when you sit down to work in your repository, first git pull to make sure you are starting with the most recent code. While you are working, frequently commit. When you are finished, git push so all your changes are uploaded and ready for you to pull again next time.

## Discussion: Compilation Errors #

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

LeapYear.java:3: error: incompatible types: int cannot be converted to boolean
if (year) {

1 error


This is a compilation error because the compiler, javac, is able to identify (‘catch’) the problem before we even run the code with java!

Discuss these questions with your partner (or someone else working alone):

• What does the bug above mean?
• What kinds of bugs is the compiler able to catch? What do you suspect is going on behind the scenes?
• What kinds of bugs is it unable to catch?
• And how is this similar or different to other languages you may have used before, like Python, Scheme, MATLAB, etc?

## Submission #

The last step is to submit your work with Gradescope. Gradescope is the site that you’ll use to submit lab and project assignments.

We added everyone’s CalCentral email to Gradescope on the first day of labs. Make sure to login using the email address listed on CalCentral.

To submit the assignment, follow the steps below. These steps are for every assignment.

1. Add your lab using git add.
2. Commit your lab using git commit.
3. Push your code to your remote repository, i.e git push origin main.
4. Open the assignment on gradescope, select your su22-s*** repository and the main branch, and upload the assignment.

Once you have a partner, you may have the same code and you can even submit from the same repository. One person should submit the assignment on Gradescope, and add the other person to their submission.

As above, 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 week.

### Checking Gradescope and Resubmitting #

If you wait for the autograder to finish running, and check your Gradescope score, you will see that you don’t have a full score. Don’t panic, this is expected!

Look at the autograder logs - you will see a failed test, with another secret word that is unique to your repo. Add this secret word to a file called gradescope_word.txt, and make another submission by following the same process. This submission should receive full score!

## 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.

If you haven’t had a chance to work on the optional Java introduction yet, now’s a good time! This will help the transition to programming in Java smoother over the next couple of labs.

### Deliverables #

As a reminder, this assignment has an FAQ page. There are three required files, all inside the lab01 directory:

LeapYear.java
You should have completed the isLeapYear method in this file.
magic_word.txt
You should have received the correct magic word from completing the git checkoff. If the lab section is about to end and you have not been checked off yet, please submit a ticket in the ticketing system, or get checked off on Thursday.
gradescope_word.txt
You will receive the correct Gradescope word from submitting once. Make sure to resubmit with the secret word.

Congratulations on finishing your first CS 61BL lab!