Exam 3 Cheat Sheet
Exam 3 Cheat Sheet
public static void main(String[] args) {} for (int count = 1; count <= 5; count++) {}
For each loop: Array:
for(int value : array) {} arrayname.length:
Class: arrayname[0] = value;
public class ClassName {} double [] prices = new double [5];
instance variables: for (int i = 0; i < array.length; i++) {
private String name {} System.out.println(array[i]); }
Constructor: API:
public ClassName(ParameterType parameterName) {} StdDraw.pause()
calling constructor: StdDraw.setPenColor(Color.BLUE);
ClassName variableName = new ClassName(constructor StdDraw.filledCirlce(x, y , r);
parameters); filledCircle(double x, double y, double radius)
Calling other method in class: filledSquare(double x, double y, double radius)
variableName.MethodName(); filledRectangle(double x, double y, double halfWidth, double
getter method: halfHeight)
à used to get instance variable in diff class that’s private StdDraw.clear(); // Clear the non-shown frame
public InstanceVariableType MethodName() { // Draw *all* objects in their locations (which may have changed
return this.InstanceVariable } from the last frame)
setter methods = mutators: StdDraw.show(); // Swap the non-shown frame with the one
Static methods class upon the class being shown on screen.
ClassName.staticMethod() Module 7 (Objects):
Non-static, call upon instance Objects are defined by a class
ObjectInstance.nonStaticMethod(); à class = blueprint/template/definition of an object
this: à class alone does nothing
à applies changes to variables in the object affected by the Instance variables = fields/properties/attributes
method à always private and at the top
Inheritance: à e.g. public class Person {
public class Child extends ParentClass {} private String name; }
super(): methods = behaviors/actions objects can perform
à refers to base class constructor method = creates an instance of an object, ensure
à in constructor, it calls the constructor in the base class all instance variables are set to acceptable values
public Employee(String theName) { à e.g. public Person()
super(theName); } à same name as the class
à super.methodInBase(), then add more operations in à nothing exists before the constructor
the method Person p1 = new Person (“Sana”);
LinkedList: à use new to call the constructor
LinkedList<DataType> listName = new LinkedList<>(); Other methods come after constructor
à calling constructor à public void print() {
à linked list is empty System.out.println(“Name: ” + name); }
.add(): Use DOT notation to call the method upon an instance of an
à adds to the end of the list object
In API, e stands for whatever type the list is à p1.print();
System.out.println(list); An object is anything that can exist and be manipulated by code
à prints list à int, double, Boolean can only have one value (primitive types)
à e.g. [Sunday, Monday, Tuesday] Class is like a type (instance variables stored in class and can be
.size(): used in all other methods in the class, larger scope)
à returns the number of elements in this list à class is capitalized to show you are dealing with an object
.get(int index): (e.g. Person)
à returns the elements at the specified position in the list Can have more than one constructor
à dimensions are not a thing with lists à default constructor has no parameters (generic)
Maps: à with default, be specific with instances (this.year = 2019;)
à no index; associations btwn keys and values Constructors with parameters allow us to be more specific
à every entry is a key value pair à public Car(int initYear) {
à a key could be anything this.model = 2019; }
Map<Key Type, ValueType> mapName = new HashMap<>(); to call constructor
à both types objects/classes à no parameters: Car car1 = new Car();
mapName.put(KeyData, ValueData) à parameters: Car car2 = new Car(2012);
.size() “this” = the instance you are currently working on
.get(Key) To print: car1.print;
à get value associated with a key If you mark something as private, you can’t access it outside of
à when nothing there, returns null the file where it has been declared (can’t be changed)
Iteration of Maps: If public, anyone can change the code or value
For(String name : phonebook.keySet()) { Getter is a method used to retrieve the value of instance
System.out.println(phonebook.get(name)) } variables (solves problem of private vs. public)
à keys of a name are a set à public String getName() {
à using for each loop to get value and keys in a map Return name; }
à use lists when order matters à return type is the same as the instance variable (a name =
Input/Scanner: String)
Scanner in = new Scanner(System.in); Setters are a method that allow us to change the values of
String name = scan.nextLine(); instance variables (always have a return type of void)
Math: à public void setID(int idNum) {
Math.round() if(idNum > 0) {
Math.random()*(upper-lower+1) + lower this.id = idNum; }}
Math.sqrt() static things belong to the class and don’t require an instance
Math.pow(numbers, 2) variable to function
nonstatic requires an instance of the class to operate à two separate objects can be considered equal if some or all of
main is always static the instance variables are equal (they are duplicates)
Module 8 (inheritance): More info
Used to model objects (talk ab them in diff ways/contexts) Course thisCourse = new Course (" CSE131");
Draw similarities btwn objects Course thatCourse = new Course (" CSE247");
Base class contains code we want to reuse System.out.printIn (thisCourse);
Use “extends” to inherit (extends = “is a”) System.out.printIn(thisCourse.isPrereq(thatCourse));
à public class Employee extends Person {} à thisCourse refers to an instance
à Employee = sub class (inheriting from base class = Person) à “Course thisCourse” is a type
Super = refers to base class à Course(“CSE131”) is a constructor (and method)
à use in sub class to define instance variables à isPrereq is a method
à super(theName), theName = instance variable from base class Given two String objects, x and y, if x == y is true then
constructor) x.equals(y) must also be true
à String output = super.getFood();, getFood is a method that True: classes can have more than one method with the same
exists in the base class that is not the constructor name
Sub class can override a method (will always use overridden False: the static methods of a class can access instance variables
method from sub class) False: methods that access instance variables must be declared
Polymorphism = we can treat objects differently in diff contexts as static
Can use method from sub class instead of base class bc False: methods must be declared as public
everything from base is in sub False: it is possible for an int variable to be null
à Meow(Person s) is the same as Meow(Student s) False: a private method can only call private methods
Module 9: True: an instance can have more than one variable referring to it
ADT = abstract data type Use == to determine if variables refer to same instance
à abstraction: use methods to abstract repetitive code to reuse Inheritance = technique used to acquire all instance variables
à abstracting methods themselves here and methods from a class
Interfaces are used to abstract behaviors common to many Constructor code example
classes à public Rectangle(double length) {
à vehicle interface could be created and applied to car/boat this.length = length; }
ADT types: list and set calling constructor in another class
A list is an ordered collection of objects (care about order) à Rectangle r = new Rectangle(9);
à allow for duplicate elements Accessors (getters and setters) = public
à maintains an order of items (regardless of importance) Draw method: public void draw() {}
Lists = parametric types Add method: public Fraction add(Fraction other) {}
à List<Color>, List<String>, List<Double> (angle brackets) Make new fraction: return new Fraction(newNum, NewDenom);
à int = Integer, double = Double (capitalized) public String toString() {} (print object to make easy to read for
All lists have same basic behaviors (so easy to switch out) people) (inside: return this.name + “ ”)
à adding something, finding nth element, finding element print objects: System.out.println(f.multiply(f2));
position, removing something, determining list length à f and f2 are objects, multiply is a method
à abstract behaviors into an interface Inheritance: public class MultipleChoice extends Question {}
à public interface List<T> { Array instance variable: private String[] choices;
public boolean add(T e); Calling constructor from base class example (adding choices)
public T get(int i); à public MultipleChoice(String prompt, String answer) {
public int indexOf(T e); super(prompt, answer);
public boolean remove(T e); this.choices = choices; }
public T remove(int i); override method example (with for each loop)
public int size(); } à public void displayPrompt() {
à above, T = parametric type super.displayPrompt();
à interface = collection of similar behaviors/methods shared int i = 1;
across multiple objects for(String choice : choices) {
ArrayList and LinkedList = list implementations System.out.println(i + “.” + choice);
à using array to track list or using links/pointers i++ }}
To create lists private LinkedList<Double> coefficients;
à List<String> eating = new LinkedList<String>(); à size of list is coefficients.size()
To ass values to list, use appropriate method Constructor
à eating.add(“chew”); or eating.add(“swallow”); à public Polynomial() {
Maps a.k.a hash tables or dictionaries (in main method) this.coefficients = new LinkedList<>(); }
Map<String, String> mapBearNameToLocation = new adding example
HashMap<String, String>(); à public void addTerm(double coeff) {
mapBearNameToLocation.put(“Winnie”, “Hundred Acre Wood”); coefficients.add(coeff); }
mapBearNameToLocation.put(“Paddington”, “Peru”); public static Map<String, Integer> countWords(List<String>
mapBearNameToLocation.put(“Paddington”, “London”); words) {}
à map.size() returns 2 à key is a word (String), value is amt word appears in list
à map.get(“Winnie”) returns Hundred Acre Wood (Integer)
à map.get(“Paddington”) returns London Create a map: HashMap<String, Integer> wordCount =
à map.get(“Hundred Acre Wood”) returns null newHashMap<>();
à map.get(“Peru”) returns null If I get something from a map that isn’t in it, return null
à map.get(“London”) returns null à if(wordCount.get(word) == null) { //not in map first time seen
Key-value pair (can have diff types) wordCount.put(word, 1); }
à all values are associated with a key, can’t have more than one else { //already in map
value associated with a key (no duplicate keys) int count = word.Count.get(word); //pull out amt times
à put and get values from map using key seen wordCount.put(word, count + 1); } //+1 to amt and
Always use == for primitive types (reference back to somewhere put it back in map
else on computer) there is no order to maps (use for each loop to iterate through
à only true if objects on left are same as objects on the right map)
Use .equals() for comparing objects à for(String key : words.keySet()) {
à examines instance variables of objects being compared System.out.println(key + “:” + words.get(key)); }