├── ArrayLists.md ├── Arrays.md ├── Base Conversion.md ├── Boolean Operators.md ├── Break.md ├── Class Casting.md ├── CompareTo EqualsTo.md ├── Continue.md ├── DeMorgan Law.md ├── Elevens Lab QA.md ├── Exceptions.md ├── File IO.md ├── For Loops.md ├── If Statements.md ├── Importing.md ├── List Interface.md ├── Memory Allocation.md ├── Methods.md ├── Object-Oriented Programming.md ├── Operators and Precedence.md ├── Primitive Data Types.md ├── README.md ├── Recursion.md ├── Scanner Class.md ├── Searching Algorithms.md ├── Sorting Algorithms.md ├── Static Variables and Methods.md ├── Switch Statements.md ├── Variable Casting.md ├── Variable Declaration.md ├── Variable Scope.md ├── While Loops.md └── Wrapper Classes.md /ArrayLists.md: -------------------------------------------------------------------------------- 1 | # **ArrayLists** 2 | - can only hold objects 3 | - stores a list of elements and provides methods to find, insert, and remove an element 4 | - an ArrayList object contains an array of object references plus many methods for managing that array 5 | 6 | ## Some ArrayLists Methods 7 | - .get() 8 | - .add(object o) 9 | - .size() 10 | - .remove() 11 | + returns the removed object 12 | - set(int i, object o) 13 | 14 | ## Example Code 15 | ``` javascript 16 | ArrayList colorList = new ArrayList (); 17 | colorList.add("green"); 18 | colorList.add("white"); 19 | colorList.add("yellow"); 20 | 21 | //returns the size or length of the ArrayList colorList 22 | colorList.size(); 23 | 24 | //makes index 0 the String "red" 25 | colorList.set(0, "red"); 26 | 27 | //removes the object at index 2 of colorList, 28 | //but returns the object that was at index 2 29 | colorList.remove(2); 30 | 31 | //gets the object at index 1 32 | colorList.get(1); 33 | 34 | //adds the String "blue" at index 2 of colorList 35 | colorList.add(2, "blue"); 36 | ``` 37 | -------------------------------------------------------------------------------- /Arrays.md: -------------------------------------------------------------------------------- 1 | # Arrays 2 | 3 | ## Overview 4 | * Arrays are the most basic data structure in Java 5 | * Arrays are linear - they store elements in a side-by-side format 6 | 7 | Consider you have a set of numbers like `1, 4, 6, 2, 9`. Below is a visual representation of how an array would store this set: 8 | 9 | ```java 10 | _____________________ 11 | | | | | | | 12 | | 1 | 4 | 6 | 2 | 9 | 13 | |___|___|___|___|___| 14 | ``` 15 | 16 | * Arrays can hold both primitive data types and objects 17 | * `int` and `double` arrays will have `0` as their default value 18 | * `Object` arrays will have `null` as their default value - this means trying to access a value of an `Object` array without declaring it will throw a `NullPointerException` 19 | * The length of an array can be retrieved with the `length` attribute 20 | * Ways to declare an array 21 | * First way: `[] = new [];` 22 | * Second way: `[] = {, , };` 23 | 24 | ## Examples 25 | 26 | ### `int` array 27 | 28 | ```java 29 | int[] array = new int[10]; 30 | 31 | for (int i = 0; i < array.length; i++) { 32 | array[i] = i; 33 | } 34 | ``` 35 | 36 | ### `String` array 37 | 38 | ```java 39 | String target = “Mike”; 40 | 41 | String[] array = {“Jack”, “Jill”, “Bob”, “Henry”, “Mike”, “James”}; 42 | for (String s : array) { 43 | if (s.equals(target)) { 44 | System.out.println(target + “ was found!”); 45 | break; 46 | } 47 | } 48 | ``` 49 | -------------------------------------------------------------------------------- /Base Conversion.md: -------------------------------------------------------------------------------- 1 | # Base Conversion 2 | 3 | ## Binary to Decimal 4 | 5 | Problem: Convert `101011101` to a decimal number (`base 10`). 6 | 7 | **Step 1:** Align the digits of a binary number with the powers of `2`. 8 | 9 | | 1 | 0 | 1 | 0 | 1 | 1 | 1 | 0 | 1 | 10 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | 11 | | 2^8 | 2^7 | 2^6 | 2^5 | 2^4 | 2^3 | 2^2 | 2^1 | 2^0 | 12 | 13 | **Step 2:** Calculate the powers of `2` on the bottom table. 14 | 15 | | 1 | 0 | 1 | 0 | 1| 1 | 1 | 0 | 1 | 16 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | 17 | | 256 | 128 | 64 | 32 | 16 | 8 | 4 | 2 | 1 | 18 | 19 | **Step 3:** If there is a `1` in the table, highlight the corresponding power of `2`. If there is a `0` in the table, ignore the corresponding power of `2`. 20 | 21 | | 1 | 0 | 1 | 0 | 1| 1 | 1 | 0 | 1 | 22 | | --- | --- | --- | --- | --- | --- | --- | --- | --- | 23 | | **1** | 0 | **1** | 0 | **1** | **1** | **1** | 0 | **1** | 24 | | **256** | 128 | **64** | 32 | **16** | **8** | **4** | 2 | **1** | 25 | 26 | **Step 4:** Add up all the powers of `2` that are bolded on the bottom. 27 | 28 | ``` 29 | 256 + 64 + 16 + 8 + 4 + 1 = 349 30 | ``` 31 | 32 | ## Hexadecimal to Decimal 33 | 34 | Reference: Before doing any hexadecimal to decimal conversions, make sure you know what different letters stand for. Here is a table for hexadecimal reference: 35 | 36 | | 10 | 11 | 12 | 13 | 14 | 15 | 37 | | --- | --- | --- | --- | --- | --- | 38 | | A | B | C | D | E | F | 39 | 40 | Problem: Convert `7DE` to a decimal number (`base 10`). 41 | 42 | **Step 1:** Align the digits of a binary number with the powers of `16`. 43 | 44 | | 7 | D | E | 45 | | --- | --- | --- | 46 | | 16^2 | 16^1 | 16^0 | 47 | 48 | **Step 2:** Calculate the powers of `16` on the bottom table and change the alphabet letters in the top table to numerical values by referencing the hexadecimal table above. 49 | 50 | | 7 | 13 | 14 | 51 | | --- | --- | --- | 52 | | 256 | 16 | 1 | 53 | 54 | **Step 3:** Multiply the number on the top table with the number on the bottom table and add the values to find the decimal number. 55 | 56 | ``` 57 | 7(256) + 13(16) + 14(1) = 2014 58 | ``` 59 | 60 | ## Decimal to Binary 61 | 62 | Problem: Convert `143` into a binary number (`base 2`). 63 | 64 | Overall Strategy: 65 | * Divide the number by `2`, and save the remainder (`1` or `0`) in a list 66 | * Divide the quotient from above by `2`, and save the remainder (`1` or `0`) in a list 67 | * Repeat above until 1) the quotient is `0` and 2) the final remainder is either `1` or `0` 68 | * Read the list backwards, and that will be your decimal number 69 | 70 | Example: 71 | 72 | ``` 73 | 1. 143 % 2 = 1, List = [1] 74 | 2. 71 % 2 = 1, List = [1, 1] 75 | 3. 35 % 2 = 1, List = [1, 1, 1] 76 | 4. 17 % 2 = 1, List = [1, 1, 1, 1] 77 | 5. 8 % 2 = 0, List = [1, 1, 1, 1, 0] 78 | 6. 4 % 2 = 0, List = [1, 1, 1, 1, 0, 0] 79 | 7. 2 % 2 = 0, List = [1, 1, 1, 1, 0, 0, 0] 80 | 8. 1 % 2 = 1, List = [1, 1, 1, 1, 0, 0, 0, 1] 81 | ``` 82 | 83 | Once you read the list backwards, you will reach the final answer of `10001111`. 84 | 85 | ## Decimal to Hexadecimal 86 | 87 | Problem: Convert `143` into a hexadecimal number (`base 16`). 88 | 89 | Overall Strategy: 90 | * Divide the number by `16`, and save the remainder (less than `16`) in a list 91 | * Divide the quotient from above by `16`, and save the remainder (less than `16`) in a list 92 | * Repeat above until 1) the quotient is `0` and 2) the final remainder is less than `16` 93 | * Read the list backwards, and that will be your hexadecimal number 94 | 95 | Example: 96 | 97 | ``` 98 | 1. 143 % 16 = 15, List = [15] 99 | 2. 8 % 16 = 15, List = [15, 8] 100 | ``` 101 | 102 | Once you read the list backwards, you will reach the final answer of `8F`. In case you didn’t catch it, the `15` in the list is represented by the alphabetical character `F`, as this is the standard hexadecimal conversion. 103 | 104 | -------------------------------------------------------------------------------- /Boolean Operators.md: -------------------------------------------------------------------------------- 1 | # Boolean operators 2 | 3 | ## Overview 4 | 5 | * `boolean` operators are very important, as they are used in various control structures and iteration loops 6 | * In order to make `boolean` operators more specific, symbols such as **and** (`&&`), **or** (`||`), and **not** (`!`) are used 7 | 8 | ## `and` keyword 9 | 10 | * `and` is used when two elements must evaluate to `true` in order for the overall `boolean` expression to be `true` 11 | * The general formula is: ` && ` 12 | 13 | ```java 14 | if (2 + 2 == 4 && 1 + 1 == 2) { 15 | System.out.println(“Both boolean operations are true”); 16 | } 17 | ``` 18 | 19 | ## `or` keyword 20 | 21 | * `or` is used when only one of the two elements must evaluate to `true` in order for the overall `boolean` expression to be `true` 22 | * The general formula is: ` || ` 23 | 24 | ```java 25 | int count = 10; 26 | 27 | if (count == 10 || false) { 28 | System.out.println(“One of the boolean expressions is true”); 29 | } 30 | ``` 31 | 32 | ## `not` keyword 33 | 34 | * `not` is used to negate an expression, or to turn it into its opposite 35 | * For example, `!true` would evaluate to `false`, and `!false` would evaluate to `true` 36 | 37 | ```java 38 | if (!(10 + 10 == 0) && !(false)) { 39 | System.out.println(“The boolean expression above evaluates to true”); 40 | } 41 | ``` -------------------------------------------------------------------------------- /Break.md: -------------------------------------------------------------------------------- 1 | # Break 2 | 3 | ## Overview 4 | 5 | * As the name suggests, the `break` keyword is used to *break* out of a conditional statement or also a loop 6 | * Generally, `break` keywords are used when the body of a conditional statement or loop is no longer needed, such as when something is found or a task is completed 7 | 8 | ## Example 9 | 10 | ## `break` in an `if` statement 11 | 12 | ```java 13 | if (2 + 2 == 4) { 14 | break; 15 | System.out.println(“Hello”); 16 | System.out.println(“Hello world”); 17 | } 18 | 19 | ``` 20 | 21 | Note: The two `System.out.println` statements are not evaluated because the `break` keyword exits the entirety of the `if` statement. 22 | 23 | ## `break` in a `for` loop 24 | ```java 25 | int target = 2; 26 | int[] numbers = {3, 7, 2, 5, 10, 12, 4, 6}; 27 | 28 | for (int i = 0; i < numbers.length; i++) { 29 | if (numbers[i] == target) { 30 | System.out.println(“Found the number at index “ + i); 31 | break; 32 | } 33 | } 34 | ``` 35 | 36 | Note: The `for` loop exits at index `3` because the target of `2` is found, and the `break` keyword forces Java to terminate the loop. -------------------------------------------------------------------------------- /Class Casting.md: -------------------------------------------------------------------------------- 1 | # Class Casting 2 | 3 | ## Overview 4 | * Class casting is to refer to the methods or variables of a sub class in reference to its parent class 5 | * If a child class inherits from a parent class, but the child class has additional methods NOT included in the parent class, then class casting must be used when initializing a variable with polymorphic behavior 6 | * The general formula for casting is: `((class name) variable name)` 7 | 8 | ## Example 9 | 10 | Because the `Student` class has methods that the `Person` class does not have, when declaring a `Student` variable with polymorphic behavior, the variable must use class casting. 11 | 12 | ```java 13 | public class Person { 14 | public String name = "Person"; 15 | public boolean female = true; 16 | 17 | public String getName() { 18 | return name; 19 | } 20 | 21 | public boolean isFemale() { 22 | return female; 23 | } 24 | } 25 | 26 | public class Student extends Person { 27 | public int[] grades = {90, 92, 96, 95}; 28 | 29 | public int[] getGrades() { 30 | return grades; 31 | } 32 | } 33 | 34 | public class Driver { 35 | public static void main(String[] args) { 36 | 37 | // Need to use class casting because the Person 38 | // class does not have the getGrades method 39 | Person p = new Student(); 40 | ((Student) p).getGrades(); 41 | 42 | // Don't need to use class casting because the 43 | // reference is to Student, not Person 44 | Student s = new Student(); 45 | s.getGrades(); 46 | } 47 | } 48 | ``` 49 | -------------------------------------------------------------------------------- /CompareTo EqualsTo.md: -------------------------------------------------------------------------------- 1 | # **CompareTo Method** 2 | - returns three different values: negative, positive, and equal values 3 | - To determine whether something is greater than another, a left to right approach is useful 4 | - one-line return statements are useful for compareTo() methods, but one must ensure that the correct primitive data type is being returned. 5 | 6 | ## Example Code 7 | ``` javascript 8 | public int compareTo (int i){ 9 | if ( i < [other number]){ 10 | return -1; 11 | } 12 | if ( i > [other number]){ 13 | return 1; 14 | } 15 | if ( i == [other number]){ 16 | return 0; 17 | } 18 | } 19 | 20 | int x = 2; 21 | int y = 7; 22 | 23 | if (x.compareTo(y) > 0){ 24 | System.out.println("x is greater than y"); 25 | } 26 | if (x.compareTo(y) < 0){ 27 | System.out.println("x is less than y"); 28 | } 29 | if (x.compareTo(y) == 0){ 30 | System.out.println("x is equal to y"); 31 | } 32 | ``` 33 | 34 | # **EqualsTo Method** 35 | - compares the contents of an object to check if they are equal to each other 36 | - The method itself is usually a function in the class it is defined in. 37 | 38 | ## Example Code 39 | ``` javascript 40 | public boolean equals (int i){ 41 | return ((test1+test2+test3) == (s.test1+s.test2+s.test3)) 42 | } 43 | ``` 44 | 45 | -------------------------------------------------------------------------------- /Continue.md: -------------------------------------------------------------------------------- 1 | # Continue 2 | 3 | ## Overview 4 | 5 | * The `continue` keyword is used for skipping over something - this is mostly used in a `for` or `while` loop where you iterate over a set or sets of elements 6 | 7 | ## Example 8 | 9 | ```java 10 | String test = “The fox jumped over the cat”; 11 | 12 | for (int i = 0; i < test.length(); i++) { 13 | if (test.charAt(i).equals(“e”) { 14 | continue; 15 | } else { 16 | System.out.println(test.charAt(i)); 17 | } 18 | } 19 | ``` 20 | 21 | Note: This snippet of code will print out all of the characters in the `test` variable except for the `e` characters. The `continue` keyword is used here to skip over these characters. -------------------------------------------------------------------------------- /DeMorgan Law.md: -------------------------------------------------------------------------------- 1 | #**Logic** 2 | + Logical operators are used in Boolean expressions that control the behavior of "if", "while", and "for" statements 3 | 4 | 5 | + `&&` (and) => both statements must be true to make the whole condition true 6 | + `||` (or) => both statements must be false to make the whole condition false, or at least one statement must be true to make the whole condition true 7 | + `!` (not) => switches true statements to false, and vice versa 8 | 9 | ## Relational Operators 10 | + `>` greater than 11 | + `>=` greater than or equal to 12 | + `<` less than 13 | + `<=` less than or equal to 14 | + `==` equal to 15 | + `!=` not equal to 16 | 17 | ## Example 18 | ```java 19 | int a = 28; int b = 47; int c = 84; 20 | if ((a<30) && (c>=85)){ 21 | System.out.println("Hello"); 22 | } 23 | else { 24 | if ((b>50) || (a>25)) { 25 | System.out.println("Goodbye"); 26 | } 27 | else { 28 | System.out.println("I can't make up my mind!"); 29 | } 30 | System.out.println("Here is a cool quilt with emoticons!"); 31 | } 32 | ``` 33 | 34 | # **DeMorgan's Laws (Boolean Logic)** 35 | - `! ( !A && B ) => ( A || !B )` 36 | - `! ( C || !D ) => ( !C && D )` 37 | - `! ( x > 5 ) => ( x <= 5 )` 38 | + basically opposites 39 | + can go backwaards and forwards 40 | 41 | ## Example Question 42 | + The expression `!((m < n) || (m != 5))` is equivalent to which of the following? 43 | + a. `(m < n) && (m != 5)` 44 | + b. `! (m < n) || ! (m != 5)` 45 | + c. `(m > n) && (m == 5)` 46 | + d. `(m >= n) && (m == 5)` 47 | + e. `(m <= n) || ! (m == 5)` 48 | -------------------------------------------------------------------------------- /Elevens Lab QA.md: -------------------------------------------------------------------------------- 1 | # Elevens Lab Questions and Answers 2 | 3 | ## Activity 2 Questions: 4 | 5 | 1) Explain in your own words the relationship between a deck and a card. 6 | 7 | ``` 8 | A deck is a collection of cards. 9 | ``` 10 | 11 | 2) Consider the deck initialized with the statements below. How many cards does the deck contain? 12 | 13 | ```java 14 | String[] ranks = {"jack", "queen", "king"}; 15 | String[] suits = {"blue", "red"}; 16 | int[] pointValues = {11, 12, 13}; 17 | Deck d = new Deck(ranks, suits, pointValues); 18 | ``` 19 | 20 | ``` 21 | The size of the constructed deck is the product of the lengths of ranks & suits, so the answer is 6. 22 | ``` 23 | 24 | 3) The game of Twenty-One is played with a deck of 52 cards. Ranks run from ace (highest) down to 2 (lowest). 25 | 26 | ``` 27 | Suits are spades, hearts, diamonds, and clubs as in many other games. 28 | A face card has point value 10; an ace has point value 11; point values for 2, …, 10 are 2, …, 10, respectively. 29 | ``` 30 | 31 | ```java 32 | Deck d = new Deck(ranks, suits, pointValues); 33 | initializes a deck for a Twenty-One game. 34 | String [ ] ranks = {“2”, “3”, “4”, “5”, “6”, “7”, “8”, “9”, “10”, “jack”, “queen”, “king”, “ace”}; 35 | String [ ] suits = {“spades”, “hearts”, “diamonds”, “clubs”}; 36 | int [ ] pointValues = {2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10, 11}; 37 | ``` 38 | 39 | 4) Does the order of elements of the ranks, suits, and pointValues arrays matter? 40 | 41 | ``` 42 | Elements of suits may appear in any order. Elements of ranks may be reordered, as ranks are not ordered in Elevens, as long as the pointValues elements are reordered in the same way. In card games where rank order is important, the sequence of elements in the ranks variable should be “in order.” 43 | ``` 44 | 45 | ## Activity 3 Questions: 46 | 47 | 1) Write a static method named flip that simulates a flip of a weighted coin by returning either "heads" or "tails" each time it is called. The coin is twice as likely to turn up heads as tails. Thus, flip should return "heads" about twice as often as it returns "tails." 48 | 49 | ```java 50 | public static String flip() { 51 | int r = (int) (Math.random() * 3); 52 | if (r < 2) { 53 | return “heads”; } 54 | else { 55 | return “tails”; } 56 | } 57 | ``` 58 | 59 | 60 | 2) Write a static method named arePermutations that, given two int arrays of the same length but with no duplicate elements, returns true if one array is a permutation of the other (i.e., the arrays differ only in how their contents are arranged).Otherwise, it should return false. 61 | 62 | Two method solution 63 | 64 | (using a helper method): 65 | ```java 66 | public static boolean arePermutations (int [ ] a, int [ ] b) { 67 | for (int aValue : a) { 68 | // Make sure that every element of a is somewhere in b. 69 | if ( ! contains ( b, aValue) { 70 | return false; 71 | } 72 | } 73 | return true; 74 | } 75 | 76 | private static boolean contains ( int [ ] b, int key ) { 77 | for ( int bValue : b) { 78 | if ( bValue == key ) { 79 | return true; 80 | } 81 | } 82 | return false; 83 | } 84 | ``` 85 | 86 | One method solution: 87 | ``` 88 | public static boolean arePermutations ( int [ ] a, int [ ] b ) { 89 | for ( int aValue : a) { 90 | // Make sure that every element of a is somewhere in b. 91 | boolean found = false; 92 | for ( int bValue : b) { 93 | if ( bValue == aValue ) { 94 | found = true; 95 | } 96 | } 97 | if ( ! found ) { 98 | return false; 99 | } 100 | } 101 | return true; 102 | } 103 | ``` 104 | 105 | 106 | 3) Suppose that the initial contents of the values array in Shuffler.java are {1, 2, 3, 4}. For what sequence of random integers would the efficient selection shuffle change values to contain {4, 3, 2, 1}? 107 | 108 | ``` 109 | The sequence 0, 1, 1. The first 0 switches 4 and 1, producing 4, 2, 3, 1; the first 1 switches 2 and 3, producing 4, 3, 2, 1; and the second 1 switches the 3 with itself. 110 | ``` 111 | 112 | ## Activity 6 Questions: 113 | 114 | 1) List all possible plays for the board 5♠ 4♥ 2♦ 6♣ A♠ J♥ K♦ 5♣ 2♠ 115 | 116 | ``` 117 | The 5♠ with the 6♣ make 11. The 5♣ with the 6♣ also make 11. 118 | ``` 119 | 120 | 2) If the deck is empty and the board has three cards left, must they be J, Q, and K? Why or why not? 121 | 122 | ``` 123 | The deck and the board satisfy three invariant relations before and after each play. 124 | - The number of face cards in the deck plus the number of face cards in the board is divisble by 3. 125 | - The number of jacks, the number of queens, and the number of kings are all equal to each other. 126 | - The number of nonface cards in the deck plus the number of nonface cards in the board is even. 127 | Thus, if the deck is empty and the board contains three cards, they must all be face cards. Because there have to be equal numbers of each face card, the three must be the remaining JQK. 128 | - If there are three face cards left, there must have been three previous plays of face cards. If the remaining cards are not JQK, then each face card rank wasn’t played the same number of times. This can’t happen. 129 | - If there are two or one face cards left, we get a contradiction using the same reasoning as in the first case. 130 | - If none of the three cards is a face card, there must have been a play of an odd number of nonface cards earlier in the game, as there are 40 nonface cards in all. This play would have been illegal. 131 | ``` 132 | 133 | 134 | 3) Does the game involve any strategy? That is, when more than one play is possible, does it matter which one is chosen? Briefly explain your answer. 135 | 136 | ``` 137 | The game doesn’t involve any strategy. When there is a choice between two or more different plays, it doesn’t matter in which order they are played. 138 | ``` 139 | 140 | 141 | ## Activity 7 Questions: 142 | 143 | 1) What items would be necessary if you were playing a game of Elevens at your desk (not on the computer)? List the private instance variables needed for the ElevensBoard class. 144 | 145 | ``` 146 | Deck of cards and a list of cards on the board. The ElevensBoard class would need Deck and Card [] instance variables. 147 | ``` 148 | 149 | 2) Write an algorithm that describes the actions necessary to play the Elevens game. 150 | Answers may vary. One possible answer is: 151 | ``` 152 | Shuffle the deck; 153 | Deal nine cards; 154 | While there is a possible move, 155 | If a pair exists that sums to 11, 156 | Remove the pair; 157 | Replace the two removed cards if possible; 158 | Else if a triplet that contains J, Q, K exists, 159 | Remove the triplet; 160 | Replace the three removed cards if possible; 161 | If there are no cards left on the board, you win, or else you lose. 162 | ``` 163 | 164 | 3) Now examine the partially implemented ElevensBoard.java file found in the Activity7 Starter Code directory. 165 | Does the ElevensBoard class contain all the state and behavior necessary to play the game? 166 | 167 | ``` 168 | In the ElevensBoard class, as written, there are no methods that actually select the cards to be removed, only ones to check 169 | already selected cards. 170 | ``` 171 | 172 | 4) ElevensBoard.java contains three helper methods. These helper methods are private because they are only called from the ElevensBoard class. 173 | a) Where is the dealMyCards method called in ElevensBoard? 174 | 175 | ``` 176 | The method, dealMyCards, is called in the ElevensBoard constructor and the newGame method. 177 | ``` 178 | 179 | b) Which public methods should call the containsPairSum11 and containsJQK methods? 180 | 181 | ``` 182 | The methods isLegal and anotherPlayIsPossible should call the containsPairSum11 and containsJQK methods. 183 | ``` 184 | 185 | c) It’s important to understand how the cardIndexes method works, and how the list that it returns is used. Suppose that cards contains the elements shown below. Trace the execution of the cardIndexes method to determine what list will be returned. Complete the diagram below by filling in the elements of the returned list, and by showing how those values index cards. Note that the returned list may have less than 9 elements. 186 | 187 | d) Complete the following printCards method to print all of the elements of cards that are indexed by cIndexes. 188 | 189 | ```java 190 | public static printCards(ElevensBoard board) { 191 | List cIndexes = board.cardIndexes(); 192 | /* Your code goes here. */ 193 | 194 | } 195 | public static printCards ( ElevensBoard board ) { 196 | List < Integer > cIndexes = board.cardIndexes ( ); 197 | 198 | for ( Integer kObj : cIndexes ) { 199 | int k = kObj.intValue ( ); 200 | System.out.println ( board.cardAt ( k ) ) ; 201 | } 202 | } 203 | ``` 204 | 205 | e) Which one of the methods that you identified in question 4b above needs to call the cardIndexes method before calling the containsPairSum11 and containsJQK methods? Why? 206 | 207 | ``` 208 | The method anotherPlayIsPossible needs to call the cardIndexes method before calling the containsPairSum11 and containsJQK methods. It needs to do this in order to get the indexes of all the cards on the board ( non-null cards) so that it can check to see if the board contains another pair of cards that sum to 11 or a JQK-triplet. 209 | ``` 210 | 211 | ## Activity 8 Questions: 212 | 213 | 1) Discuss the similarities and differences between Elevens, Thirteens, and Tens. 214 | 215 | Similarities: 216 | 217 | ``` 218 | They are all single player games. 219 | They are all played on a board with cards. 220 | The cards are selected for removal based on one of two rules: the cards’ point values add up to a specific sum, or there is a specific group of face cards. 221 | ``` 222 | 223 | Differences: 224 | 225 | ``` 226 | The number of cards on the board is different. 227 | The sums differ. 228 | The specific groups of face cards differ. 229 | ``` 230 | 231 | 2) As discussed previously, all of the instance variables are declared in the Board class. But it is the ElevensBoard class that “knows” the board size, and the ranks, suits, and point values of the cards in the deck. How do the Board instance variables get initialized with the ElevensBoard values? What is the exact mechanism? 232 | The ElevensBoard constructor passes to the Board constructor the information needed to initialize the instance variables declared in the abstract Board class. This is accomplished through the following use of super: 233 | 234 | ```java 235 | super ( BOARD_SIZE, RANKS, SUITS, POINT_VALUES ); 236 | ``` 237 | 238 | 3) Now examine the files Board.java, and ElevensBoard.java, found in the Activity8 Starter Code directory. Identify the abstract methods in Board.java. See how these methods are implemented in ElevensBoard. Do they cover all the differences between Elevens, Thirteens, and Tens as discussed in question 1? Why or why not? 239 | 240 | ``` 241 | No. The abstract methods will have to be implemented differently in the Tens and Thirteens games and will need different private helper methods to accomplish their tasks. 242 | ``` 243 | -------------------------------------------------------------------------------- /Exceptions.md: -------------------------------------------------------------------------------- 1 | # Exceptions 2 | 3 | ## Overview 4 | * Exceptions occur when there is an error that Java detects in your program during compile or run time 5 | * While you cannot prevent exceptions from occurring (in some situations), you can control the outcome 6 | * The general strategy to control exceptions is using a `try`/`catch` block, where you `try` to perform a block of code, but you can `catch` the exception if it occurs 7 | * You must specify what type of exception you're "catching" in the `catch` block - the most generic one is `Exception`, but sometimes programmers will put more specific ones like `FileNotFound` 8 | 9 | ## Example 10 | 11 | ### Handling a `NullPointerException` 12 | ```java 13 | public class Student { 14 | 15 | private String name; 16 | 17 | public Student(String name) { 18 | this.name = name; 19 | } 20 | 21 | public static void main(String[] args) { 22 | Student s = new Student(null); 23 | 24 | try { 25 | System.out.println(s.name); 26 | } catch (NullPointerException e) { 27 | System.out.println("The variable is null"); 28 | } 29 | } 30 | } 31 | ``` 32 | 33 | ### Handling an `ArrayIndexOutOfBounds` Exception 34 | 35 | ```java 36 | public static void main(String[] args) { 37 | int[] array = {0, 0, 0, 0, 0, 0}; 38 | int i; 39 | 40 | try { 41 | for (i = 0; i <= array.length; i++) { 42 | System.out.println(array[i]); 43 | } 44 | } catch (ArrayIndexOutOfBounds e) { 45 | System.out.println("Index " + i + " does not exist"); 46 | } 47 | } 48 | ``` 49 | -------------------------------------------------------------------------------- /File IO.md: -------------------------------------------------------------------------------- 1 | # File IO 2 | 3 | ## Overview 4 | * File IO, also known as File Input and Output, is used to read in a file and do something with the contents 5 | * There are multiple packages that must be imported, such as: 6 | * `java.util.Scanner` - reads the file into our program 7 | * `java.io.IOException` - handles IO-related exceptions 8 | * `java.io.File` - the actual file object 9 | * It is common to use the `hasNext()` method from the `Scanner` class with a `while` loop to loop through the contents of a File 10 | * In order for File IO to work correctly, make sure that the path to your `txt` file is properly configured 11 | * In Eclipse, it should be outside of the `src` folder and inside the project folder 12 | 13 | ## Example 14 | 15 | ### Basic `txt` file output 16 | 17 | `numbers.txt` 18 | ``` 19 | 14 20 | 22 21 | 42 22 | 53 23 | 28 24 | 87 25 | ``` 26 | 27 | `IOTest.java` 28 | ```java 29 | import java.util.Scanner; 30 | import java.io.IOException; 31 | import java.io.File; 32 | 33 | public class IOTest { 34 | public static void main(String[] args) { 35 | Scanner in = null; 36 | try { 37 | in = new Scanner(new File("numbers.txt")); 38 | while (in.hasNext()) { 39 | System.out.println(in.nextLine()); 40 | } 41 | } catch (IOException e) { 42 | System.out.println(e.getMessage()); 43 | } 44 | } 45 | } 46 | ``` 47 | 48 | ### Mean calculator 49 | 50 | `numbers.txt` 51 | ``` 52 | 128.5 53 | 380.4 54 | 123.9 55 | 684.2 56 | 679.4 57 | 189.5 58 | 948.2 59 | ``` 60 | 61 | `IOTest.java` 62 | ```java 63 | import java.util.Scanner; 64 | import java.io.IOException; 65 | import java.io.File; 66 | 67 | public class IOTest { 68 | public static void main(String[] args) { 69 | Scanner in = null; 70 | double sum = 0; 71 | double total = 0; 72 | 73 | try { 74 | in = new Scanner(new File("numbers.txt")); 75 | while (in.hasNextDouble()) { 76 | sum += in.nextDouble(); 77 | total++; 78 | } 79 | System.out.println("Mean: " + sum/total); 80 | } catch (IOException e) { 81 | System.out.println(e.getMessage()); 82 | } 83 | } 84 | } 85 | ``` 86 | -------------------------------------------------------------------------------- /For Loops.md: -------------------------------------------------------------------------------- 1 | # For Loops 2 | 3 | ## Overview 4 | * `for` loops are used to iterate through a sequence of primitive data types or objects 5 | * It is a pre-check loop, which means that if its `boolean` condition evaluates to `false`, then the body of the loop will not be executed 6 | * The `for` loop has three parts: the variable, `boolean` condition, and increment/decrement status 7 | * There is also a variant of the `for` loop, called the `for each` loop 8 | * This is generally used to loop through arrays, `ArrayList`, or generic `List` objects - basically anything that has an iterative structure 9 | * The `for each` loop is much more simple in syntax - the general formula is: the variable, the colon (`:`), and the name of the data structure to iterate through 10 | * A general rule of thumb is if you need to change the values of an existing data structure, `for` loops should be used to change the values and **not** `for each` loops because `for each` loops create a **copy** of the original data structure and iterates through that, instead of editing the original one 11 | 12 | ## Examples 13 | 14 | # `for` loop and an array 15 | 16 | ```java 17 | double[] raceTimes = {3.4, 5.6, 8.2, 3.9, 6.2, 5.8}; 18 | double min = raceTimes[0]; 19 | 20 | for (int i = 0; i < raceTimes.length; i++) { 21 | if (raceTimes[i] < min) min = raceTimes[i]; 22 | } 23 | 24 | System.out.println(“The shortest time was “ + min); 25 | ``` 26 | 27 | # `for each` loop and an `ArrayList` 28 | 29 | ```java 30 | ArrayList list = new ArrayList(); 31 | list.add(new Integer(5)); 32 | list.add(new Integer(10)); 33 | list.add(new Integer(12)); 34 | 35 | for (Integer i : list) { 36 | if (i.intValue() % 2 == 0) { 37 | System.out.println(“The value at index “ + i + “ is even”); 38 | } 39 | } 40 | ``` -------------------------------------------------------------------------------- /If Statements.md: -------------------------------------------------------------------------------- 1 | # If Statements 2 | 3 | ## Overview 4 | 5 | * `If` and `else` statements are the most basic type of control structure 6 | * If you require more than two choices, there is an additional `else if` statement 7 | * You can navigate these conditional statements through a `boolean` expression 8 | * If the `boolean` condition is `true`, then the code in the `if` statement is evaluated 9 | * If the `boolean` condition is `true`, then the code in the `else` statement is evaluated 10 | * If the `boolean` condition in the `if` statement is `false`, but the `boolean` condition in the `else if` statement is `true`, then the code in the `else if` statement is evaluated 11 | 12 | The basic structure of an `if`/`else` statement is as follows: 13 | 14 | ```java 15 | if () { 16 | // Code that goes in the if statement 17 | } else { 18 | // Code that goes in the else statement 19 | } 20 | ``` 21 | 22 | As stated above, you can also add `else if` statements if you would like to have more than two options. 23 | 24 | ```java 25 | if () { 26 | // Code that goes in the if statement 27 | } else if () { 28 | // Code that goes in the else if statement 29 | } else { 30 | // Code that goes in the else statement 31 | } 32 | ``` 33 | 34 | ## Miscellaneous 35 | 36 | * You can have more than one `else if` statements, but you can only have one `if` and one `else` statement in a single conditional expression 37 | * The `else` statement is optional in a conditional expression 38 | * The `else` statement does not require a boolean expression 39 | * You can also have further `if` and `else` statements within an `if` or `else` statement for greater conditional control 40 | 41 | ## Examples 42 | 43 | ### One `if`/`else if`/`else` statement 44 | ```java 45 | int count = 10; 46 | 47 | if (count < 10) { 48 | System.out.println("Number is below 10"); 49 | } else if (count == 10) { 50 | System.out.println("Number is equal to 10"); 51 | } else { 52 | System.out.println("Number is greater than 10"); 53 | } 54 | ``` 55 | 56 | ### Nested `if`/`else` statements 57 | 58 | ```java 59 | int count = 10; 60 | if (count < 10) { 61 | if (count % 2 == 0) { 62 | System.out.println("Number is less than 10 AND even"); 63 | } else { 64 | System.out.println("Number is less than 10 AND odd"); 65 | } 66 | } else if (count == 10) { 67 | System.out.println("Number is equal to 10"); 68 | } else { 69 | System.out.println("Number is greater than 10"); 70 | } 71 | ``` -------------------------------------------------------------------------------- /Importing.md: -------------------------------------------------------------------------------- 1 | # Importing 2 | 3 | ## Overview 4 | 5 | * Programmers often need to use libraries that are included in the standard Java distribution and reference methods from other classes 6 | * Libraries auto-imported include the `String` and `System` classes 7 | * In order to import a library, you can use the `import` keyword 8 | * In AP Computer Science, the classes that are imported the most include `ArrayList`, `Random`, `Scanner`, and `File` 9 | * Follow these steps to import a class 10 | * Select the class you need to import, for example, a `Scanner` 11 | * Determine where it is stored - you can find this information easily from the Java documentation or online on websites like Stack Overflow 12 | * Write the import statement with the `import` keyword 13 | 14 | ## Example 15 | 16 | ```java 17 | import java.util.Scanner; 18 | 19 | public class ReadFile { 20 | 21 | // Create object variable 22 | Scanner in = new Scanner(System.in); 23 | } 24 | ``` -------------------------------------------------------------------------------- /List Interface.md: -------------------------------------------------------------------------------- 1 | # List Interface 2 | 3 | Data structures like the `ArrayList` have overriden methods that are derived from the `List` interface. Because `List` is an interface, it is not possible to instantiate it, but it is possible to declare a reference to the `List` interface, as shown below. 4 | 5 | ```java 6 | # Not possible 7 | List list = new List(); 8 | 9 | # Possible 10 | List list = new ArrayList(); 11 | ``` 12 | 13 | Important methods that belong to the `List` interface: 14 | * `add(E element)` - adds the object to the end of the list 15 | * `add(int index, E element)` - adds the object to the specified index in the list 16 | * `clear` - removes all the elements from the list 17 | * `equals(Object o)` - compares the element in the parameter to an element inside of the list 18 | * `get(int index)` - retrieves the object at the specified index 19 | * `isEmpty` - confirms whether there is or is not an element inside of the list 20 | * `remove(int index)` - removes the object at the specified index 21 | * `remove(Object o)` - removes the first occurrence of the object in the list, provided that the object is actually in the list 22 | * `set(int index, E element)` - sets the element present in the current index to the object passed into the parameter 23 | -------------------------------------------------------------------------------- /Memory Allocation.md: -------------------------------------------------------------------------------- 1 | # Memory Allocation 2 | 3 | ## Overview 4 | * Java allocates memory for primitive data types and objects differently 5 | * Primitive data type variables have their value directly stored into them 6 | * Object variables merely hold a **reference** to where the actual object is stored - this is also known as a *hexadecimal address* or *hex address* for short 7 | * For objects, `null` indicates **nothing** or the absence of a reference to an object 8 | 9 | ## Examples 10 | 11 | ### Primitive data types 12 | 13 | 1) The contents of `v1` are directly passed on to `v2`. 14 | 15 | ```java 16 | int v1 = 10; 17 | int v2 = v1; 18 | 19 | ### Objects 20 | 21 | 1) The reference, or hex address, of `s1` is passed onto `s2`, so both variables **point** to the same location. 22 | 23 | ```java 24 | String s1 = “Computer Science”; 25 | String s2 = s1; 26 | ``` 27 | 28 | 2) Using `System.out.println` on the variable `s3` would throw a `NullPointerException` because the variable does not point to anything, and does not have a location in memory. It is considered garbage and therefore discarded. 29 | 30 | ```java 31 | String s3 = null; 32 | System.out.println(s3); 33 | 34 | // Equivalent to 35 | 36 | String s4; 37 | System.out.println(s4); 38 | ``` 39 | -------------------------------------------------------------------------------- /Methods.md: -------------------------------------------------------------------------------- 1 | #**Methods**# 2 | - must have return statements, unless it is a **void** method 3 | - method format is: 4 | + < visibility modifier > < return type > < method name > < parameter list > 5 | 6 | #Example# 7 | 8 | ```javascript 9 | //this method gets the number 10 | public int getNum (int x) { 11 | return x; 12 | } 13 | ``` 14 | 15 | -------------------------------------------------------------------------------- /Object-Oriented Programming.md: -------------------------------------------------------------------------------- 1 | # Object-Oriented Programming 2 | 3 | ## Overview 4 | 5 | * Object-oriented programming (OOP) is a standard by which programming languages can model objects in the world 6 | * **Classes** represent objects and **methods** can be used to do something to the object 7 | * Objects also have attributes, which can be represented by individual variables 8 | 9 | ## Attributes 10 | * Represented by variables, which can be primitive data types or even other objects, like the `String` class 11 | * Generally declared as `private` but they can also be `public` – the difference is whether they can be accessed from within or outside of the class 12 | * `private` attributes can only be used inside the class 13 | * `public` attributes can be used by classes from the outside 14 | 15 | ```java 16 | // How to declare variables 17 | private boolean x1; 18 | private int x2; 19 | private double x3; 20 | ``` 21 | 22 | ## Methods 23 | * Represent functions that the object either has or can do 24 | * For example, a `Square` object could have methods called `getArea()` and `getPerimeter()` that calculate the area and perimeter of the `Square` 25 | * `return` is used to essentially return or "get" a value from the function; if you have nothing to return, then put `void` in the identifier of the function 26 | * If you use `return`, you must declare the primitive data type or object that the function is returning in the identifier 27 | 28 | ```java 29 | // How to declare methods 30 | 31 | // Example of the return keyword 32 | private double getArea() { 33 | return height * width; 34 | } 35 | 36 | // Example of the void keyword 37 | private void sayHello() { 38 | System.out.println("Hello from this method"); 39 | } 40 | ``` 41 | 42 | ## Methods and Parameters 43 | 44 | * Parameters are used in methods in order to pass a value into the function for its internal use 45 | * Each parameter requires declaring it with its data type and name, just like a variable or class attribute is declared 46 | * For example, we need the height and width of a rectangle in order to calculate its area, so these can be parameters in a function called `getRectangleArea()` 47 | 48 | ```java 49 | private double getRectangleArea(double height, double width) { 50 | return height * width; 51 | } 52 | ``` 53 | 54 | ## Constructor 55 | 56 | * The constructor is a special method used to instantiate the attributes of a class 57 | * For example, we cannot know what a `Square` fundamentally and intrinsically is without knowing its height and width, which is why these attributes are absolutely necessary 58 | * How constructors are different from methods 59 | * They do not return anything 60 | * Their name must be the same as the class name 61 | * They do not have additional identifiers like `void` or `static` 62 | 63 | ```java 64 | public class Square { 65 | 66 | // Attributes 67 | private double height; 68 | private double width; 69 | 70 | // Constructor 71 | public Square(double myHeight, double myWidth) { 72 | height = myHeight; // copy parameter into attribute 73 | width = myWidth; // copy parameter into attribute 74 | } 75 | } 76 | ``` 77 | 78 | ## Case Study: Pencil 79 | 80 | A pencil is an example of an object in the real world. Naming a class can follow this general formula: `public class `. Note: there are no other modifiers that go in the class declaration. 81 | 82 | ```java 83 | public class Pencil { 84 | // Attributes and methods go here 85 | } 86 | ``` 87 | 88 | Examples of attributes that belong to a pencil include a serial number, lead width, and whether it is a mechanical pencil or regular pencil. 89 | 90 | ```java 91 | public class Pencil { 92 | 93 | private long serialNumber; 94 | private double leadWidth; 95 | private boolean isMechanical; 96 | } 97 | ``` 98 | 99 | A constructor can also be used to instantiate these variables. 100 | 101 | ```java 102 | public class Pencil { 103 | 104 | private long serialNumber; 105 | private double leadWidth; 106 | private boolean isMechanical; 107 | 108 | public Pencil(long mySerialNumber, double myLeadWidth, boolean myIsMechanical) { 109 | serialNumber = mySerialNumber; 110 | leadWidth = myLeadWidth; 111 | isMechanical = myIsMechanical; 112 | } 113 | } 114 | ``` 115 | 116 | We can also add methods in order to access the private data members or attributes if we want to use the `Pencil` object in another class. Note that all of the methods are uniform and specific in their name. 117 | 118 | ```java 119 | public class Pencil { 120 | 121 | private long serialNumber; 122 | private double leadWidth; 123 | private boolean isMechanical; 124 | 125 | public Pencil(long mySerialNumber, double myLeadWidth, boolean myIsMechanical) { 126 | serialNumber = mySerialNumber; 127 | leadWidth = myLeadWidth; 128 | isMechanical = myIsMechanical; 129 | } 130 | 131 | public long getSerialNumber() { 132 | return serialNumber; 133 | } 134 | 135 | public double getLeadWidth() { 136 | return leadWidth; 137 | } 138 | 139 | public boolean getMechanical() { 140 | return isMechanical; 141 | } 142 | } 143 | ``` -------------------------------------------------------------------------------- /Operators and Precedence.md: -------------------------------------------------------------------------------- 1 | # Operators and Precedence 2 | 3 | ## Math Operators 4 | 5 | ### Binary Operators 6 | 7 | * `+` - Addition 8 | * `-` - Subtraction 9 | * `*` - Multiplication 10 | * `/` - Division 11 | * If the operands are integers, the result will be an integer. `5 / 3` will result in an answer of `1`, and not `1.6666` 12 | * If the operands are floating point numbers, the result will be a floating point number. `5 / 3` will result in an answer of `1.6666`, and not `1` 13 | * `%` - Modulus (remainder) 14 | 15 | Note: If a single operand is a floating point number, the result will also be a floating point number. `17 + 1.0` will result in an answer of `18.0`. 16 | 17 | ### Unary operators 18 | 19 | * `-` - Negation 20 | 21 | To clarify, the negation operator only takes one operand, instead of two, like binary operators do. `-(-17)` will result in an answer of `17`. 22 | 23 | ### Precedence 24 | 25 | The precedence of the math operators (binary and unary) follow the order of operations. Unary operators (`-`) are evaluated first, then the multiplication (`*`), division (`/`), and modulus (`%`) operators, and finally the addition (`+`) and subtraction (`-`) operators. 26 | 27 | Example: 28 | ```java 29 | 9 + 16 / 3 * 7 % 8 - 5 30 | 9 + 5 * 7 % 8 - 5 31 | 9 + 35 % 8 - 5 32 | 9 + 3 - 5 33 | 7 34 | ``` 35 | 36 | ## Assignment Operators 37 | 38 | Assignment operators are used to perform a math operation on a variable, and then assign the new value of that variable to the variable. 39 | 40 | ```java 41 | // Declare variable 42 | int count = 0; 43 | 44 | // Count variable equals 1 45 | count = count + 1; 46 | ``` 47 | 48 | There are shortcuts for these types of operations: 49 | * `+=` - Add and assign 50 | * `-=` - Subtract and assign 51 | * `*=` - Multiply and assign 52 | * `/=` - Divide and assign 53 | * `%=` - Modulo and assign 54 | 55 | ```java 56 | // Addition 57 | int x1 = 10; 58 | x1 += 10; // x1 = 20 59 | 60 | // Subtraction 61 | int x2 = 10; 62 | x1 -= 10; // x2 = 0 63 | 64 | // Multiplication 65 | int x3 = 10; 66 | x3 *= 10 // x3 = 100 67 | 68 | // Division 69 | int x4 = 10; 70 | x4 /= 2; // x4 = 5 71 | 72 | // Modulus 73 | int x5 = 10; 74 | x5 %= 5; // x5 = 2 75 | ``` 76 | 77 | ## Increment/Decrement Operators 78 | 79 | Java provides shortcuts for incrementing and decrementing variables by `1`. Instead of performing `+=` or `-=`, you can use `++` or `--`. 80 | 81 | ```java 82 | int count = 0; 83 | 84 | // Increment operator 85 | count = count + 1; 86 | count += 1; 87 | count++; 88 | 89 | // Decrement operator 90 | count = count - 1; 91 | count -= 1; 92 | count--; 93 | ``` 94 | 95 | Note: There is a difference between `++count` and `count++`: 96 | * In `++count`, you increment the variable and then use it 97 | * In `count++`, you use the variable and then increment it 98 | 99 | ```java 100 | int a, b; 101 | 102 | // Scenario 1 103 | a = 0; 104 | b = ++a; // b = 1, a = 1 105 | 106 | // Scenario 2 107 | a = 0; 108 | b = a++; // b = 0, a = 1 109 | ``` 110 | 111 | To clarify, `++a` means **increment** and **then** use, but `a++` means **use** and then **increment**. -------------------------------------------------------------------------------- /Primitive Data Types.md: -------------------------------------------------------------------------------- 1 | # Primitive Data Types 2 | 3 | Java has 8 primitive data types: 4 | * `byte` - represents a byte 5 | * `boolean` - "true" or "false" values 6 | * `short` - "short" integers 7 | * `int` - regular integer 8 | * `long` - "long" integer 9 | * `float` - "short" real numbers 10 | * `double` - "long" real numbers 11 | * `char` - single ASCII character 12 | 13 | Programmers will mostly use the `boolean`, `int`, `double`, and sometimes the `char` data types, but it is good to know the other primitive data types and the differences between them. 14 | 15 | | byte | char | short | int | long | float | double | 16 | | --- | --- | --- | --- | --- | --- | --- | --- | 17 | | 1 byte | 2 bytes | 2 bytes | 4 bytes | 8 bytes | 4 bytes | 8 bytes | 18 | | `0` | `'a'` | `4` | `148` | `12897498` | `0.94` | `0.5972739` | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AP Computer Science 2 | 3 | This repository includes general notes and mini study guides for topics covered in AP Computer Science A, an introductory high school class covering important topics in theoretical computer science and the Java programming language. 4 | 5 | Additional resources for AP Computer Science: 6 | * [The AP Computer Science CollegeBoard website][1] 7 | * [Oracle Java Documentation][2] 8 | * [Oracle Java Tutorials][3] 9 | 10 | ## Table of Contents 11 | 12 | ### Introduction 13 | * [Base Conversion](https://github.com/shreydesai/apcs/blob/master/Base%20Conversion.md) 14 | * [Primitive Data Types](https://github.com/shreydesai/apcs/blob/master/Primitive%20Data%20Types.md) 15 | * [Variable Declaration](https://github.com/shreydesai/apcs/blob/master/Variable%20Declaration.md) 16 | * [Operators and Precedence](https://github.com/shreydesai/apcs/blob/master/Operators%20and%20Precedence.md) 17 | * [Variable Casting](https://github.com/shreydesai/apcs/blob/master/Variable%20Casting.md) 18 | * [Variable Scope](https://github.com/shreydesai/apcs/blob/master/Variable%Scope.md) 19 | 20 | ### Control Structures 21 | * [If Statements](https://github.com/shreydesai/apcs/blob/master/If%20Statements.md) 22 | * [Switch Statements](https://github.com/shreydesai/apcs/blob/master/Switch%20Statements.md) 23 | * [Handling Exceptions](https://github.com/shreydesai/apcs/blob/master/Handling%20Exceptions.md) 24 | 25 | ### Iteration 26 | * [For Loops](https://github.com/shreydesai/apcs/blob/master/For%20Loops.md) 27 | * [While/Do-While Loops](https://github.com/shreydesai/apcs/blob/master/While%20Loops.md) 28 | * [Recursion](https://github.com/shreydesai/apcs/blob/master/Recursion.md) 29 | 30 | ### Logic 31 | * [Boolean Operators](https://github.com/shreydesai/apcs/blob/master/Boolean%20Operators.md) 32 | * [DeMorgan's Law](https://github.com/shreydesai/apcs/blob/master/DeMorgan%Law.md) 33 | 34 | ### Branching Statements 35 | * [Break](https://github.com/shreydesai/apcs/blob/master/Break.md) 36 | * [Continue](https://github.com/shreydesai/apcs/blob/master/Continue.md) 37 | 38 | ### Data Structures 39 | * [Arrays](https://github.com/shreydesai/apcs/blob/master/Arrays.md) 40 | 41 | ### Classes 42 | * [Object-Oriented Programming](https://github.com/shreydesai/apcs/blob/master/Object-Oriented%20Programming.md) 43 | * [Static Variables and Methods](https://github.com/shreydesai/apcs/blob/master/Static%20Variables%20and%20Methods.md) 44 | * [Memory Allocation](https://github.com/shreydesai/apcs/blob/master/Memory%20Allocation.md) 45 | * [Class Casting](https://github.com/shreydesai/apcs/blob/master/Class%20Casting.md) 46 | * [Wrapper Classes](https://github.com/shreydesai/apcs/blob/master/Wrapper%20Classes.md) 47 | 48 | ### Libraries 49 | * [Importing](https://github.com/shreydesai/apcs/blob/master/Importing.md) 50 | * [File IO](https://github.com/shreydesai/apcs/blob/master/File%20IO.md) 51 | 52 | ### Interfaces 53 | * [List Interface](https://github.com/shreydesai/apcs/blob/master/List%20Interface.md) 54 | 55 | ### Algorithms 56 | * [Sorting Algorithms](https://github.com/shreydesai/apcs/blob/master/Sorting%20Algorithms.md) 57 | * [Searching Algorithms](https://github.com/shreydesai/apcs/blob/master/Searching%20Algorithms.md) 58 | 59 | ### Labs 60 | * [Elevens Lab](https://github.com/shreydesai/apcs/blob/master/Elevens%20Lab%20QA.md) 61 | 62 | ## Contributors 63 | 64 | * Shrey Desai 65 | * Kimberly Chen 66 | 67 | Ways to contribute to the repository: 68 | * Create an issue if you find an error in the articles 69 | * Write an original article and create a pull request 70 | * Review an existing article and create a pull request 71 | 72 | [1]: https://apstudent.collegeboard.org/apcourse/ap-computer-science-a 73 | [2]: https://docs.oracle.com/javase/7/docs/api/ 74 | [3]: https://docs.oracle.com/javase/tutorial/ 75 | -------------------------------------------------------------------------------- /Recursion.md: -------------------------------------------------------------------------------- 1 | # Recursion 2 | 3 | ## Overview 4 | * Recursion is the process of calling a function over and over again until it reaches a base case, finally terminating the process and yielding a result 5 | * The base case is usually evaluated through a conditional statement 6 | * If the `boolean` statement is `true`, then the recursive process terminates 7 | * If the `boolean` statement is `false`, then the function calls itself and keeps going until it reaches a base case 8 | * What recursion does is work its way to the base case, calling the function over and over again; when the base case is reached, usually some value is returned, and this value makes its way up to the front of the stack, and this is the value that is returned to the user 9 | * It is wise to be extremely careful with recursion - if you do not reach a base case, your program and/or computer can crash due to memory overload because of thousands of recursive calls 10 | 11 | ## Example 12 | 13 | ### Number of calls 14 | 15 | ```java 16 | public static int calls(int depth) { 17 | if (depth == 10) { 18 | return 1; 19 | } else { 20 | return calls(depth + 1); 21 | } 22 | } 23 | 24 | public static void main(String[] args) { 25 | 26 | // Finds the number of recursive calls 27 | // with 10 as the upper limit 28 | calls(0); 29 | } 30 | ``` 31 | 32 | ### Fibonacci sequence 33 | 34 | ```java 35 | public static int fib(int n) { 36 | if (n == 0) { 37 | return 0; 38 | } else if (n == 1) { 39 | return 1; 40 | } else { 41 | return fib(n - 1) + fib(n - 2); 42 | } 43 | } 44 | 45 | public static void main(String[] args) { 46 | 47 | // Finds the 10th number in the Fibonacci sequence 48 | fib(10); 49 | } 50 | ``` 51 | -------------------------------------------------------------------------------- /Scanner Class.md: -------------------------------------------------------------------------------- 1 | # **Scanner Class** 2 | - grabs whatever is inputted in the console 3 | - use "System.in" 4 | 5 | ## Example 6 | ```javascript 7 | Scanner keyboard = new Scanner(System.in); 8 | int num1, num2; 9 | double dnum1, dnum2; 10 | 11 | System.out.print("Eter an integer: "); 12 | num 1 = keyboard.nextInt(); 13 | System.out.print("Enter a double value: "); 14 | dnum1 = keyboard.nextDouble(); 15 | ``` 16 | -------------------------------------------------------------------------------- /Searching Algorithms.md: -------------------------------------------------------------------------------- 1 | # Searching Algorithms 2 | 3 | ## Linear Search 4 | 5 | **Overview:** 6 | * This methods examines each element in sequence starting with the first one to determine if a target element is found; the loop will break if the target is found 7 | * If the target is not found, then the method will output `-1` 8 | * When searching an array of objects, one can use the `equal` method to compare the objects, such as Strings 9 | * Time complexity is O(n), or linear, which is considered inefficient 10 | 11 | **Code:** 12 | ```java 13 | public static int linearSearch (Rectangle [] r) { 14 | for (int i = 0; i < r.length; i++) { 15 | if (r[i].myWidth == 4) { 16 | return i; 17 | } 18 | } 19 | return -1; 20 | } 21 | ``` 22 | 23 | ## Binary Search 24 | 25 | **Overview:** 26 | * Binary search divides an array in half and examines the data at the point of the split. When the array is split, it is easy to rule out the half that does not matter 27 | * Steps include: 1) Divide the array in half 2) Examine the value in the middle; is the value you’re searching for higher or lower? If higher, discard the lower half array. If lower, discard the higher half array. 3) Repeat. 28 | * **Important consideration:** Arrays must be sorted in order for binary search to work. Its time complexity does not account for its pre-processing time. 29 | * Time complexity is O(log2N), or logarithmic, so it is considered quite efficient. For example, finding the number `1` in a list of `1024` would take `10` steps, since `log2(1024)` is equal to `10`. 30 | 31 | **Non-Recursive Code:** 32 | ```java 33 | int[] data; 34 | int size; 35 | 36 | public boolean binarySearch(int key) { 37 | int low = 0; 38 | int high = size - 1; 39 | 40 | while (high >= low) { 41 | int middle = (low + high) / 2; 42 | if (data[middle] == key) { 43 | return true; 44 | } 45 | if (data[middle] < key) { 46 | low = middle + 1; 47 | } 48 | if (data[middle] > key) { 49 | high = middle - 1; 50 | } 51 | } 52 | 53 | return false; 54 | } 55 | ``` 56 | 57 | **Recursive Code:** 58 | ```java 59 | public int binarySearch(int[] list, int lowIndex, int highIndex, int value) { 60 | if (lowIndex > highIndex) { 61 | return -1; 62 | } else { 63 | int middle = (lowIndex + highIndex) / 2; 64 | if (value == list[middle]) { 65 | return middle; 66 | } else if (value < list[middle]) { 67 | return binarySearch(list, lowIndex, middle - 1, value); 68 | } else { 69 | return binarySearch(list, middle + 1, highIndex, value); 70 | } 71 | } 72 | } 73 | ``` 74 | 75 | Note: The recursive solution is sometimes easier to understand, but might be less efficient when compared to the non-recursive solution because it requires more memory to add each call to the recursive stack. However, both solutions are conceptually equivalent. 76 | -------------------------------------------------------------------------------- /Sorting Algorithms.md: -------------------------------------------------------------------------------- 1 | # Sorting Algorithms 2 | 3 | ## Bubble Sort 4 | 5 | **Overview:** 6 | * Elements are sorted as they gradually "bubble" to their proper location in the array 7 | * The algorithm continues by comparing adjacent elements of an array; the first and second elements are compared and swapped if out of order 8 | * There is an early kick-out feature, which exits the array if there are no swaps that have been made (generally uses a `while` loop) 9 | * Time complexity is `O(n^2)`, or quadratic time; the algorithm is considered inefficient because it uses nested loops 10 | 11 | **Code:** 12 | ```java 13 | public void bubbleSort(int[] list) { 14 | for (int outer = 0; outer < list.length - 1; outer++) { 15 | for (int inner = 0; i < list.length - outer - 1; inner++) { 16 | if (list[inner] < list[inner + 1]) { //this statement determines whether high-to-low 17 | int temp = list[inner]; 18 | list[inner] = list[inner + 1]; 19 | list[inner + 1] = temp; 20 | } 21 | } 22 | } 23 | } 24 | ``` 25 | 26 | Note: The `<` in the first conditional statement can be changed to `>` if you want to change the algorithm to sort the elements in an ascending order (lower elements to higher elements). 27 | 28 | There is also a more efficient version of the bubble sort algorithm. In the previous example, it continues throughout the entire array until all elements have been touched. In the more efficient version, the algorithm will make up to `n - 1` passes, but will exit early if no exchanges are made on the previous pass. 29 | 30 | ```java 31 | public static void bubbleSort(int[] list) { 32 | int k = 0; 33 | boolean exchangeMade = true; 34 | 35 | while ((k < list.length - 1) && exchangeMade) { 36 | exchangeMade = false; 37 | k++; 38 | for (int j = 0; j < list.length - k; j++) { 39 | if (list[j] < list[j + 1]) { //this statement determines whether high-to-low 40 | swap(a, j, j + 1); 41 | exchangeMade = true; 42 | } 43 | } 44 | } 45 | } 46 | ``` 47 | 48 | ## Selection Sort 49 | 50 | **Overview:** 51 | * The selection sort is a combination of searching and sorting 52 | * During each iteration, the unsorted element with the smallest/largest value is moved to its respective index in the array 53 | * The inner loop finds the smallest/largest value and the outer loop places the value into its respective index 54 | * There are `n - 1` iterations where `n` is the length of the array 55 | * Time complexity is `O(n^2)`, or quadratic time; the algorithm is considered inefficient because it uses nested loops. 56 | 57 | **Code (long version):** 58 | 59 | ```java 60 | public void selectionSort(int[] list) { 61 | for (int i = 0; i < list.length - 1; i++) { 62 | int minIndex = findMinimum(list, i); 63 | if (minIndex != i) { 64 | swap(a, i, minIndex); 65 | } 66 | } 67 | } 68 | 69 | //if you want to do high-to-low, then you do findMaximum 70 | //if you want to do low-to-high, then you do findMinimum 71 | public int findMinimum(int[] list, int first) { 72 | int minIndex = first; 73 | for (int i = first + 1; i < list.length; i++) { 74 | if (list[i] < list[minIndex]) { //this statement determines whether high-to-low 75 | minIndex = i; 76 | } 77 | } 78 | return minIndex; 79 | } 80 | 81 | public void swap(int[] list, int x, int y) { 82 | int temp = list[x]; 83 | list[x] = list[y]; 84 | list[y] = temp; 85 | } 86 | ``` 87 | 88 | **Code (short version):** 89 | ```java 90 | public void selectionSort(int[] list) { 91 | int i, j, first, temp; 92 | 93 | for (i = list.length - 1; i > 0; i--) { 94 | first = 0; 95 | 96 | for (j = 1; j <= i; j++) { 97 | if (list[j] < list[first]) { 98 | first = j; 99 | } 100 | } 101 | 102 | temp = list[first]; 103 | list[first] = list[i]; 104 | list[i] = temp; 105 | } 106 | } 107 | ``` 108 | 109 | ## Insertion Sort 110 | 111 | **Overview:** 112 | * This algorithm passes through the array only once by splitting the array into two-sub arrays, and then working with both of them 113 | * The first sub-array is always sorted and increases in size as the sort continues; the second sub-array is unsorted and decreases in size as the elements are inserted into the first sub-array 114 | * Unlike the other algorithms, insertion sort has a `k` value, or "key", which 1) stands for the element that needs to be sorted and 2) indicates the division between the first and second sub-arrays 115 | * The goal is that on the `kth` pass, the `kth` element will be sorted 116 | * Time complexity is `O(n^2)`, or quadratic time; the algorithm is considered inefficient because it uses nested loops 117 | 118 | **Code:** 119 | ```java 120 | public void insertionSort(int[] list) { 121 | int itemToInsert, j; 122 | boolean stillLooking; 123 | 124 | for (int k = 1; k < list.length; k++) { 125 | itemToInsert = list[k]; 126 | j = k - 1; 127 | stillLooking = true; 128 | 129 | while ((j >= 0) && stillLooking) { 130 | if (itemToInsert < list[j]) { //this statement determines whether high-to-low 131 | list[j + 1] = list[j]; 132 | j--; 133 | } 134 | else { 135 | stillLooking = false; 136 | } 137 | } 138 | 139 | list[j + 1] = itemToInsert; 140 | } 141 | } 142 | ``` 143 | 144 | ## Merge Sort 145 | 146 | **Overview:** 147 | * In summary, the purpose of merge sort is to "divide and conquer" 148 | * The list passed into the merge sort algorithm will be split into equal size lists, which will be sorted, and then **merged back** into the larger list, which will be sorted 149 | * There are both non-recursive and recursive implementations 150 | * The **non-recursive** algorithm usually splits the algorithm into two sections – selection sort and a merge method 151 | * The **recursive** algorithm calls itself over and over again until the list is completely sorted 152 | * Time complexity is `O(N * log2N)`, or linear logarithmic time; the algorithm is considered quite efficient, especially when compared to the quadratic time sorting algorithms 153 | 154 | **Code (non-recursive pseudocode):** 155 | ```java 156 | public void mergeSort(ArrayList list, int first, int last) { 157 | int mid; 158 | 159 | mid = (first + last) / 2; 160 | selectionSort(list, first, mid); 161 | selectionSort(list, mid + 1, last); 162 | merge(list, first, mid, last); 163 | } 164 | ``` 165 | 166 | **Code (recursive pseudocode):** 167 | ```java 168 | public void mergeSort(int[] list, int first, int last) { 169 | int mid; 170 | 171 | if (first == last) { 172 | return; 173 | } else if (first + 1 == last) { 174 | // determine smaller/bigger and swap 175 | } else { 176 | mid = (first + last) / 2; 177 | mergeSort(list, first, mid); 178 | mergeSort(list, mid + 1, last); 179 | merge(list, first, mid, last); 180 | } 181 | } 182 | ``` 183 | 184 | ## Sorting Objects 185 | 186 | **Overview:** 187 | * Java objects will generally implement the `Comparable` interface and implement the method `compareTo`, which allows for the testing of integers or floating-point numbers 188 | * The goal is to replace all of the array parameters with the respective object and use `compareTo` instead of mere array item comparison with numerical operators 189 | 190 | **Sample Code:** 191 | ```java 192 | public int findMinimum(Object[] list, int first) { 193 | int minIndex = first; 194 | 195 | for (int i = first + 1; i < list.length; i++) { 196 | if ((Comparable)list[i]).compareTo([list[minIndex]] < 0) { 197 | minIndex = i; 198 | } 199 | } 200 | 201 | return minIndex; 202 | } 203 | ``` 204 | 205 | ## Identifying Algorithms 206 | 207 | ### General rule 208 | Assuming `list[inner]` will be replaced with `list[inner + 1]`, `<` inside the boolean condition means **high to low** and `>` means **low to high**. 209 | 210 | ### Bubble Sort 211 | * The non-early kickout feature has two `for` loops 212 | * The early kickout feature has a `while` loop with a boolean condition 213 | * The sorting happens inside the loops 214 | 215 | ### Selection Sort 216 | * There are two `for` loops 217 | * Inside the inner `for` loop, there is variable assignment 218 | * Inside the outer `for` loop, there is sorting 219 | 220 | ### Insertion Sort 221 | * There is one `for` loop and one `while` loop 222 | * The `while` loop has a boolean condition 223 | * Inside the `while` loop, there is a variable that decrements 224 | * Sorting happens inside the outer loop -------------------------------------------------------------------------------- /Static Variables and Methods.md: -------------------------------------------------------------------------------- 1 | # Static Variables and Methods 2 | 3 | ## Overview 4 | 5 | * Static variables and methods are used when you want to create variables that are common, or "static," for all objects 6 | * Unlike instance variables, static variables usually remain constant or change minimally when objects are declared 7 | * Static variables and methods should **not** access instance variables because this ruins the purpose of them being class-specific - this means you can't use the `this` keyword when referring to static variables and methods 8 | * For example, variables like `color` or `size` would fluctuate for a `Frog` object, but something like `pondColor` or `pondSize` would probably remain constant between `Frog` objects 9 | 10 | ## Declaration 11 | 12 | Static variables and methods are declared using the `static` modifier, along with the other modifiers. The `static` declaration should come after visibility modifiers and before return type modifiers. 13 | 14 | ```java 15 | # Example of a static variable 16 | private static int number; 17 | 18 | # Example of a static method 19 | private static int getNumber() { 20 | return number; 21 | } 22 | ``` 23 | 24 | ## Calling static variables 25 | 26 | Because static variables and methods are a part of the class, they must be called by referring to the class itself, and not the object. For example, recalling the `Frog` class from above: 27 | 28 | ```java 29 | # Access the pondColor variable 30 | Frog.pondColor; 31 | 32 | # Access the pondColor variable through an accessor method 33 | Frog.getPondColor(); 34 | ``` 35 | 36 | While it is possible to access static variables and methods through an object, this is discouraged because it defeats the purpose of the variable/method being a part of the class itself. 37 | -------------------------------------------------------------------------------- /Switch Statements.md: -------------------------------------------------------------------------------- 1 | # Switch Statements 2 | 3 | ## Overview 4 | * `switch` statements are used when there are multiple conditional outcomes that must be handled in a particular program 5 | * These statements are usually preferred over multiple `else if` statements 6 | * The `switch` statement requires some sort of variable to *switch* on - this can be anything from an `int` variable to even an `Object` 7 | * Each `switch` statement involves a `case`, which specifies which conditional outcome to handle, and also has a `default` case, which is triggered if none of the cases are reached 8 | * `case` statements can also be grouped together to share code 9 | * There must be a `break` keyword after each `case` statement to indicate that the code in the statement is finished executing - if there is no `break` keyword, there will be a *fallout* where the code in every single `case` statement after that one will also be executed 10 | 11 | ## Example 12 | 13 | ## Individual `case` statements 14 | 15 | ```java 16 | int number = 0; 17 | 18 | switch (number) { 19 | case 0: 20 | System.out.println("The number is 0"); 21 | break; 22 | case 1: 23 | System.out.println("The number is 1"); 24 | break; 25 | case 2: 26 | System.out.println("The number is 2"); 27 | break; 28 | default: 29 | System.out.println("Some other number"); 30 | } 31 | ``` 32 | 33 | ## Grouped `case` statements 34 | 35 | ```java 36 | boolean flag = true; 37 | 38 | switch (flag) { 39 | case true: case false: 40 | System.out.println("The flag is true or false"); 41 | break; 42 | default: 43 | System.out.println("The flag is neither true nor false"); 44 | } 45 | ``` -------------------------------------------------------------------------------- /Variable Casting.md: -------------------------------------------------------------------------------- 1 | # Variable Casting 2 | 3 | ## Overview 4 | 5 | * Variable casting is used when the data type of a variable is temporarily converted to another primitive data type. The general formula for variable casting is: ` = () `. 6 | * Common variable casting conversions include: 7 | * `int` to `double` and `double` to `int` 8 | * `int` to `char` and `char` to `int` 9 | * Some primitive data types cannot be casted to another, such as `boolean` to `int`, or `short` to `long` - doing so will throw an exception 10 | 11 | ## Examples 12 | 13 | **`int` and `double`** 14 | 15 | ```java 16 | int x1 = 5; 17 | 18 | // Casting an integer to a double 19 | double x2 = (double) x1; 20 | 21 | System.out.println(x2); // Prints 5.0 22 | ``` 23 | 24 | **`int` and `char`** 25 | 26 | ```java 27 | char x1 = 'a'; 28 | 29 | // Casting a char to an integer 30 | int x2 = (int) x1; 31 | 32 | System.out.println(x2); // Prints 97 33 | ``` 34 | 35 | ## Miscellaneous 36 | 37 | More on `int` to `char` casting: 38 | * `char` data types are actually stored as integers in memory 39 | * These data types follow the American Standard Code for Information Interchange, or ASCII, coding 40 | * Refer to [this table](http://www.asciitable.com/) for a comprehensive list on what the corresponding integer is for a character -------------------------------------------------------------------------------- /Variable Declaration.md: -------------------------------------------------------------------------------- 1 | # Variable Declaration 2 | 3 | Variables are used to store information and data in different formats. The general formula is: ` = ;` 4 | 5 | ```java 6 | // Declare an integer variable 7 | int x1 = 5; 8 | 9 | // Declare a double variable 10 | double x2 = 5.0; 11 | 12 | // Declare a boolean variable 13 | boolean x3 = true; 14 | ``` 15 | 16 | Variables can also be declared and then initialized later. This means that the variable's name is stored in the system, but then the contents of the variable is allocated in memory later on. 17 | 18 | ```java 19 | // Declare the variable 20 | int x1; 21 | 22 | // Initialize the variable 23 | x1 = 5; 24 | ``` 25 | -------------------------------------------------------------------------------- /Variable Scope.md: -------------------------------------------------------------------------------- 1 | # Variable Scope 2 | 3 | ## Overview 4 | * There are two namespaces for variables, `global` and `local` 5 | * Global variables are usually declared as `class` variables 6 | * Local variables are usually declared within individual methods, or even conditional or iterative statements 7 | * As long as they do not conflict, global and local variables can share the same name and object type/primitive data type 8 | * For local variables, there is some memory that is allocated for them in the beginning of a parameter list or method, but then that memory is deleted once the reading of the parameter list or method has completed - the variable effectively does not *exist* anymore 9 | 10 | ## Example 11 | 12 | All three of these variables can coexist within the program. 13 | 14 | ```java 15 | public class Test { 16 | private int num = 10; 17 | 18 | private void testerMethod(int num) { 19 | return num; 20 | } 21 | 22 | public static void main(String[] args) { 23 | for (int num = 0; num < 10; num++) { 24 | System.out.println(num); 25 | } 26 | } 27 | 28 | } 29 | ``` 30 | -------------------------------------------------------------------------------- /While Loops.md: -------------------------------------------------------------------------------- 1 | # **While Loops** 2 | + `while` loops have a condition that must be satisfied in order to implement the code inside the `while` loop 3 | + The quantity of iterations is unknown for the while loop 4 | + This is a pretest loop 5 | 6 | ## Example 7 | ```java 8 | double num = 24.0; 9 | while (num <= 32) { 10 | System.out.println(num + " "); 11 | num += 1.25; 12 | } 13 | ``` 14 | 15 | # **Do While Loops** 16 | + Similar to a `while` loop except that the code will run the `do-while` loop at least once 17 | - After the code has gone through the loop the first time, the condition must be satisfied to go through the `do-while` loop again 18 | + This is a post-test loop 19 | 20 | ## Example 21 | ```java 22 | int m = 1; 23 | do { 24 | System.out.println(m + " " + (m-1)); 25 | m+=2; 26 | } 27 | while (m != 10); 28 | ``` 29 | -------------------------------------------------------------------------------- /Wrapper Classes.md: -------------------------------------------------------------------------------- 1 | # Wrapper Classes 2 | 3 | ## Overview 4 | * Because some data structures like `ArrayList` require objects, we must use wrapper classes for the primitive data types 5 | * We can do `int[] num`, but we can't do `List` 6 | * Each primitive data type has a corresponding wrapper class - you just capitalize the first letter of each 7 | * `int` -> `Integer` 8 | * `double` -> `Double` 9 | * `boolean` -> `Boolean` 10 | * The wrapper classes are objects, so in order to *unpack* the value inside, use its respective method 11 | * `Integer` -> `getIntValue()` 12 | * `Double` -> `getDoubleValue()` 13 | * `Boolean` -> `getBooleanValue()` 14 | * You can also use wrapper classes with arrays, such as `Integer[] nums` instead of `int[] nums` - it just becomes an object array 15 | 16 | ## Example 17 | 18 | Random number generation, storing the values in an `ArrayList`, and iterating through it to calculate the mean. 19 | 20 | ```java 21 | 22 | import java.util.ArrayList; 23 | 24 | public class Test { 25 | public static void main(String[] args) { 26 | ArrayList values = new ArrayList(); 27 | int total = 0; 28 | for (int i = 0; i < 100; i++) { 29 | int num = (int) (Math.random() * 100); 30 | values.add(new Integer(num)); 31 | } 32 | for (Integer i : values) { 33 | int num = i.getIntValue(); 34 | total += num; 35 | } 36 | System.out.println("Mean: " + values.size()/num); 37 | } 38 | } 39 | 40 | ``` 41 | --------------------------------------------------------------------------------