1 / 60

CISC101 - Last Time: Math class, Style and Documentation, Loops, and Exercises!

This lecture covers the topics from the last class, including math operations, coding style and documentation, loops, and exercises. It also introduces one-dimensional arrays, attributes, and methods in Java.

choia
Download Presentation

CISC101 - Last Time: Math class, Style and Documentation, Loops, and Exercises!

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Last Time • Math class • Style and Documentation • Loops • And Exercises! CISC101 - Prof. McLeod

  2. Announcements • Lecture exercise sample solutions for last lecture are posted. • Any questions on these? • We should have a midterm next week – how about Tuesday the 23rd? One hour tutorial followed by 2 hrs for exam? • Optional: bring a copy of Java syntax summary sheet. • All topics up to and including arrays. CISC101 - Prof. McLeod

  3. Today • “Warm-up” exercise to review loops. • Arrays – One dimensional and two dimensional. • Please read array notes linked off of Syllabus page. • More exercises (of course)! • Introduction to class structure: • Attributes • Methods CISC101 - Prof. McLeod

  4. Warm Up! • Print out the numbers between 0 and 200, inclusive, by 20’s, one number per line. • Write the program three ways – using each type of loop, in turn. CISC101 - Prof. McLeod

  5. Warm Up – Cont. • You could get the same output without using a loop, but what a pain! Suppose you had to count to 2,000 instead? • You can write this program in a very inefficient way! CISC101 - Prof. McLeod

  6. Aside - Efficient Code • We have talked about coding style and documentation. • The compiler does not care about how efficient your code is either. • Who does care? • “Efficiency” is all about execution time: Try to write code that accomplishes your purpose with the minimum number of instructions, provided you have not greatly compromised the readability of your program. CISC101 - Prof. McLeod

  7. Aside – Memory Efficiency? • These days our computers have so much RAM, we are not so concerned about being memory efficient. • But: • Declaring an excess number of variables makes your program harder to read, as well as using up excess memory. • Overly large programs are also harder to debug – Modular coding can lead to more efficient code that is also easier to write, debug and re-use. CISC101 - Prof. McLeod

  8. One-Dimensional Arrays • An array is just a collection of items, stored in computer memory (RAM). • In Java: • The items must all be of the samebase type. • Can be of any primitive type or object. • The size of the array must be declared before any items can be stored. • The size of the array cannot be changed after declaration. • An array occupies a contiguous memory space. • Array elements are numbered from zero. CISC101 - Prof. McLeod

  9. One-Dimensional Arrays - Cont. • The use of arrays in memory offers great speed advantages over processing data in and out of files. • File operations are always much slower than operations dealing only in RAM. • Typically, you will write array programs to: • Read values from a file. • Carry out all the calculations and manipulations required, in memory. • Save the data back to another file. • Arrays make it much easier to carry out the same calculation on many values. CISC101 - Prof. McLeod

  10. One-Dimensional Arrays - Declaration • For example, to create an array to hold 10 integers: int[] testArray = new int[10]; • testArray now points to an area of memory that holds locations for 10 integers. • It also points to one location that holds testArray.length which is an attribute of the array, that is equal to the number of elements. • Arrays are Objects in Java. CISC101 - Prof. McLeod

  11. Aside – New Java Keywords? • The declaration and use of arrays does not require us to learn any new Java keywords. • The only new thing are the square brackets [ ]. CISC101 - Prof. McLeod

  12. One-Dimensional Arrays - Declaration, Cont. 0 0 0 0 0 0 0 0 0 0 0480ff 0180ff … int[] testArray 0480ff • As a “pointer”, testArray points to an area of memory that contains a series of int values as well as the attribute length. 10 .length CISC101 - Prof. McLeod

  13. One-Dimensional Arrays - Declaration, Cont. • The java statement above can be split into two: int[] testArray; testArray = new int[10]; • The first statement creates a variable of type int[] - that is to say that it will be an array of int’s. • The variable, testArray is now an object of type int[] that contains an “object reference” or a pointer. The object reference is null after the first statement. CISC101 - Prof. McLeod

  14. One-Dimensional Arrays - Declaration, Cont. int[] testArray; testArray = new int[10]; • The second statement looks for a chunk of memory big enough to contiguously hold 10 integers (about 40 bytes), and then changes the object reference of testArray from null to the memory location of the chunk. • This assignment of the object reference of the testArray object is carried out by the “=“ assignment operator. • The new keyword is responsible for blocking out the memory space and initializing each memory location to the default value for a new memory location of type int (zero). CISC101 - Prof. McLeod

  15. One-Dimensional Arrays - Cont. • Back to the 10 array elements in memory: testArray[0] testArray[1] testArray[2] testArray[3] testArray[4] testArray[5] testArray[6] testArray[7] testArray[8] testArray[9] 0 0 0 0 0 0 0 0 0 0 testArray.length 10 CISC101 - Prof. McLeod

  16. One-Dimensional Arrays - Indices • The numbers 0 to 9 are called the index values of the array. The notation used above allows you to refer to individual elements. • Note that the elements of the array are numbered from zero. • arrayname.length returns the number of elements in the array. • length is an attribute of the array Object. CISC101 - Prof. McLeod

  17. One-Dimensional Arrays - Cont. • for loops are often used with arrays. For example, to initialize each of the elements of testArray to the value 1000 * i: int i; for (i = 0; i < 10; i++) testArray[i] = 1000 * i; • Arrays can also be initialized at declaration, using an “array initializer”. To get the same array as above: int[] testArray = {0, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000}; CISC101 - Prof. McLeod

  18. One-Dimensional Arrays - Cont. • Arrays can also be created using a variable (or constant) to specify the array size: final int MAX_SIZE = 1000; int[] testArray = new int[MAX_SIZE]; int size = testArray.length; // size is 1000 CISC101 - Prof. McLeod

  19. One-Dimensional Arrays - Cont. • All the examples so far, have been arrays of int’s. • Could be arrays of double’s, boolean’s or even String’s: (anything in fact, as long as all the array elements are the same “thing”) • For example (on the next slide): CISC101 - Prof. McLeod

  20. More Declaration Examples double[] dArray = new double[50]; String[] sArray = new String[100]; String[] sArray2 = {“Hi”, “Ho”, “Silver!”}; • Note that there is some flexibility in where the first set of “[]” goes. These two declarations are equivalent: double[] disNDat = new double[1000]; double disNDat[] = new double[1000]; CISC101 - Prof. McLeod

  21. One-Dimensional Arrays - “Out-of-bounds” Error • If n is the size of the array, then: • Array indices (or “subscripts”) < 0 or  n are illegal, since they do not correspond to real memory locations in the array. • These indices are said to be out-of-bounds. • Reference to an out-of-bounds index produces an out-of-bounds exception, and the program will crash if the exception is not caught. CISC101 - Prof. McLeod

  22. One-Dimensional Arrays - “Out-of-bounds” Error, Cont. • Example: // Declare and initialize array int a[] = {1,2,3,4,5}; // Write array to screen (with an error!) for ( int i = 0; i <= 5; i++ ) System.out.println("a[" + i + "] = " + a[i]); • On the screen: • a[0] = 1 • a[1] = 2 • a[2] = 3 • a[3] = 4 • a[4] = 5 • java.lang.ArrayIndexOutOfBoundsException: 5 • at TestBounds.main(TestBounds.java:15) CISC101 - Prof. McLeod

  23. One-Dimensional Arrays - Reminders • The “[]” brackets are used in three different ways, all associated only with arrays: • At declaration: • To specify the base type: int[] • To specify the size: int[10] • To refer to a single element: testArray[i] • The base type of an array can be any primitive type, such as int, double, etc., as well as String, or any object type. • Each array element must be of the same type. CISC101 - Prof. McLeod

  24. One-Dimensional Arrays - Reminders - Cont. • Remember that array elements are numbered starting from zero. So, the 10th element in an array called “myArray” is myArray[9]. Suppose myArray was declared to hold 1000 elements. If you try to access myArray[1000] you will get an “Array index out of bounds” error. CISC101 - Prof. McLeod

  25. Multi-Dimensional Arrays • Multi-dimensional arrays are just arrays of arrays. • For example, to create a two-dimensional array: int[][] twoDArray = new int[10][20]; Holds 200 elements. Initialize each element to the sum of its indices, for example: int i, j; for (i = 0; i < 10; i++) for (j = 0; j < 20; j++) twoDArray[i][j] = i + j; CISC101 - Prof. McLeod

  26. Multi-Dimensional Arrays - Cont. • Everything is the same as for one-dimensional arrays, except that you have a set of “[]” for each dimension. • Two-dimensional arrays are suitable for storage of a single type of data that would normally be viewed in a table with rows and columns. • Java does not place any limitation on the number of dimensions used in an array. CISC101 - Prof. McLeod

  27. Multi-Dimensional Arrays - Cont. • Consider: int[][] exArray = new int[3][5]; 1002fc 0 0 0 0 0 int[][] exArray 0480ff int[] exArray[0] 1002fc int[] exArray[1] 1010fc int[] exArray[2] 1201ab 1010fc 0 0 0 0 0 1201ab 0 0 0 0 0 CISC101 - Prof. McLeod

  28. Multi-Dimensional Arrays - Cont. • So exArray points to three one dimensional arrays: exArray[0] exArray[1] exArray[2] • Each of these arrays has the same length: exArray[2].length // returns 5 CISC101 - Prof. McLeod

  29. Multi-Dimensional Arrays - Cont. int[][] twoDArray = new int[10][20]; • The above is equivalent to: int[][] twoDArray; twoDArray = new int[10][]; for (int i = 0; i < 10; i++) twoDArray[i] = new int[20]; • As shown above: twoDArray.length // gives 10 twoDArray[0].length // gives 20 CISC101 - Prof. McLeod

  30. Multi-Dimensional Arrays - Cont. • “Ragged Arrays” are not “square” and are legal in Java: int[][] raggedArray = new int[5][]; raggedArray[0] = new int[2]; raggedArray[1] = new int[4]; raggedArray[2] = new int[6]; raggedArray[3] = new int[8]; raggedArray[4] = new int[10]; CISC101 - Prof. McLeod

  31. Multi-Dimensional Arrays - Cont. • Array initializer for two-D array, for example: int[][] twoDArray = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {10, 11, 12}}; System.out.println(twoDArray.length); // 4 System.out.println(twoDArray[0].length); // 3 CISC101 - Prof. McLeod

  32. Time for An Exercise! • Prompt the user for how many random numbers to generate (using Math.random()). Exit the program (use System.exit(0);) if the user enters a number < 1. • Generate and store these numbers in an array. • Calculate the mean of the array of numbers. • Count how many of these numbers are <= 0.5 . • Display the mean and the count <= 0.5 and > 0.5. CISC101 - Prof. McLeod

  33. Array Exercise 2 • Prompt the user for the number of columns and the number of rows of a 2D array. Both numbers must be > 2 (or just exit the program). • Generate and then display a 2D array of this size with the number 8 all around the outside and 1 everywhere else. • For example for 6 columns and 5 rows: 888888 811118 811118 811118 888888 CISC101 - Prof. McLeod

  34. Arrays as Objects - Example 5 int[] first = {1, 2, 3, 4, 5}; int[] second = {10, 20, 30, 40, 50, 60, 70}; 1 2 3 4 5 10 20 30 40 50 60 70 0480ff 0960ff int[] first 0480ff int[] second 0960ff .length .length 7 CISC101 - Prof. McLeod

  35. Arrays as Objects - Example Cont. 5 second = first; // Aliasing! 1 2 3 4 5 10 20 30 40 50 60 70 0480ff 0960ff int[] first 0480ff int[] second 0480ff .length .length 7 CISC101 - Prof. McLeod

  36. Arrays as Objects - Example Cont. 5 // after garbage collection 1 2 3 4 5 0480ff int[] first 0480ff int[] second 0480ff .length CISC101 - Prof. McLeod

  37. Arrays as Objects - Example Cont. 5 first[4] = 500; // second[4] is also 500 1 2 3 4 500 0480ff int[] first 0480ff int[] second 0480ff .length CISC101 - Prof. McLeod

  38. Arrays as Objects - Aliasing • So, setting one array to equal another as in: array1 = array2; sets array1 to point to the same data memory location that was (and still is) pointed to by array2. • Now, changing the value of an element in array2 will change that same element in array1, or visa-versa - this makes sense since both array Objects point to the same set of data values in memory! CISC101 - Prof. McLeod

  39. Arrays as Objects - Cont. • System.out.println() will print anything, but when it is used to print an Object, some interesting “gibberish” is produced! • Testing Objects for equality (with the “==“ boolean operator) is also interesting: • This test will only give a true when both objects have been aliased, using the assignment operator “=“. • So, even if both arrays have identical contents, “==“ will return false, unless both arrays point to the same location. • This means that comparing Objects with “==“ only compares pointers, not contents. CISC101 - Prof. McLeod

  40. Array Exercise 3 • Using array literals, create two arrays, array1 holding the numbers 1, 2, 3, 4, 5 and array2 with the numbers 100, 200, 300. • Use System.out.println(array1) to print out the first and then a similar statement to print out array2. • Run the program. • Add the line System.out.println(array1 == array2); and run again. CISC101 - Prof. McLeod

  41. Array Exercise 3, Cont. • Add code to print out the first elements of both arrays, and run again. • Add the line array1 = array2; • Add the line System.out.println(array1 == array2); as above, and run again. • Add or copy the code to print the first elements again, and run again. Explain the results. • Change the first element of array1 to -500 and display both elements again. CISC101 - Prof. McLeod

  42. Array Exercise 4 • Modify the program you wrote for exercise 2 to put zero’s on the diagonals. CISC101 - Prof. McLeod

  43. Class Structure • A class consists of instance variables and/or methods. • By convention, instance variables are all declared before the methods: public class ShowStructure { // instance variables here // methods here } // end class ShowStructure CISC101 - Prof. McLeod

  44. Instance Variables • Also called “class variables” or “attributes”. • These variables are declared at the same level as the methods in a class. • They are known to all methods within a class. Their scope is the entire class in which they were declared. CISC101 - Prof. McLeod

  45. Instance Variables, Cont. • The syntax for the declaration of attributes: [private|public] [static] [final] typevariable_name [= literal_value]; • The “|” in this syntax means “one or the other”. • The “[ ]” means that this part is optional. CISC101 - Prof. McLeod

  46. Instance Variables, Cont. • private or public determines if the attribute can be accessed from outside the class. • A static attribute shares only a single memory location, regardless of how many times its class is instantiated. So, every instantiation shares this attribute, and any of them can change it. • Otherwise, the declaration of an attribute is just the same as any other variable declaration. CISC101 - Prof. McLeod

  47. Methods • The syntax for simple method declaration: [private|public] [static] return_type method_name ([parameter_list]) {…} CISC101 - Prof. McLeod

  48. Methods - Cont. • Often, “utility” methods that are only used by other methods within a class are kept private. • When the “static” keyword is used with methods, it means that the method can be used without instantiation. (All the methods in the Math class are static, for example.) • When a static method is invoked for the first time, it is loaded into memory and then will stay in memory until the program completes. CISC101 - Prof. McLeod

  49. Aside - “Instantiation”??? • Simply put, it is the creation of a new Object using the “new” keyword. • Another Object is required to provide the “pattern” for the new Object: • Familiar example: Scanner input = new Scanner(System.in); CISC101 - Prof. McLeod

  50. Aside - “Instantiation”??? – Cont. • Another example: String aString = new String(“Hello class!”); is actually better form than: String aString = “Hello class!”; • The latter form (aliasing aString to a String literal…) is allowed because it is convenient (and much like using primitive types.) CISC101 - Prof. McLeod

More Related