--- tags: summer 2018 cs61bl --- # CS 61BL Week 1 Notes Hello! Here are the notes I've compiled from my first week of tutoring sessions. If you're already familiar with all the topics, check out the **Resources** section for more practice or insights. Also, [here](https://drive.google.com/drive/folders/180f9opglO7kWzNEvQbfiYpBDv_mrlv6n?usp=sharing) is a folder of all practice problems I have sent out. [TOC] ## Class Architecture * **Methods:** functions * **Fields:** variables * **Constructors:** intializes object's state * Same as class name ```Java class Student { //fields String major; int GPA; // default constructor: public Student() {} // written constructor public Student(String major, int GPA) { this.major = major; this.GPA = GPA; } //Methods public declareMajor() { System.out.println(major); } } ``` ## Primitive Types Copied from CS 61BL Summer 2018 Lab 2: ![](https://i.imgur.com/dul4g8m.png) ### Declaring primitive types without intialization ``` Java int a; // 0 double b; // 0.0d long c; // 0 char d; // '\u0000' boolean e; //false ``` ## Classes, Objects, and References ![](https://i.imgur.com/nDGpy0Z.png) Taken from [StackOverFlow](https://stackoverflow.com/questions/9224517/what-are-classes-references-and-objects) ### Declaring objects without intialization ``` Java String j; //null Object i; //null ``` ## '==' vs .equals Only primitive types work with '==' comparison. ```Java int i = 5; int j = 5; i == j; //returns true ``` '==' compares object references. When an object is instantiated (even if it seems to have the same components as another object), it will have a new memory address. Equals is a method inside the object's class that overrides Java's default comparison method. (For Lab 4, you had to copy over the equals method for IntList). It allows you to compare the objects based on their components rather than their memory addresses. ```Java String h = 'hi'; String j = 'hi'; h == j; //returns false h.equals(j); //returns true ``` ## 'Static' Keyword You can have static fields, methods, and classes (out ot scope). When a field or method is static, it can be applied to the general class. If a field or method is non-static, it is applied to all instances. Let's look at the example below: ```Java class CalStudent { int currentGPA; //non-static field static int maxGPA = 4.0; //static field //non-static method public int getCurrentGPA() { return currentGPA; } //static method public static int getMaxGPA() { return maxGPA; } //non-static method public int getCurrentGPA() { return currentGPA; } //constructor public CalStudent(int GPA) { currentGPA = GPA; } } ``` We use the class name to call static methods and return static fields. ```Java CalStudent.getMaxGPA(); // returns 4.0 CalStudent.maxGPA; //returns 4.0 ``` We use an instance object to call non-static methods and return non-static fields. ```Java CalStudent bob = new CalStudent(3.5); bob.getCurrentGPA(); //returns 3.5 bob.currentGPA; //returns 3.5 ``` #### Can a constructor be static? No. It's a common misconception. Remember a constructor is *not* a method despite having a similar structure. #### Can we call static fields/methods with an instance object? Yes! The following code will work. After all, all individual students still have the same max GPA. ```Java CalStudent bob = new CalStudent(3.5); bob.getmaxGPA(); //returns 4.0 bob.maxGPA; //returns 4.0 ``` #### Can we call non-static fields/methods with a static object? No! It would make no sense to ask the general CalStudent for a current GPA because we all have different GPA's. ```Java CalStudent.getCurrentGPA(); //compile-time error ``` More specifically, we get the error below. ```Java Cannot access non-static field in static method main ``` #### Why have static and non-static fields and methods in the first place? It leads to less repetition of code. A common acronym in programming is DRY: Do not Repeat Yourself. If we wanted to instantly update a field for multiple instances, we could do it through static keywords. **Example:** We write a class that represents babies born **last year**. As a result, they all have the same age. ```Java class Baby { public static int age = 1; public void ageOneYear() { age++; } } ``` Suppose one year has passed and we want the time change to reflect in all of the individual babies. The static keyword allows us to update the age all at once. ```Java Baby sally = new Baby(); sally.age; //returns 1 Baby billy = new Baby(); billy.age; //returns 1 sally.ageOneYear(); //1 year has passed sally.age; //returns 2 billy.age; //returns 2 ``` #### When to use static vs non-static? Keep it static if you don't want to access a non-static field or method. ## Constructors Constructors intialize the objects state and create instance objects. Each time an object is created using 'new', the constructor is being called. If a constructor isn't written in the class, you use to the default Candy() to intialize an object. ```Java class Candy { String color; boolean soft; //default constructor public Candy() {} //written constructors replace the default constructor //multiple constructors can exist as long //as they have a different number of arguments + //different types of arguments public Candy(String colour, boolean softCandy) { color = colour; soft = softCandy; } public Candy(boolean softCandy, String colour) { color = colour; soft = softCandy; } public Candy(boolean hard) { soft = !hard; } } ``` If a written constructor replaces the default constructor, the default constructor cannot be called unless a constructor with the same structure is written in as well. ## Scoping and Variable Lookup In Java, variables have lookup rules that follow the checklist below: 1. Local Scope (located in the code block) 2. Instance and Class 3. Superclass #### Usage of 'this' keyword 1. If a parameter or variable in the local scope has the same name as a field: use this.variableName to assign something to the field 2. A method requires you to use the current instance object ```Java class Fruit { public boolean isTasty; public String color; public Fruit(boolean isTasty, String color) { //isTasty = isTasty; //color = color; //The lines above only affect the variables in the local scope //adding 'this' allows us to assign //the values passed in to the class fields this.isTasty = isTasty; this.color = color; } public Fruit growFruit(Fruit f) { return new Fruit(f.isTasty, f.color); } //method requires current instance object public Fruit cloneFruit() { return makeFruit(this); } } ``` ## Access Modifiers Access modifiers limit the scope of the field or method they're used on. Don't worry about subclasses for now. ![](https://i.imgur.com/VUjXo5B.png =x200) :::info Package refers to a group of related classes. Files contained in the same folder are considered to be in the same package. ::: ## Recursion tips In comparison to iteration, recursion usually has more parameters because we open a new frame to call the function again and lose important references. #### Steps to Take 1. Think about the **parameters** in the recursive problem and what is lost every time we call the method. 2. Think about the **base case** (what stops the method from running infinite times). It should have something to do with the **parameters**! 3. Think about what to **recurse on**. If we know the parameters and what the function is returning, we know we have to either **update** the parameters or use the parameter to keep **track** of a reference we lose. 4. Think about **edge cases** that we can catch with **if statements**. What if the object you're recursing is null? What if something errors before you hit your goal? #### Common Base Cases I've Observed * IntLists: IntList is null or IntList.next is null * Integers: i <= 0 ## Relevant Resources [CS 61B CSM Worksheets](https://csmberkeley.github.io/csm-61b/): CSM stands for Computer Science Mentors. It's an organization that tutors groups of students in lower-division CS courses (and EE 16A) during the semester. They provide weekly worksheets and solutions that are really useful to work through. (Also, the instructor of this course was the creator of these worksheets) [CSM Video Walkthroughs](https://www.youtube.com/channel/UCqiudaLea8HNE23GBC34R5Q/videos): helps explains some CSM problems! [CS 61B Course Staff Video Walkthroughs](https://www.youtube.com/channel/UCNBSbBTFx8nFahcQyZOYOgQ/videos): contains Spring 2016 and Spring 2018 Midterm 1 Walkthrough! [Java Gotchas](https://kevinl.info/cs61b/java-gotchas/): helps with understanding how Java works [Week 1 Practice Problems](https://drive.google.com/drive/folders/180f9opglO7kWzNEvQbfiYpBDv_mrlv6n?usp=sharing): compiled by Tina