Skip to content

Instantly share code, notes, and snippets.

@GavHern
Last active April 26, 2022 22:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GavHern/f1bec5a7118ce69cc76b317000260303 to your computer and use it in GitHub Desktop.
Save GavHern/f1bec5a7118ce69cc76b317000260303 to your computer and use it in GitHub Desktop.
Notes for AP Computer Science A

Resources:

Notes

  • Comments
    • Single Line
      • Begins with //
      • Ends at the end of that line
    • Mutliline
      • Begings with /*
      • Closed with */
      • Sometimes has preceeding asterisks on each line. These are documentation comments. /** */
    • Javadoc (Partially tested)
      • Javadoc is a tool for creating documentation using information given with multiline comments before a variable, method, class, or interface.
      • Javadoc comments typically follow the /** */ format, though it is not required.
      • Some Javadoc tags include:
        • @param describes a parameter/ argument
        • @return describes a return value
        • Other tags exist but are not within the AP Java Subset. Though, the College Board does state they are useful to know. A list of Javadoc tags can be found here.
      • Javadoc comments are seperate from Java's typing system and only serve to describe how elements of the code function for automatically generated documentation
      • An example of a Javadoc comment:
        /**
         * Adds two values.
         *
         * @param operand1 - first numeric value for the ADD operation
         * @param operand2 -  second numeric value for same purposes
         * @return sum of two operands
         */
         public int add(int operand1, int operand2) {...}
      (Source: StackOverflow)
  • Primative Types (⭐ = In the AP Java Subset)
    • int: A 32 bit signed integer value (-2147483648 to 2147483647)
    • double: A 64 bit signed floating point number. (-1.8 × 10308 to 1.8 × 10308-1)
    • boolean: A true or false value.
    • char: An unsigned 16 bit integer, usually used to represent a single charactar. Assigned with a character between single quotes: char myChar = 'H';. (0 to 65535)
    • byte: An 8 bit signed integer. (-128 to 127)
    • short: A 16 bit signed integer. (-32768 to 32767)
    • long: A 64 bit signed integer. (263)
    • float: A 32 bit signed floating point number. (-3.4 × 1038 to 3.4 × 1038-1)
  • Operators
    • Arithmetic
      • + Addition (ex. 3 + 4)
      • - Subtraction (ex. 6 - 2)
      • * Multiplication (ex. 3 * 2)
      • / Division (ex. 8 / 4)
      • % Modulus (ex. 8 % 2)
    • Increment/Decrement
      • ++ Increment value by 1 and assign
      • -- Decrement value by 1 and assign
    • Assignment
      • = Assigns a value. a = 10;
      • Assignment operators may also be preceeded by any arithmetic operator to perform that operation to the existing value and reassign it
        • ex. a += 10 is the same as writing a = a + 10, which takes the current value of a and adds 10 to it.
    • Relational
      • == Returns true if the left and right values are equal to each other.
      • != Returns true ii the left and right values are not equal to each other.
      • < Returns true if the left value is less than the right value.
      • <= Returns true if the left value is less than or equal to the right value.
      • > Returns true if the left value is greater than the right value.
      • >= Returns true if the left value is greater than or equal to the right value.
    • Logical
      • ! Returns the oposite of a boolean value. ex. if a is true, then !a would be false and vice versa.
      • && Returns true if the left and the right values are both true.
      • || Returns true if the left or the right values are both true.
    • Numeric Casts
      • Placing a numerical type between parenthesis before another numerical value will cast it to that type
        • ex. if myInt were 10, (double) myInt would return the same value as a double (10.0).
      • Can be used with any numerical type, though only (int) and (double) are in the AP Java Subset.
    • String concatenation
      • + Combines two strings. ex. "a" + "b" would return "ab".
  • Object Comparison
    • Object Identity vs. Object Equality
      • Checking for equality using object identity is when you use the == or != operators. This checks for the equality of the references stored in the variable. A reference states where in memory an object's data is held and doesn't represent the data within that object. (Before checking if the references are the same, JVM will first check if they are of the same type)
      • Checking for equality using object equality is when you use the equals method. This is a method on an object that tells you if the data within an object equals the data within another. This is used when you want to test if two different objects contain the same data, even if thet are stored in different memory allocations and are associated with different reference values.
    • String compareTo
      • compareTo is a method on a String instance that represents how lexicographically similar that string is to another. This method uses the unicode values of each letter to determine how similar they are. It returns 0 if they are identical, a positive value if the initial string is longer, and a negative value of the argument string is longer. The value returned represents the number of characters off one of the strings is.
  • Escape Sequences (⭐ = In the AP Java Subset)
    • \" Represents a quotation mark in a string (since a normal quotation mark will terminate the string)
    • \\ Represents a backslash in a string (since the backslash is reserved for escape sequences)
    • \n Represents a new line in a string
    • \t Represents a tab character in a string
  • Input / Output
    • System.out.print Used to print text to the output.
    • System.out.println Used to print text to the output, followed by a new line (\n).
  • Exceptions
    • Types of exceptions (all extend the RuntimeException class)
      • Arithmetic Exceptions occur when there is an error evauluating a mathematical statement. A common example of this is a divide by 0 error
      • NullPointerExceptions occur when you try to reference a pointer that does not point to an object. This can happen if you try to trigger a method on a null reference or try to access a value in a null reference.
      • IndexOutOfBoundsExceptions occur when you try to access an item in a list-style object with an index that is not within the bounds of the object. An example of this is if you had char[] letters = ['a', 'b', 'c']; and you tried to access letters[3]. Since there is no item at index 3 (lists start at 0 so only 0, 1, and 2 are occupied), Java will throw an IndexOutOfBoundsException.
      • ArrayIndexOutOfBoundsExceptions are specific to arrays. You can also index other list-style objects such as Strings and Vectors, which have their own out of bounds exceptions.
      • IllegalArgumentExceptions occur when an argument passed to a method is illegal, meaning it isn't of the correct type, doesn't exist, etc.
    • Catching Errors
      • A try/catch/finally block can be used to catch errors
      try {
        // Code that is attempted to run
      } catch(Exception e) {
        // Code that runs only if the try block throws a runtime error. Arugment containing the error object is passed.
      } finally {
        // Code that always runs after either the try or the catch block is finished
      }
      • The catch or finally block can be ommitted, but at least one of them must be present.
  • Arrays
    • Arrays are lists of a fixed length that can store values of the same type. To declare an array that can hold 4 integers, you can write int[] myArray = new int[4];
    • Accessing values in arrays is done by using square brackets. For example, to get the 2nd item in the array, you can write myArray[1]. Note that arrays begin at 0, meaning that an index of 1 refers to the second item in the array.
    • A 2 dimensional array is essentially an array of arrays, forming a table-like data structure. 2d arrays are defined by writing int[][] my2dArray = new int[10][20];. This creates a 2d array that is 10 elements by 20 elements. The data can be accessed by writing my2dArray[2][6], which gets the item in the 6th position of the 2nd array. Additional dimensions can be added up to 255, but are very unlikely to be needed.
    • If the values of an area are known when the array is being defined, you can use an initializer list to define the values of an array. int[] myArray = {1, 2, 3, 4};. You can also do this for 2d arrays by making an array of initializer lists. {{2, 4}, {6, 8}, {10, 12}}
    • Row-Major Order is a way to traverse a 2d array. If the 2d array is defined as new type[y][x], Row-Major order refers to going through all of the x values before moving down to the next y value. A diagram of this can be found here.
    • ArrayLists
      • ArrayLists are arrays that are dynamic in length
      • In older versions of Java, ArrayLists were called Lists. In the AP test, they are referred to as ArrayLists.
      • Found in the java.util.ArrayList package. (or java.util.List in older versions)
      • Defined with ArrayList<DataType> myArrayList = new ArrayList<DataType>(n);, where n is an optional parameter stating how long the ArrayList should begin as. ArrayLists do not have to be typed (<DataType can be ommitted), but it is strongly recommended for predictability reasons.
      • Can store a list of references, but cannot store primative values such as ints, chars, booleans, doubles, etc.. To store primative values, wrapper classes such as Integer, Character, Boolean, Double, etc..
      • You may write any value to an untyped ArrayList (may receive compiler warnings for using them), though you will get an error if you attempt to assign a value of the wrong type to a typed ArrayList.
      • When looping through an ArrayList with an enhanced for-loop, the value passed into the loop should not be modified as it is a duplicate of the actual value rather than a reference to it.
      • Array List Methods
        • ArrayLists have a getter function .size() to get the number of elements in the ArrayList.
        • ArrayLists can be appended to with the .add(a) method, which adds an element (a) to the end of the list. To add at a specific index, the index can be passed as an integer value as the first parameter with the value being the second (.add(2, a)).
        • ArrayLists can be removed from with the .remove(i) method, where i is the index of the item to be removed. This method will return the item that got removed.
        • ArrayLists have a method called .set(i, a), which replaces an item at an index (i) with another value (a). This method returns the old value of the item that was replaced.
        • ArrayList have a method called .get(i), which returns the value of an item at a given index (i).
  • Control Statements
    • An if statment is used to check if a boolean expression is true, and runs code if it is. Additionally, an else statement can be added after which will run if the boolean is false.
    • A while loop is used to repeatedly run code until a boolean expression becomes false. The expression is reevaluated each time the program restarts the loop
    • A for loop is a loop that runs a specified number of times. Nothing is reevaluated each loop as the number of times it must loop is determined when the program enters the loop
    • An enhanced for loop, otherwise known as a foreach, will run once for every item in an array; passing the item as an arguemnt into the code segment
        int[] letters = {'a', 'b', 'c', 'd', 'e'};
      
        for (int letter: letters) {
          System.out.println(letter); // Outputs the current letter
        }
    • The return keyword can be used to exit a loop, but is mostly used for a method to return a value when called. Return statements do not need to have a value, and usually don't when used to terminate a loop.
  • Variables
    • Parameter variables are variables passed to a method as an argument. These variables are scoped to that method and cannot be accessed outside of it.
    • Local variables are variables defined within a method. These variables are scoped to that method and cannot be accessed outside of it.
    • private instance variables are variables that are specific to an instance of a class and cannot be accessed outside of it. They are called instance variables because, unlike static variables, they are specific to the instance of a class rather than the class itself.
    • public instance variables can be accessed anywhere in the program.
    • final variables are immutable (constant) variables and cannot be changed after they're declared.
    • static (class) variables are values that are identical for every instance of a class. If a new class is instantiated, it will reference the same value as the existing instances for any static variables.
  • Methods
    • Method Visibility
      • Public methods are methods that can be accessed outside of a class and run on a class. Calling a public method on an object looks like this: new MyClass().publicMethod().
      • Private methods are methods that cannot be accessed outside of the class defintion. Private methods are used if the method does not need to be accessed from outside of the class definition and are only important for code within the definition.
      • Static methods belong to the class itself and run exactly the same regardless of which instance of the class it is run on. Static methods do not have access to instance variables and can only access variables declared with the static keyword; these variables belong to the class itself rather than an instance of the class.
      • Non-static methods (methods without the static keyword) belong to each instance of a class and have access to instance variables on the class instance.
    • Method signatures
      • The method signature is the format for a method when being defined.
      • Method signatures consist of ...
        • Method visibility (public, private, etc.)
        • Return type (void, int, boolean, String, etc)
        • Method name
        • Parameter list (always between parethnthesis. If the method does not require any parameters, the parenthesis must still be there, just without anything in it)
      • Example: private int myMethod(String param1, boolean param2), where private is the visibility, int is the return type, myMethod is the name, and (String param1, boolean param2) are the parameters
    • Overloading & Overriding
      • Method overloading is when there are several method definitions with the same method name, but different parameters. Java will pick the method with the best fitting parameter list when the method is called (i.e. has the same number of parameters and each parameter is of the correct type).
      • Method overriding is when a subclass redefines a method that is already defined in the superclass. All methods are inherited by default, but they can be overridden by defining a method with the same method signature in the subclass.
    • Parameter Passing
      • Parameters, or arguments, are values passed into a method when it is called.
      • Parameter values are scoped to the method definition.
      • myMethod(10) will pass the value of 10 into the method, which is defined with myMethod(int number) { ... }. In the method signature, the parameter is named number, so it will be defined as the varible number in the definition.
  • Constructors
    • A constructor is a method that runs when a class is instantiated. Anything can be put in the method, but it is usually used to accept arguments and set them to local variables.
    class MyClass {
      public MyClass() {
        // Constructor code goes here
      }
    }
    • Classes can extend other classes and inherit all of its values and methods. This is a subclass (child) which extends a superclass (parent).
    • super is an object that refers to the superclass of a class. If the superclass had a method called myMethod(), running super.myMethod() in the subclass will run the method that is defined in the superclass.
    • super() as a method refers to the constructor of a superclass. Running super() without arguments will simply run the constructor of the superclass. You do not need to call the super method yourself as Java will run it automatically.
    • super(args) is when you pass arguments to the super method. Java runs the super() method without any arguments by default, but the super method can be manually called with arguments which will override Java's default call. This is helpful if you wish to pass arguments to the superclass' constructor.
  • Classes
    • The new keyword instantiates a class. (ex. new MyClass() returns a new instance of MyClass)
    • Accessor methods (or getters) are methods that return a property of an object. These can be more helpful than public data members since you can process the data before it is returned. These typically start with "get" (i.e. getScore()).
    • Mutator methods (or modifier methods/ setters) are methods that overwrite or update a property on an object. These can be more helpful than mutable public data members since you can be more specific about how the data is being changed or run other code whenever the value gets changed. These typically start with "set" or "update" (i.e. updateScore()).
    • Subclasses are classes that are derived/ extended from other classes. To create a subclass, use class MySubclass extends MySuperclass. The superclass refers to the class that the subclass inherited.
    • Abstrations with classes
      • Abstract classes are classes that cannot be instantiated.
      • Abstract classes exist to be extended upon with sublcasses.
      • To define an abstract class, use the abstract keyword. (ex. abstract class MyClass { ... }
      • By default, classes are non-abstract, meaning they behave normally and can both be instantiated and extended. Abstract classes exist to hide generic versions of classes that will never be instantiated on their own.
      • An example of using abstract classes would be a zoo program. The zoo has an abstract class called Animal, but the zoo has no generic "animals" in it. Instead, the zoo has Gorillas, Tigers, Penguins, etc. which all inherit all of the functionality that an Animal has, but with their own added functions specific to their species. Creating the abstract Animal class allows the programmer to never have a normal Animal be created while not having to reimplement the shared functionality that every animal has each time a new animal class is made.
  • Interfaces
    • Interfaces are similar to abstract classes, but are not able to be extended upon. Interfaces do not require the use of the abstract keyword.
    • Interfaces act as blueprints for classes and define what methods must be included on classes created using the interface. Methods on the interface cannot have any implementation but are intended to be implemented in the class definition.
    • Methods on interfaces will not be inherited as they have no implementation yet, though variables will be inherited.
    • Interfaces are tools for organizing your classes and making sure they include all the functionality they need. The compiler will not compile the code unless the interface rules are met.
    interface GameInterface {
      // Methods don't have any `{ ... }`. The compiler knows they are methods since they have parenthesis.
      public void startGame();
      public int getScore();
    
      public int score = 0; // Classes will inherit the variable `score` with a default of 0
    }
    
    class Game implements GameInterface {
      // Code in here must implement `startGame` and `getScore`
    
      public void startGame() { ... }
      public int getScore() { ... }
    
      // Any other code goes here
    }
  • Inheritance
    • Inheritance is when a class inherits all of the properties of another class.
    • For a class to inherit other, you use the extends keyword. For example, class MySubclass extends MySuperclass. The subclass refers to the new class being made while the superclass refers to the class it is being made from.
    • Classes can also inherit variable values from interfaces, though they do not inherit method implementations since interfaces cannot implement methods. Rather, classes must implement every method on an interface itself.
    • The inheritance heirarchy refers to how classes get more and more specific as they extend other classes. For example, A Car class would be very generic, but a HondaCar class would be more specific, and a HondaHatchback would be even more specific. These heiarchies can keep going as long as you'd like, but the general idea is that you take a very generic class such as Car and end up with something more specific like HondaHatchback.
  • Packages
    • Packages are premade pieces of code that are usually made by other developers.
    • People use packages to avoid reimplementing solutions to problems that have already been solved.
    • To bring a package into a program, use the import keyword at the very start of the file.
    • Some packages that are used in the AP Java Subset include ...
      • ArrayLists (import java.util.ArrayList)
      • Math (import java.lang.Math)
    • Asterisks (*) can be used to import every method in a package. For instance, import static java.lang.Math.* will import all of the Math class methods directly into the code. This means you can write something like abs(num) rather than Math.abs(num). The static keyword means that we are importing static methods on the package rather than a whole package itself.
    • While packages must be imported to be used in Java, many claim the AP test will never require you to write your import statements and it is assumed that the needed packages are already imported.
  • Object-Oriented Programming Concepts
    • "is-a" & "has-a" relationships
      • An "is-a" relationship is used with inheritance. For example, a Jeep is a car.
      • A "has-a" relationship is used when an instance variable of a class contains an instance of another class. For example, a Car has a steering wheel.
      • It wouldn't make sense to say that a Jeep has a car or that a car is a steering wheel. Understanding the relation that classes have with one another is important when trying to implement them and make them work together.
    • null
      • Null is a term that means the absence of value.
      • The null literal in Java is used when there is no value for an object.
      • Variables that hold primative values cannot be null.
      • Using a variable that holds a null value can lead to a NullPointerException since the variable does not point to an actual instance of the class.
    • this
      • The this keyword refers to the object it is used inside of.
      • The this keyword is often used in constructors to assign arguments to data members on the object
      class MyClass {
        public int value1;
        public int value2;
      
        // Constructor method
        public MyClass(int value1, int value2) {
          // The `this` keyword must be used since `value1` and `value2` now refer to the private variables in the argument. Using `this` will write it to the variables on the MyClass object that is being instantated.
          this.value1 = value1;
          this.value2 = value2;
        }
      }
    • super.method()
      • The super keyword refers to the superclass that a class was extended from.
      • If MySubclass extends MySuperclass, calling super.method() from the subclass is the same as calling method() from the superclass.
  • Java Standard Library
    • Object class
      • The Object class is the class that every class extends by default.
      • The Object class contains methods that every class has, such as .equals() or .toString(). Every object has these methods defined because every class inherits them.
    • Wrapper Classes & Autoboxing
      • Java is considered an Object Oriented Programming language, meaning that everything is an object. The one exception to this are the primative data types such as int, double, boolean, etc.
      • You can declare any primative type as an object by using it's wrapper class.
      • Wrapper classes include: Boolean, Byte, Character, Double, Float, Integer, Long, & Short. All of them are just their primative names with the first letter being uppercase, apart from Integer and Character which are int and char spelled out.
      • These are useful because primatives use pass by value, meaning they hold the actual value of the variable. Objects use pass by reference, meaning that the variable holds a reference to where you can find the value somewhere else in memory. Using a wrapper class allows you to use references with primative types. The benefit of this could be that you only have to modify the value once and it will be updated everywhere it is referenced because they all point to the same area in memory.
      • You may also see wrapper classes used as data types in places such as ArrayLists.
      • To create a new instance of a wrapper class, use Integer myValue = new Integer(20);. In this example, the class used is an Integer and it holds the value of 20. The class is constructed using the primative value as an argument, which can either be a literal or a variable that holds the primative value. Putting a primative value into a wrapper class is called autoboxing.
      • To get the primative value back out, use myValue.intValue(), which returns the value as an integer. This works similarly for other wrapper classes, with the only difference being the name of the method. The method name is just the primative name, followed by "Value" (i.e. .doubleValue(), .booleanValue(), .charValue(), etc.). Taking the primative value out of a wrapper class is called unboxing.
    • Strings
      • Strings are Objects that implement arrays of characters.
      • Strings act as containers for text.
      • Strings are immutable; trying to mutate a string causes a new string to be created and the variable to now reference that object.
    • Math package
      • The Math package is a package that supports various math-related methods.
      • Imported using import java.lang.Math;
      • There are a lot of methods on the Math object, but only 5 are included in the Java Quick Reference:
        • int abs(int a): returns the absolute value of an integer
        • double abs(double a): returns the absolute value of a double
        • double pow(double a, double b): returns a to the power of b
        • double sqrt(double a): returns the square root of a
        • double random(): returns a random double value from 0.0 (inclusive) to 1.0 (exclusive)
    • List<E> and ArrayList<E>
      • Lists are an interface for storing lists of items, excluding Arrays.
      • ArrayLists are like dynamic-length arrays. For more info, see ArrayLists under the Arrays section.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment