cs300---fall-2024-1.pdf

Full Transcript

Learning Objectives: Array Basics Create an array using both the initializer list and new methods Access and modify array elements Iterate through arrays using both a regular for loop and an enhanced for loop Determine array output Creating an Array What Is an Array? An array is a data s...

Learning Objectives: Array Basics Create an array using both the initializer list and new methods Access and modify array elements Iterate through arrays using both a regular for loop and an enhanced for loop Determine array output Creating an Array What Is an Array? An array is a data structure that stores a collection of data such as ints, doubles, Strings, etc. This data is often referred to as the array’s elements. Being able to store elements into an array helps reduce the amount of time needed to declare and initialize variables. For example, if you wanted to store the names of all family members in your household, you would typically have to declare and initialize String variables and values for each family member. Copy the code below into the text editor on the left and then click the TRY IT button to see the output. You can also click on the ++Code Visualizer++ link underneath to see how the program runs behind the scenes. String a = "Alan"; String b = "Bob"; String c = "Carol"; String d = "David"; String e = "Ellen"; System.out.println(a); challenge What happens if you: Change the a in System.out.println(a) to b, c, d, or e? Array Creation To avoid the repetitive task of declaring and initializing multiple variables, you can declare an array and directly assign values or elements into that array like below. This technique is referred to as the initializer list method. String[] names = {"Alan", "Bob", "Carol", "David", "Ellen"}; “Initializer List” Method Syntax: Specify the data type that the array will store (i.e. String) followed by empty brackets []. Declare the variable name for the array (i.e. names) followed by the assignment symbol =. Elements assigned to the array are separated by commas , and enclosed within curly braces {}. Additional information If you used the Code Visualizer, you’ll notice that the array variable names refers to all of the elements as a collection. An array is considered to be an object that bundles all of the data that it holds. Note that the first array slot, or index, is always 0 so Alan is located at index 0 instead of 1. Alternatively, you can create an array using the new method in which you will need to declare and specify the array variable and length before you can assign elements to the array. String[] names = new String; “New” Method Syntax Specify the data type that the array will store (i.e. String) followed by empty brackets []. Declare the variable name for the array (i.e. names) followed by the assignment symbol =. Declare the keyword new followed by the data type (i.e. String) and number of elements in brackets (i.e. ). Additional information If you used the Code Visualizer, you’ll notice that the array variable names refers to all of the elements as a collection. null appears in all of the array slots because no elements have been assigned to them yet. Note that the first array slot, or index, is always 0. Array Details Both the initializer list and new methods mentioned above will store five elements in the array called names. However, the new method automatically initializes each element to a default value of null while the initializer list method does not. Note that array slots are formally called indices and each index can carry just one type of data. For example, storing an int of 5 into a String array will result in a error. P.O. Boxes at the postal office is symbolically similar to arrays. Each row of P.O. Boxes is like an array, except each box can only store one item (element) and each item within that row must be of the same type (i.e. Strings). The position at which each box is located is its index..guides/img/ArrayElementsIndices Oversize and Perfect Size Arrays Perfect size arrays A perfect size array is an array where the number of elements is equal to the memory allocated. (These are almost certainly the variety of array that you’re already familiar with.) For example, the maximum daily temperature for a week could be stored in an array with 7 integer values. Perfect size arrays can be created using an initializer, which sets both the array’s length and initializes each element in the array to given values: int[] highTempsF = {93, 80, 62, 75, 74, 89, 97}; Perfect size arrays of objects may contain null values. When to use perfect size arrays Perfect size arrays are especially useful when the size of the array is fixed by the context of the program. Storing the names of the days of the week in a perfect size array makes sense because the number of days in a week will not change. Compare this to an array that contains the list of cities where a company has locations – companies may add or remove locations over time, so this is not a great candidate for a perfect size array. Methods with perfect size array parameters Perfect size arrays are passed to methods using only the array’s reference (its location in heap memory). The number of elements and data are accessed from that array reference. Consider this method to store the given value at each element of the array: public static void fill(int[] arrayReference, int value) { int index; for (int index = 0; index < arrayReference.length; ++index) { arrayReference[index] = value; } } When an array reference is passed to a method, the method can update the contents of the original array AND those updates will persist after the method has completed, without needing to return a value (note that the return type of fill() is void). Methods returning perfect size arrays Methods can also return perfect size array references. Since methods can only return one value, a method returning an array MUST return a perfect size array! Oversize arrays An oversize array is an array where the number of elements used at any given time in the program is less than or equal to the memory allocated for the array (that is, its length). Since the number of elements (the size) of an oversize array can be less than the array’s length, we use a separate integer variable to keep track of how many elements are currently used. This is an example of an empty oversize array: int[] programScores = new int; int programScoresSize = 0; Since you haven’t completed any programming assignments yet this semester, the array only contains its default values. As the semester progresses, you may add more data to this array, and increase the corresponding size variable accordingly. Oversize array protocols There is nothing inherent to Java that enforces the rules of oversize arrays; these are a set of protocols that programmers agree to follow to make oversize array usage predictable: 1. Oversize arrays consist of an initialized array reference and an integer size variable. 2. Oversize arrays must be compact; that is, initialized values in an oversize array are present from index 0 to index size-1 with no gaps. This means that any data outside of the index range [0 - (size-1)] is considered “junk data”. Oversize arrays vs perfect size arrays Let’s compare the usage of these two standards of array maintenance. In each of the following questions, select the variable type that best matches the stated application. Accessing an Array Array Access To access and print array elements, you need to know their position. The position at which an element is stored is called its index. For example, numbers refers to the first element in the array called numbers. Array indices always start at 0 and increment by 1 with each element that comes next. Due to this, numbers refers to the fifth element in the array, not the fourth. int[] numbers = {1, 2, 3, 4, 5}; System.out.println(numbers); challenge What happens if you: Change numbers in the code above to numbers? Change numbers in the code above to numbers? Change numbers in the code above to numbers? important IMPORTANT You may have noticed that printing the numbers array without specifying an index resulted in an output that starts with [I@… This occurs because printing an array actually prints its memory location, not its elements. You’ll learn how to print all elements in an array without having to specify all of their indices on a later page. Default “New” Elements When using the new method to create an array, there are default values that populate as elements inside of the array, depending on the array type. For example, String[] words = new String will result in five null elements and int[] numbers = new int will populate five elements of 0s within the array. Below is a table showing the default values of different array types when the “new” method is used. Data Type Default Value String null int 0 double 0.0 boolean false double[] decimals = new double; boolean[] bools = new boolean; System.out.println(decimals); System.out.println(bools); challenge What happens if you: Change decimals in the code above to decimals? Change bools in the code above to bools? Change decimals in the code above to decimals? Change bools in the code above to bools? IndexOutOfBounds Error A common error that occurs is called the ArrayIndexOutOfBoundsException error. This happens when you try to access or print an element at an index that does not exist within the array. In the example above, decimals and bools both resulted in an ArrayIndexOutOfBoundsException because neither array has an index of 2. Both arrays have only indices and to hold their elements..guides/img/ArrayException Modifying an Array Array Modification To modify an element within an array, simply find the index at which that element is stored and assign a new value to it. int[] grades = {85, 95, 48, 100, 92}; System.out.println(grades); grades = 88; //88 will replace 48 at index 2 System.out.println(grades); challenge What happens if you: Change int[] grades = {85, 95, 48, 100, 92}; in the code above to int[] grades = new int;? Change all System.out.println(grades); in the code above to System.out.println(grades);? Change grades = 88; in the code above to grades = 100;? Modifying Multiple Arrays You can create and modify as many arrays as you’d like. For example, you can create an array to store your family members and another array to store their age. String[] family = {"Dad", "Mom", "Brother", "Sister"}; int[] age = new int; System.out.println(family + " " + age); System.out.println(family + " " + age); System.out.println(family + " " + age); System.out.println(family + " " + age); challenge What happens if you: Add age = 50; directly below the line int[] age = new int;? Add age = 45; below the line int[] age = new int; but before the print statements? Add age = 25; below the line int[] age = new int; but before the print statements? Add age = 20; below the line int[] age = new int; but before the print statements? Change "Sister" within the String array to "Brother2"? important IMPORTANT Since the integer array above was created using the new method, 0 was populated as elements within the array at first. Then by setting the array indices to specific values, you were able to modify the array to include the appropriate age for each family member. Iterating an Array Array Iteration Though we can add many elements to our array, printing each of them can get quite tedious. For example, if we have 10 names of friends in our array, we would need to specify each of their array index to print them. String[] friends = {"Alan", "Bob", "Carol", "David", "Ellen", "Fred", "Grace", "Henry", "Ian", "Jen"}; System.out.println(friends); System.out.println(friends); System.out.println(friends); System.out.println(friends); System.out.println(friends); System.out.println(friends); System.out.println(friends); System.out.println(friends); System.out.println(friends); System.out.println(friends); Luckily, we can use loops which we had learned previously to help us with this process. To print out all of our friends’ names without repeating the print statement ten times, we can use a for loop to iterate 10 times. String[] friends = {"Alan", "Bob", "Carol", "David", "Ellen", "Fred", "Grace", "Henry", "Ian", "Jen"}; for (int i = 0; i < 10; i++) { System.out.println(friends[i]); } challenge What happens if you: Change System.out.println(friends[i]); in the code above to System.out.println(friends);? Change System.out.println(friends[i]); in the code above to System.out.println(friends);? important IMPORTANT Did you notice that the print statement above includes i as the index for friends? We do this because i will take on the values specified by the for loop. The loop starts at 0 and increments by 1 until it reaches 9 (not including 10). Thus, friends will print, then friends, so on and so forth until friends is printed. Then the loop ends. Array Length To make the iteration process easier, we can use an instance variable called length to determine how many elements are in our array. To use length, just call it by adding a period. after our array followed by length. For example, friends.length will tell us how many elements are in our friends array. The advantage of using length is that we can initialize additional elements in our array without having to keep track of how many elements are already inside. String[] friends = {"Alan", "Bob", "Carol", "David", "Ellen", "Fred", "Grace", "Henry", "Ian", "Jen"}; for (int i = 0; i < friends.length; i++) { System.out.println(friends[i]); } challenge What happens if you: add "Kate" as an element to the array right after "Jen"? remove "Alan" and "Bob" from the array? Notice how friends.length continues to keep track of how many elements are in our array even though we’ve made several changes. Enhanced For-Loop Using an Enhanced For-Loop There is a special type of for loop that can be used with arrays called an enhanced for loop. An enhanced for loop, also known as a for each loop, can be used to iterate through array elements without having to refer to any array indices. To use an enhanced for loop, you need the following: * The keyword for followed by parentheses (). * A typed iterating variable followed by colon : followed by the array name. * Note that the iterating variable must be of the same type as the array. * Any commands that repeat within curly braces {}. * Note that when using an enhanced for loop, you can print the iterating variable itself without using brackets []. String[] friends = {"Alan", "Bob", "Carol", "David", "Ellen", "Fred", "Grace", "Henry", "Ian", "Jen"}; for (String i : friends) { System.out.println(i); } challenge What happens if you: change System.out.println(i); in the code above to System.out.println(friends[i]);? change String i in the code above to int i? important IMPORTANT One of the main differences between a regular for loop and an enhanced for loop is that an enhanced for loop does not refer to any index or position of the elements in the array. Thus, if you need to access or modify array elements, you cannot use an enhanced for loop. In addition, you cannot use an enhanced for loop to iterate through a part of the array. Think of an enhanced for loop as an all-or- nothing loop that just prints all of the array elements or nothing at all. Also note that the iterating variable type must match the array type. For example, you cannot use for (int i : friends) since friends is a String array and i is an integer variable. Use for (String i : friends) instead. Helpful Array Algorithms Array Algorithms In addition to being used with loops, arrays can also be used with conditionals to help with tasks such as searching for a particular element, finding a minimum or maximum element, or printing elements in reverse order. Searching for a Particular Element String[] cars = {"Corolla", "Camry", "Prius", "RAV4", "Highlander"}; String Camry = "A Camry is not available."; //default String value for (String s : cars) { //enhanced for loop if (s.equals("Camry")) { //if "Camry" is in array Camry = "A Camry is available."; //variable changes if "Camry" exists } } System.out.println(Camry); //print whether Camry exists or not challenge What happens if you: delete "Camry" from the cars array? try to modify the code above so that the algorithm will look for Prius in the array and will print A Prius is available. if Prius is an element and A Prius is not available. if it is not an element. Sample Solution String[] cars = {"Corolla", "Camry", "Prius", "RAV4", "Highlander"}; String Prius = "A Prius is not available."; for (String s : cars) { if (s.equals("Prius")) { Prius = "A Prius is available."; } } System.out.println(Prius); Finding a Minimum or Maximum Value int[] grades = {72, 84, 63, 55, 98}; int min = grades; //set min to the first element in the array for (int i : grades) { //enhanced for loop if (i < min) { //if element is less than min min = i; //set min to element that is less } } //elements are not modified so enhanced for loop can be used System.out.println("The lowest grade is " + min); //print lowest element challenge What happens if you: replace 72 in the int array with 42? try to modify the code so that the algorithm will look for the maximum element instead? Sample Solution int[] grades = {72, 84, 63, 55, 98}; int max = grades; for (int i : grades) { if (i > max) { max = i; } } System.out.println("The highest grade is " + max); Printing Elements in Reverse Order String[] letters = {"A", "B", "C", "D", "E"}; //start at index 4, then decrement by 1 until i < 0, then stop for (int i = letters.length - 1; i >= 0; i--) { System.out.println(letters[i]); } //regular for loop needed to access each element index Formative Assessment 1 Formative Assessment 2 Learning Objectives: ArrayLists Create an empty ArrayList Add and remove ArrayList elements Get and set ArrayList elements Iterate through ArrayLists using both a regular for loop and an enhanced for loop Determine ArrayList output Determine key differences between ArrayLists and arrays Creating an ArrayList What Is an ArrayList? Although arrays are very useful for data collection, they are considered static, meaning once they are created, you cannot add or remove elements from them without changing the way they are initialized. ArrayLists, on the other hand, are dynamic, meaning you can make changes to them while the program is running. ArrayLists are particularly helpful when you don’t know how large your collection of elements will become. Since ArrayLists are dynamic, you can add and remove elements later on if needed. In order to use ArrayLists, you must import it using import java.util.ArrayList; in the header of your program. For convenience, the program file to your left already contains the import statement. ArrayList Creation To create an ArrayList, you need to include the following: * The keyword ArrayList followed by the data type in angle brackets. * Note that unlike arrays, ArrayList types are labeled slightly differently (e.g. Integer, Double, Boolean, and String). * A variable name that refers to the ArrayList. * The assignment operator = followed by the keyword new. * Another ArrayList keyword followed by the data type in angle brackets followed by empty parentheses (). ArrayList numbers = new ArrayList(); System.out.println(numbers); important IMPORTANT Unlike printing arrays, printing an ArrayList will output its elements instead of its memory address. When an ArrayList is initialized, it is empty by default. This is why printing a new ArrayList results in empty brackets []. Determining ArrayList Size ArrayLists use the method size() to determine the number of elements that exist instead of length which is used for arrays. When an ArrayList is initially created, its size is automatically 0 since all new ArrayLists are empty by default. ArrayList numbers = new ArrayList(); System.out.println(numbers.size()); Adding and Removing Elements Adding ArrayList Elements To add elements to the ArrayList, simply use the add() method. The add() method will add whatever element that is specified inside parentheses () to the end of the ArrayList by default. If an element is added to an empty ArrayList, that element will be the first and only element in the ArrayList. ArrayList numbers = new ArrayList(); numbers.add(50); //add 50 as an element to end of ArrayList System.out.println(numbers); challenge What happens if you: add numbers.add(100); directly below numbers.add(50);? add numbers.add(12.3); below numbers.add(50); but before the print statement? important IMPORTANT Much like arrays, ArrayLists can only store one type of data. For example, you cannot store 12.3 into an Integer ArrayList. To add an element to a specific index in the ArrayList, you can use the add() method with two parameters inside the parentheses (). The first parameter is the index where you want the element to be stored at and the second parameter is the element itself. For example, numbers.add(0, 12) will add the number 12 to index 0 causing 12 to become the first element in the ArrayList. This will cause all of the elements to the right of 12 to move up by 1 index number. ArrayList numbers = new ArrayList(); numbers.add(50); numbers.add(100); System.out.println(numbers); numbers.add(0, 12); //add 12 as an element to index 0 System.out.println(numbers); challenge What happens if you: add numbers.add(2, 75); directly below numbers.add(0, 12);? add numbers.add(4, 250); below numbers.add(0, 12); but before the second print statement? add numbers.add(8, 320); below numbers.add(0, 12); but before the second print statement? important IMPORTANT Adding numbers.add(8, 320); produces the familiar IndexOutOfBoundsException error. This occurs because the ArrayList does not contain index number 8. However, you can add an element to the ArrayList if you specify the last available array index plus 1. For example, if the last available index is 3, then you can use numbers.add(4, 250); to add 250 to index 4 which did not exist previously. Removing ArrayList Elements To remove an element from an ArrayList, use the remove() method and specify the ArrayList index of the element you want to be removed as a parameter inside the parentheses (). Deleting an element will cause all elements to the right of that element to move down by 1 index number. ArrayList numbers = new ArrayList(); numbers.add(12); numbers.add(50); numbers.add(75); numbers.add(100); System.out.println(numbers); numbers.remove(2); //remove element at index 2 System.out.println(numbers); challenge What happens if you: add another numbers.remove(2); directly below numbers.remove(2);? add a third numbers.remove(2); directly below the other two numbers.remove(2);s? Getting and Setting Elements Getting ArrayList Elements To get or access ArrayList elements, use the get() method and include the index as a parameter inside parentheses (). ArrayList contact = new ArrayList(); contact.add("First name"); contact.add("Last name"); contact.add("Phone number"); System.out.println(contact.get(0)); //gets element at index 0 and prints challenge What happens if you: change contact.get(0) in the code above to contact.get(1)? change contact.get(0) in the code above to contact.get(2)? change contact.get(0) in the code above to contact.get(3)? Setting ArrayList Elements To set or modify ArrayList elements, use the set() method which includes two parameters within parentheses (). The first parameter specifies the ArrayList index and the second parameter specifies the element that will replace the current value at the index. For example, contact.set(2, "Email") will modify the element at index 2 and change it to Email. ArrayList contact = new ArrayList(); contact.add("First name"); contact.add("Last name"); contact.add("Phone number"); System.out.println(contact); contact.set(2, "Email"); //change element at index 2 to "Email" System.out.println(contact); challenge What happens if you: add contact.set(0, "Full name"); to the line directly before contact.set(2, "Email");? change contact.set(2, "Email"); in the code above to contact.set(1, "Address");? change contact.set(2, "Email"); in the code above to contact.set(3, "Alternative name");? important IMPORTANT Both get() and set() methods require that the ArrayList already has an element that exists at the specified index. Otherwise, the IndexOutOfBoundsException error will occur. Iterating an ArrayList Iterating ArrayList Elements Iterating through an ArrayList is very similar to iterating through an array. The main difference is that in an ArrayList, we use get() to access the elements instead of brackets []. Both of the code blocks below use a regular for to produce the exact same results. The first code block contains an array and the second contains an ArrayList. //iterating through an array int[] grades = {85, 95, 48, 100, 92}; for (int i = 0; i < grades.length; i++) { System.out.println(grades[i]); } //iterating through an ArrayList ArrayList grades = new ArrayList(); grades.add(85); grades.add(95); grades.add(48); grades.add(100); grades.add(92); for (int i = 0; i < grades.size(); i++) { System.out.println(grades.get(i)); } Enhanced For Loop in ArrayList We can also use an enhanced for loop to iterate through an ArrayList. //iterating an ArrayList with Enhanced For Loop ArrayList grades = new ArrayList(); grades.add(85); grades.add(95); grades.add(48); grades.add(100); grades.add(92); for (Integer i : grades) { //Integer is required instead of int! System.out.println(i); } important IMPORTANT When using an enhanced for loop for an ArrayList, you must label the iterating variable accordingly. Remember that ArrayLists use Integer, Double, and Boolean instead of int, double, and boolean. Only String is consistently labeled between ArrayLists and arrays. Therefore, for (Integer i : grades) is required instead of for (int i : grades). ArrayList vs. Array ArrayList vs. Array Which one is better: ArrayList or array? The answer is, it really depends. If you know how many elements you need in your collection and you don’t intend on changing the order of those elements, then it is better to use an array. On the other hand, if you don’t know how many elements you need and want to modify the order of elements later on, then it is better to use an ArrayList. Although an array is shorter to write and arguably easier to use, it is static, meaning it is not possible to add additional elements to the array after it has already been initialized. In contrast, an ArrayList is more dynamic, meaning you can add, remove, and reorganize elements as needed later on. Here is a table showing the differences between ArrayLists and arrays. Note that uppercase Type stands for compatible ArrayList types while lowercase type stands for compatible array types. Also note that var stands for ArrayList or array name, num stands for an integer number, index stands for index or position number, and element stands for an ArrayList or array element. Method/Types ArrayList Array type[] var = new type[num] ArrayList var = new Create or type[] var = {element, ArrayList() element…} Find number var.size() var.length of elements Access an var.get(index) var[index] element Modify and var.set(index, element) var[index] = element element Add an var.add(element) or n/a element var.add(index, element) Remove an var.remove(index) n/a element for (int i = 0; i < var.length; for (int i = 0; i < var.size(); i++) i++) for loop {System.out.println(var.get(i));} {System.out.println(var[i]);} Enhanced for for (Type i : var) for (type i : var) Enhanced for for (Type i : var) for (type i : var) loop {System.out.println(i)} {System.out.println(i)} Common Integer, Double, Boolean, int, double, boolean, compatible Strings Strings types Using Both an ArrayList and Array ArrayLists and arrays can be used in tandem with each other. For example, the following code keeps track of the top five students in a class. String[] top = {"First: ", "Second: ", "Third: ", "Fourth: ", "Fifth: "}; ArrayList names = new ArrayList(); names.add("Alan"); names.add("Bob"); names.add("Carol"); names.add("David"); names.add("Ellen"); for (int i = 0; i < 5; i++) { System.out.println(top[i] + names.get(i)); } challenge Without deleting any existing code, try to: switch Alan and Carol’s places. replace David with Fred. make Grace get “Fifth” place and remove Ellen from the list. Sample Solution String[] top = {"First: ", "Second: ", "Third: ", "Fourth: ", "Fifth: "}; ArrayList names = new ArrayList(); names.add("Alan"); names.add("Bob"); names.add("Carol"); names.add("David"); names.add("Ellen"); names.set(0, "Carol"); //switch Alan with Carol names.set(2, "Alan"); //and vice versa names.set(3, "Fred"); //Fred replaces David names.add(4, "Grace"); //Grace takes Ellen's place names.remove(5); //Ellen's "Sixth" place gets removed for (int i = 0; i < 5; i++) { System.out.println(top[i] + names.get(i)); } Helpful ArrayList Algorithms ArrayList Algorithms Like arrays, ArrayLists can be used to search for a particular element and to find a minimum or maximum element. Additionally, ArrayLists can reverse the order of elements rather than just simply printing the elements in reverse order. Searching for a Particular Element ArrayList cars = new ArrayList(); String Camry = "A Camry is not available."; //default String value cars.add("Corolla"); cars.add("Camry"); cars.add("Prius"); cars.add("RAV4"); cars.add("Highlander"); for (String s : cars) { //enhanced for loop if (s.equals("Camry")) { //if "Camry" is in ArrayList Camry = "A Camry is available."; //variable changes if "Camry" exists } } System.out.println(Camry); //print whether Camry exists or not challenge What happens if you: add cars.remove(1); to the line directly below cars.add("Highlander");? try to modify the code above so that the algorithm will look for Prius in the array and will print A Prius is available. if Prius is an element and A Prius is not available. if it is not an element. Sample Solution ArrayList cars = new ArrayList(); String Prius = "A Prius is not available."; cars.add("Corolla"); cars.add("Camry"); cars.add("Prius"); cars.add("RAV4"); cars.add("Highlander"); for (String s : cars) { if (s.equals("Prius")) { Prius = "A Prius is available."; } } System.out.println(Prius); Finding a Minimum or Maximum Value ArrayList grades = new ArrayList(); grades.add(72); grades.add(84); grades.add(63); grades.add(55); grades.add(98); int min = grades.get(0); //set min to the first element in the array for (int i : grades) { //enhanced for loop if (i < min) { //if element is less than min min = i; //set min to element that is less } } //elements are not modified so enhanced for loop can be used System.out.println("The lowest grade is " + min); //print lowest element challenge What happens if you: add grades.set(0, 42); to the line directly below grades.add(98);? try to modify the code so that the algorithm will look for the maximum element instead? Sample Solution ArrayList grades = new ArrayList(); grades.add(72); grades.add(84); grades.add(63); grades.add(55); grades.add(98); int max = grades.get(0); for (int i : grades) { if (i > max) { max = i; } } System.out.println("The highest grade is " + max); Reversing the Order of Elements ArrayList letters = new ArrayList(); letters.add("A"); letters.add("B"); letters.add("C"); letters.add("D"); letters.add("E"); int original = letters.size(); //original size //regular for loops needed to access element indices for (int i = letters.size() - 1; i >= 0; i--) { letters.add(letters.get(i)); } //add elements in reverse order to the ArrayList for (int j = 0; j < original; j++) { letters.remove(0); } //remove all the original elements System.out.println(letters); //print new ArrayList important IMPORTANT Note that we used letters.remove(0) rather than letters.remove(j) in the code above because remove() deletes both the element and the index. Thus, the next element in the ArrayList becomes the new 0th index which we want to continue to delete. Formative Assessment 1 Formative Assessment 2 Learning Objectives: 2D Arrays Create a 2D array using both the initializer list and new methods Access and modify 2D array elements Iterate through 2D arrays using both a regular for loop and an enhanced for loop Determine 2D array output Creating a 2D Array An Array Inside Another Array An array inside another array is called a 2D array. A 2D arrays is symbolic of a table where there are rows and columns. The first index number represents the row position and the second index number represents the column position. Together, the row and column indices enable elements to be stored at specific locations..guides/img/2DArray String[][] names = new String; 2D Array Syntax array type followed by two empty brackets [][] followed by a name for the 2D array. The = operator followed by the keyword new followed by the array type and two brackets [][]. The number of rows goes inside the first bracket and the number of columns goes inside the second bracket. Why Array Inside Array? The way 2D arrays store elements is a little unique. Rather than creating an actual table like shown above, each initial row of the 2D array actually refers to another column array. This is why a 2D array is considered to be an array inside of another array..guides/img/2DArrayReference To determine the number of rows and columns in the 2D array, we can use the instance variable length like we did for arrays. String[][] names = new String; System.out.println(names.length + " rows"); System.out.println(names.length + " columns"); important IMPORTANT Note that when determining column length, you must refer to the 2D array’s initial row index. For example, names.length will calculate how many elements are inside row index 0 and these elements determine how many columns there are in the row. Accessing and Modifying a 2D Array 2D Array Access To access and modify elements inside a 2D array, you need to specific the row and column indices at which the elements are located. For example names refers to the element that’s at row index 1 and column index 2..guides/img/2DArray Below is a code block showcasing a 2D array that contains fifteen P.O. Box names from a postal office. Note that you can use the initializer list method to populate elements inside your 2D array. Each column array is separated by curly braces {} as well as a comma ,. String[][] names = { {"Alan", "Bob", "Carol", "David", "Ellen"}, {"Fred", "Grace", "Henry", "Ian", "Jen"}, {"Kelly", "Liam", "Mary", "Nancy", "Owen"} }; System.out.println(names); challenge What happens if you: change names within the print statement from above to names? change names within the print statement from above to names? important IMPORTANT Note that you will still get an ArrayIndexOutOfBoundsException error if you attempt to access or modify an element at a row or column index that does not exist. Like arrays, you cannot add additional rows or columns of elements to the 2D array after it has been initialized. 2D Array Modification To modify elements within a 2D array, simply access the element and assign another element to it. String[][] names = { {"Alan", "Bob", "Carol", "David", "Ellen"}, {"Fred", "Grace", "Henry", "Ian", "Jen"}, {"Kelly", "Liam", "Mary", "Nancy", "Owen"} }; System.out.println(names); names = "Harry"; System.out.println(names); challenge What happens if you: change all names within the code above to names? change "Harry" in the code above to "Amy"? Iterating a 2D Array 2D Array Iteration To iterate through a 2D array, we can use two for loops, one nested inside another. The outer for loop is for the rows while the inner for is for the columns. int[][] digits = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; for (int i = 0; i < digits.length; i++) { for (int j = 0; j < digits.length; j++) { System.out.println(digits[i][j]); } } challenge What happens if you: change digits.length in the inner for loop to digits.length change println in the print statement to print? Note that all of the rows’ lengths are the same, they each have three elements. Therefore, it doesn’t matter if we use digits.length, digits.length, or digits.length. Also note that using println prints the elements vertically while print prints the elements horizontally. To print the elements so that the columns stay together but the rows separate, we can try something like this: int[][] digits = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; for (int i = 0; i < digits.length; i++) { for (int j = 0; j < digits.length; j++) { if (j == digits.length - 1) { System.out.println(digits[i][j]); } else { System.out.print(digits[i][j] + " "); } } } The if conditional forces the elements to be printed with a newline every time the iterating variable reaches the end of the column index. Otherwise, the elements will be printed with a space instead. 2D Array with Enhanced For Loop Like arrays and ArrayLists, 2D arrays can also make use of the enhanced for loop. int[][] digits = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; for (int[] i : digits) { for (int j : i) { if ((j == 3) | (j == 6) | (j == 9)) { System.out.println(j); } else { System.out.print(j + " "); } } } Note that we cannot use an enhanced for loop to manipulate array indices. Our iterating variable goes through the 2D array and takes on each element value rather than each element index. This is why we have the conditional statement if ((j == 3) | (j == 6) | (j == 9)) rather than if (j == digits.length - 1). Additionally, since we have an array inside of another array, our iterating variable i is of type int[] rather than just int. Formative Assessment 1 Formative Assessment 2 The Java Documentation Tool The Java Development Kit (JDK) contains a Javadoc tool that takes the information in the comments of a Java file and generates an HTML page with documentation for that file. For more detailed information, you may visit the Javadoc website. The Javadoc tool recognizes comments it should use by the extra asterisk at the opening of a multi-line comment: Javadoc comments are typically placed above classes, methods or fields. The first part of the comment is the description followed by the block tags (beginning with @ sign) to describe meta data. The description should go beyond a repeat of the name of the class or method. Javadoc style conventions: - The first line contains the opener for a Javadoc comment Best practices for documenting Java code Every class and method should be preceded by a Javadoc style comment Class comments should contain: - The - The - The Method comments should contain: - The - An - A if there is one or a comment to the effect that nothing is returned. -A Generate the JavaDoc Paste the following command in the terminal window javadoc BookReader.java -d jdoc Open up the generated document and answer the question below. Javadoc Tags The Javadoc tool recognizes a set of tags when they are inside a Javadoc type comment (starts with \**). All tags must start with a @ sign and are case sensitive (must follow the casing in the list below). The tag must be the first thing in a line, leading spaces or a preceding (optional) asterisk are okay. More information about tags may be found here. There are two types of tags: - Block tags - these start with an @ sign and must be in the tag section after the main description - Inline tags - inline tags are surrounded by curly braces. They can be anywhere in the main description or in the comments for the block tags. Tag Ordering The following is the ordering convention: 1. @author (classes and interfaces only, required) 2. @version (classes and interfaces only, required) 3. @param (methods and constructors only) 4. @return (methods only) 5. @exception (or @throws) 6. @see 7. @since 8. @serial (or @serialField or @serialData) 9. @deprecated Order of multiple tags if the same kind Tags with the same name are grouped together and follow these conventions: @author tags should be listed chronologically, the creator of the class should appear at the top. @param tags should be listed in the order they are declared in. @exception tags (also known as @throws) should be listed alphabetically by their exception name. @see tags should be from nearest to farthest access and from least- qualified to fully-qualified. Tags and their purpose Tag (value) Purpose Creates an author entry. You can @author name create multiple author entries or one with multiple names Display the text provided in code font {@code text} and as it is, not interpreted. Used to specify the relative path of {@docRoot} the doc’s root directory You can use this tag in any of the doc comments for: overview, package, @deprecated explanation class, interface, constructor, method and field @exception class-name The class-name is the exception that description may be thrown by the method. Copies documentation from the {@inheritDoc} nearest inheritable class Inserts an in-line link with a visible {@link package.class#member text label that points to the label} documentation for the specified package Similar to @link but the label is in {@linkplain} text format Display the text provided as is, not {@literal text} interpreted. Adds a parameter with the specified parameter-name followed by the @param name description specified description to the “Parameters” section Creates a Returns section with the @return description description text @see string The quoted string is displayed as is @see Java Adds the defined link Spec Adds a link, with a text label, that @see package.class#member points to the documentation for the label specified name referenced in the argument @serial field-description Used in the doc comment for a (include or exclude) default serializable field. Documents the types and order of @serialData data-description data in the serialized form @serialField field-name field- Documents an ObjectStreamField type field-description component Documents that the change or @since since-text feature has existed since the release specified by the since-text @throws Same as @exception Can display the value of the specified {@value} package.class#field argument Adds a “Version” subheading with @version version-text the specified version-text to the generated docs Classes vs Objects (MOD-1.B.1, MOD-1.B.2) Vocabulary The words “class” and “object” are used in an almost interchangeable manner. There are many similarities between classes and objects, but there is also an important difference. Classes - Classes are a collection of data and the actions that can modify the data. Programming is a very abstract task. Classes were created to give users a mental model of how to think about data in a more concrete way. Classes act as the blueprint. Objects - Objects are constructed according to the blueprint that is the class. Instance - Another way that programmers talk about objects is to say that an object is an instance of a particular class. Trying it out with Turtles There is a Turtle class that is a blueprint allowing you to easily create Turtle objects. The first Turtle object has been created in the code file in the top-left. Click the button below to see the created Turtle. Note: To “end” Turtle programs, you will need to close the application in the bottom-left pane, then close the terminal in the top-left: Let’s create a second Turtle object: //Creating Turtle 2 Turtle t2 = new Turtle(-150,150); t2.fillColor(Color.blue); Copy the above code onto Line 12 in the top-left pane. If you compare the code for the second turtle to the code for the first turtle, you will notice that the will appear below the : You will also notice that the. Try creating more turtles Try making a pink third turtle, t3, at position -200,200 Try making a yellow fourth turtle, t4, at position -200,150 Class Attributes (MOD-1.B.1) Class Attributes In the previous example, you might have noticed that to refer to a color, we used Color. before the color name. That’s because Java has a Color class which defines colors for us. info A class attribute is a variable associated with that class. You can access attributes like variables – but you have to also say what class owns the attribute. The syntax is className.attributeName – like Color.yellow. The Color class has a list of attributes or fields that represent a lot of the colors – this makes it easier for us to color turtles without having to represent colors in RGB or Red Green and Blue format. What is RGB? The RGB color model is an additive color model in which red, green, and blue light are added together in various ways to reproduce a broad array of colors. The main purpose of the RGB color model is for the display of images in electronic systems, such as televisions and computers.This widget let’s you see how you can specify a color using the RGB values. Try it out With the Color class, the attributes mapping colors to RGB values stay the same. However, each of the turtles you made on the last page have different fillColor attributes. Try printing out the different attributes for each turtle by pasting this on line 24. System.out.println("Turtle 1 is green or " + t1.fillColor); System.out.println("Turtle 2 is blue or " + t2.fillColor); System.out.println("Turtle 3 is pink or " + t3.fillColor); System.out.println("Turtle 4 is yellow or " + t4.fillColor); Instantiation (MOD-1.D.1, MOD- 1.D.2, MOD-1.D.3, VAR-1.D.1) In the previous lesson, we created Turtle objects. info Instantiation is the process of creating a new object from a class Every time you instantiate or create an object, you will use the keyword new. For example: Turtle t1 = new Turtle(); If you remember back to variables, this is actually two steps: Turtle t1; t1 = new Turtle(); If an object has been declared but not intialized (i.e. Turtle t1;) then is called null. info The keyword null is a special value used to indicate that a reference is not associated with any object. The second piece (t1 = new Turtle();) is actually calling the constructor. That’s why the first Turtle has no paranthesis but the second one does – the first one is simply stating what type of data is in t1 - the second is calling a special method called a constructor (which is discussed on the next page). You won’t have to guess the name of the method to instantiate an object – constructors always have the same name as the class. For example, to invoke the Color constructor you would do Color red = new Color(255,0,0);. At this point we have talked about the Color class and the Turtle class – both of which you did not write. When you write code, you don’t have to start from nothing every time. Existing classes and class libraries can be utilized as appropriate to create objects. Some of the most common (String, Integer, Double, Math and ArrayList) are listed on the AP Java Quick Reference Sheet so you don’t have to memorize them but can use them when you write code on the AP exam. Default Constructor (MOD-1.D.1, MOD-1.D.2, VAR-1.D.1, VAR-1.D.2) The constructor is a special method (more on methods in another lesson) for a class. Its job is to define all of attributes associated with the object. In Java, the constructor always has the same name as the class. Use the visualizer on the left to see how the program executes. (If you get any kind of error, click the Refresh Code button in the top left). As you click the “Forward” button, notice on the following steps… Step 3: The program jumps from line 6 to line 19 because the new Turtle() calls the constructor There is an empty framework of a Turtle object created on the right with the class attributes The default value for int is 0 The fillColor attribute has not been set, and since it’s a Color object it is set to null Step 11: The t1 object has the defualt values set in the default constructor Since fillColor is an Object, there is a reference/arrow instead of a value Since x and y are primitives, there is a value instead of a reference/arrow Step 21: t1.x = 50 only effects the t1 object Step 22: t2.y = 200 only effects the t2 object The real Turtle constructor actually has a lot more attributes: public Turtle() { location=new Point2D.Double(0,0); direction=0; //degrees shape="turtle"; //Stores a key to the shapes hashmap image=null; shapeWidth=33; shapeHeight=33; penWidth=2; penColor=Color.BLACK; outlineWidth=2; outlineColor=Color.BLACK; fillColor=new Color(0,255,0,128); speed=50; //milliseconds to execute a move isPenDown=true; isFilling=false; isVisible=true; } Parameters (MOD-1.C.1 - MOD-1.C.6, MOD-1.D.4) Previously, we made a number of turtles – and we set their location when we instatiated them. This is because the Turtle class has two constructors. The one on the previous page is called the default constructor, meaning it makes a default turtle with no custom information. There is a second constructor that looks like: public Turtle(double x,double y) { location=new Point2D.Double(x,y);.... } You’ll notice that unlike the previous constructor, this constructor has parameters. Instead of just setting the location to an arbitrary point, the user tells the constructor where to put the turtle. info Parameters are how you can pass information into methods and constructors. Use the visualizer on the left to see how the example program executes. (If you get any kind of error, click the Refresh Code button in the top left). As you click the “Forward” button, notice on the following steps… Step 3: The program jumps from line 5 to line 17 because the new Turtle() calls the default constructor There is an empty framework of a Turtle object created on the right with the class attributes The default value for int is 0 The fillColor attribute has not been set, and since it’s a Color object it is set to null Step 11: The t1 object has the defualt values set in the default constructor Since fillColor is an Object, there is a reference/arrow instead of a value Since x and y are primitives, there is a value instead of a reference/arrow Step 12: The program jumps from line 6 to line 28 because the new Turtle(200, 200, Color.BLACK); calls the constructor with the signature that matches (public Turtle(int x1, int y1, Color col)) Step 15: fillColor is set using the col parameter Steps 16 and 17: x and y are set to 200 instead of the default values because of the values passed through the constructors parameters Step 20: fillColor for t2 is a DIFFERENT color object than t1 since t1 is green and t2 is black. Step 21: The program jumps from line 7 to line 23 because the new Turtle(300, 300); calls the constructor with the signature that matches (public Turtle(int x1, int y1)) Step 24: The fillColor attribute is set to the same color object as t1 Steps 25 and 26: x and y are set to 300 instead of the default values because of the values passed through the constructors parameters The Java program knows which constructor to used based on it’s signature. A signature consists of the constructor name and the parameter list. In the example above, you can see how in steps 3, 12 and 21 the values in the instantiation step are being matched to the constructor with matching parameters. info To clarify, prorgrammers often call the parameter list, in the header of a constructor, which lists the types of the values that are passed and their variable names, formal parameters. In contrast, programmers often call the parameter value that is passed into a constructor actual parameters or arguments. So int x1, int y1 are the formal paramenters while (300,300) are the actual parameters Parameters are passed using call by value. Call by value initializes the formal parameters with copies of the actual parameters. Methods (MOD-1.E.1 - MOD-1.E.4, MOD-1.E.6, MOD-1.E.7) Up to this point we have focused on how to create or instantiate objects and an object’s attributes. Objects also have behaviors. What the object can do (or what can be done to it) is defined by methods. We’ve actually already used methods with the Turtle class. When we were setting the fillColor, we were using a method: Turtle t1 = new Turtle(); t1.fillColor(Color.blue); The Turtle class has a method with the signature fillColor(Color) that allows us to change the Turtle color. Similar to attributes, methods start with the object name: objectName.methodName(). Check out the code on the left – it has a turtle draw a square. Reminder on how to close a Turtle program How do we know the turtle will draw a square instead of random lines? A method (or constructor) call interrupts the sequential execution of statements, causing the program to first execute the statements in the method (or constructor) before continuing. Once the last statement in the method (or constructor) has executed, flow of control is returned to the point immediately following where the method (or constructor) was called. In other words - the program finishes each line in order. It won’t go to the next line until it has finished the method call on the current line. Try out some of these other Turtle methods: Method Description forward() Move the turtle forward 10 pixels backward() Move the turtle backward 10 pixels right() Turn the turtle to the right 90 degrees left() Turn the turtle to the left 90 degrees Taking a look at the list of methods above, notice three things: 1. Programmer can use a method by knowing what the method does even if they do not know how the method was written. This is sometimes refered to as procedural abstraction 2. A method signature for a method without parameters consists of the method name and an empty parameter list () 3. All of these methods do things – but they do not return values. Methods that do not return a value are called void methods. More Methods (MOD-1.E.5, MOD- 1.E.8, Skill 3.A) All of these Turtle methods are called through objects. These methods are non-static methods. That means these methods are only available when the object is avaiable. Try running this code: t.forward(); Turtle t = new Turtle(); You get an error because t has not yet been instatiated when t.forward() is run. You will also get an error if you have a null object. Try running this code: Turtle t = null; t.forward(); t = new Turtle(); You should see something on the terminal that looks like: Exception in thread "main" java.lang.NullPointerException at MoreMethods.main(MoreMethods.java:7) This Null Pointer Exception is thrown when using a null reference to call a method or access an instance variable/attribute. Void Methods with Parameters (MOD-1.F.1, MOD-1.F.2, MOD-1.F.3, Skill 2.C) In the last lesson we learned how to make our turtles draw! |Method|Description| |:—–:|:———:| |forward()|Move the turtle forward 10 pixels| |backward()|Move the turtle backward 10 pixels| |right()|Turn the turtle to the right 90 degrees| |left()|Turn the turtle to the left 90 degrees| The methods we learned in the last lesson are acutally overloaded. You can use them with parameters for more flexibility. definition Overloaded Methods are said to be overloaded when there are multiple methods with the same name but a different signature. In the table below we see a second method signature, but you can have even more methods with the same name (as long as the method signature is unique). Command Parameter Description Where n represents the forward(n) Move the turtle forward number of pixels Where n represents the backward(n) Move the turtle backward number of pixels Where d represents the right(d) Turn the turtle to the right number of degrees Where d represents the left(d) Turn the turtle to the left number of degrees Try out the code on the left which draws a triangle. Reminder on how to close a Turtle program Experiment with the turtle methods. You can also speed up or slow down your turtle using the speed(double delay) method. The longer the delay, the slower your turtle will draw. The default speed is 50ms. If you need to pick up() or put down() your turtle pen, there are methods for that too! Method Signatures A method signature for a method with parameters consists of the method name and the ordered list of parameter types. Just like constructors, when you are calling a method, the actual parameters or arguments must match the type and order of the formal parameters in the method header. For example, the turtle method: public void setPosition(double x, double y, double direction) {...} Even though there are 3 doubles, we know what order to list them in because of the method header. Non-void Methods (MOD-1.G.1, Skill 1.C) Non-void methods return a value that is the same type as the return type in the signature. To use the return value when calling a non-void method, it must be stored in a variable or used as part of an expression. A couple of non-void or return functions in the Turtle class: * public double getX() * public double getY() * public double towards(double x, double y) Check out how they are used in the code to the left to draw a parabola. Reminder on how to close a Turtle program.guides/img/closingTurtlePrograms The code consists of the same code over and over again: t.setPosition(t.getX()+1, (t.getX()+1)*(t.getX()+1), //increment X and set Y to X^2 t.towards(t.getX()+1, (t.getX()+1)*(t.getX()+1)) ); //use towards to face turtle Leap Frog Enjoy the slightly modified version of leap frog! Feel free to modify it – changing the multiplier effects how far they jump. Creating a String (VAR-1.E.1, VAR- 1.E.2) Back in Unit 1, we saw Strings. While int, double, and boolean from Unit 1 are primitive types, String is an object. Try instantiating it with it’s default constructor: String test = new String(); System.out.println(test); Similar to Turtle, the String constructor is overloaded. Another constructor has the signature public String(String original). Try out this construtor: String test = new String("test"); System.out.println(test); Because Strings are so common, there is some syntactical sugar to make this process as easy as it is for primitives: String test = "test2"; System.out.println(test); info Strings are immutable meaning that String methods do not change the String object. Concatenation (VAR-1.E.3, VAR- 1.E.4, Skill 2.A) info Concatenation is the joining of two Strings. For example, “Computer” concatenated with “Science!” would be “Computer Science!” You can concatenate Strings using the + operator. Try it out: String first = "Computer "; String second = "Science!"; System.out.println(first+second); You might have realized, this means that the + operator is overloaded! Java knows if you are doing int + int or String + String): String one = "1"; String two = "2"; System.out.println(one+two); int oneInt = 1; int twoInt = 2; System.out.println(oneInt+twoInt); You can even use the += operator with Strings: String first = "Computer "; first += "Science!"; System.out.println(first); Finally, you can concatenate Strings with primitives (int, double, and boolean): String first = "Computer "; first += "Science is #"; first += 1; System.out.println(first); Escape Sequences (VAR-1.E.5) Strings can mess up certain characters. Try to print out this quote: “Computer Science is no more about computers than astronomy is about telescopes.” — Dijkstra System.out.println(" "Computer Science is no more about computers than astronomy is about telescopes." — Dijkstra "); info Escape sequences start with a and have a special meaning in Java. Escape sequences used in this course include ”, \, and. Now try escaping the quotation marks: System.out.println("\"Computer Science is no more about computers than astronomy is about telescopes.\" - Dijkstra"); Escaping removes or adds special meaning. For example, you can use \n to create a new line: System.out.println("\"Computer Science is no more about computers \n than astronomy is about telescopes.\" \n - Dijkstra"); Similarly, because \ signifies escape characters, you need to escape it as well: System.out.println("The escape character is \\"); APIs and Libraries (VAR-1.E.6 - VAR-1.E.9) Application program interfaces (APIs) and libraries simplify complex programming tasks. Strings are pretty complex, but because they are so useful, there is a library to handle them. Documentation for APIs and libraries are essential to understanding the attributes and behaviors of an object of a class. For Java, most of the documentation for the most common libraries can be found on the Oracle website. Classes in the APIs and libraries are grouped into packages. This heirarchy will be important later – for now just know that there are helpful bundles of libraries called packages. If you take a look at the documenation for the String class (pane on the left), you’ll notice: * the String class is part of the java.lang package (which is available by default) * the Field section lists String class attributes * the Constructor section lists the different constructor signatures * the Methods section lists the different methods you can use with Strings Let’s try out some of these String methods! String methods (VAR-1.E.10, VAR- 1.E.12, VAR-1.E.13) String indeces Strings are treated as a list of characters. A String object has index values from 0 to length – 1..guides/img/StringIndices You can access a subset or part of a String, called a substring, using the indices: String test = "Hello World!"; System.out.println(test.substring(0,5)); //characters at indeces 0-4 System.out.println(test.substring(6)); //characters at indeces 6-end You can see from the AP Java Quick Reference sheet that the substring method is overloaded. You can either specify both the start and end, or just the start (and the substring goes until the end of the string). Attempting to access indices outside this range will result in an IndexOutOfBoundsException: String test = "Hello World!"; System.out.println(test.substring(0, 13)); If you want to access a character at location index, you can use substring(index, index + 1): String test = "Hello World!"; System.out.println(test.substring(4, 5)); //gets character at index 4 More String Methods Let’s try out the rest of the methods listed on the Quick Reference sheet: String(String str) Constructs a new String object that represents the same sequence of characters as str: String test = new String("this is a constructor"); System.out.println(test); int length() Returns the number of characters in a String object: String test = "Hello World!"; System.out.println("The string \""+test+"\" has " + test.length() + " characters"); int indexOf() Returns the index of the first occurrence of str; returns -1 if not found String test = "Hello World! I am a computer :)"; System.out.println(test.indexOf("computer")); boolean equals(String other) Returns true if this is equal to other; returns false otherwise String test = "Hello World!"; System.out.println(test.equals("Hello World!")); int compareTo(String other) Returns a value < 0 if this is less than other; returns zero if this is equal to other; returns a value > 0 if this is greater than other String test = "Hello World!"; System.out.println(test.compareTo("Hello Universe!")); toString (VAR-1.E.11) Objects often hold complex data. However, all objects have a toString() method which attempts to represent the object as a String: Integer four = new Integer(4); Integer three = new Integer(3); System.out.println(four.intValue() + three.intValue()); System.out.println(four.toString() + three.toString()); A String object can be concatenated with an object, which implicitly calls the referenced object’s toString method: Integer four = new Integer(4); Integer three = new Integer(3); System.out.println("The value of four is " + four); System.out.println("The value of three is " + three); Integer class (VAR-1.F.1, VAR-1.F.2, Skill 2.C) After the last lesson, you can probably guess why this code does not print “8”: int a = 5; String b = "3"; System.out.println(a + b); However, you can convert b to an integer to fix the problem. int a = 5; String b = "3"; System.out.println(a + (new Integer(b)).intValue()); The Integer class, part of the java.lang package, has some helpful methods - including intValue(). Integer class Methods Integer(int value) - constructor Constructs a new Integer object that represents the specified int value Integer two = new Integer(2); Integer.MIN_VALUE and Integer.MAX_VALUE The minimum and maximum value represented by an int or Integer Integer min = new Integer(Integer.MIN_VALUE); Integer max = new Integer(Integer.MAX_VALUE); int intValue Returns the value of this Integer as an int System.out.println(two.intValue()); System.out.println(min.intValue()); System.out.println(max.intValue()); Double class (VAR-1.F.1, VAR-1.F.3, Skill 2.C) The Double class, part of the java.lang package, has some helpful methods. Double(double value) Constructs a new Double object that represents the specified double value Double two = new Double(2.3); System.out.println(two); double doubleValue Returns the value of this Double as a double Double two = new Double(2.3); System.out.println(two.doubleValue() * 2); Autoboxing and Unboxing (VAR- 1.F.4 - VAR.1.F.7) Autoboxing info Autoboxing is the automatic conversion that the Java compiler makes between primitive types and their corresponding object wrapper classes. This includes converting an int to an Integer and a double to a Double. The Java compiler applies autoboxing when a primitive value is: * Passed as a parameter to a method that expects an object of the corresponding wrapper class. * Assigned to a variable of the corresponding wrapper class. For example: Integer two = 2; Double threeIsh = 3.4; Unboxing info Unboxing is the automatic conversion that the Java compiler makes from the wrapper class to the primitive type. This includes converting an Integer to an int and a Double to a double. The Java compiler applies unboxing when a wrapper class object is: * Passed as a parameter to a method that expects a value of the corresponding primitive type. * Assigned to a variable of the corresponding primitive type. For example: int two = new Integer(2); Static Math Methods (MOD-1.H.1, CON-1.D.1 - CON-1.D.3) For the last library of this unit, we are going to cover the Math class. The Math class is also part of the java.lang package. Unlike the previous classes we investigated, the Math class contains only static methods. This means we don’t need to instantiate a Math object to use them - they are ALWAYS available. Static methods are called with the syntax ClassName.MethodName. For example, Math.abs(-3) returns the absolute value of the argument. Try out the following Math methods: int abs(int x) Returns the absolute value of an int value System.out.println(Math.abs(-3)); double abs(double x) Returns the absolute value of an double value System.out.println(Math.abs(-3.5)); double pow(base, exponent) Returns the value of the first parameter, base, raised to the power of the second parameter, exponent System.out.println(Math.pow(2,0)); System.out.println(Math.pow(2,1)); System.out.println(Math.pow(2,2)); System.out.println(Math.pow(2,3)); System.out.println(Math.pow(2,4)); double sqrt(double x) Returns the positive square root of a double value System.out.println(Math.sqrt(16)); System.out.println(Math.sqrt(9)); System.out.println(Math.sqrt(4)); System.out.println(Math.sqrt(1)); Math.random (CON-1.D.3, CON- 1.D.4, Skill 1.B) Math.random() returns a double value greater than or equal to 0.0 and less than 1.0. While this seems a little odd, you can manipulate this range based on what you need. For example, to make the range 0 to 99 you simply multiply by 100: System.out.println((int) (Math.random()*100)); Tip: When playing with random numbers, run the program several times! If I want to shift the range to say, -25 to 25, then there is two steps: 1. Scale the range to 0 to 50 System.out.println((int) (Math.random()*50)); 2. Shift the range by -25 to get to -25 to 25 System.out.println((int) (Math.random()*50 - 25)); Random Turtle Enjoy the random Turtle program from the previous page – and feel free to explore! Print statments have been added so you can see how far the turtle is turning and walking. The turtle is also being set to a random color by generating random RGB values. Reminder on how to close a Turtle program Learning Objectives Recognize and understand the fundamental concepts of exceptions in Java, including the distinction between checked and unchecked exceptions Understand and implement the basic constructs of exception handling in Java, including the use of try, catch, and finally blocks. Handle exceptions using Java keywords ||| Info ## Make Sure You Know Understand Java Syntax Understanding Exceptions in Java What are Exceptions? In Java, exceptions are events that disrupt the normal flow of a program’s instructions. They are objects that encapsulate information about an error state or unexpected behavior encountered by the program. Understanding exceptions is crucial for writing robust and error-resistant Java applications. Java uses a class hierarchy to differentiate between different types of errors and exceptions. At the top of this hierarchy is the Throwable class, which has two main subclasses: Error and Exception. Error: Represents serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. Exception: Conditions that a program might want to catch. Let’s look at an example: classDiagram Throwable

Use Quizgecko on...
Browser
Browser