Objects and Arrays Phil Tayco San Jose City

Objects and Arrays Phil Tayco San Jose City College Slide version 1. 0 Created Apr. 21, 2020
![Array Recap • Recall how Java arrays are created int[] numbers; • This is Array Recap • Recall how Java arrays are created int[] numbers; • This is](http://slidetodoc.com/presentation_image_h2/5fdb5a30bc64e60035d644b16d2f49bd/image-2.jpg)
Array Recap • Recall how Java arrays are created int[] numbers; • This is a variable declaration of an integer array called numbers • When we look under the hood, numbers is waiting for us to define how much memory for the array to allocate (i. e. how many elements to reserve) numbers ? • We have to define how many integers we want to reserve for the array to allocate memory
![Array Recap numbers = new int[10]; • This reserves 10 integers in memory • Array Recap numbers = new int[10]; • This reserves 10 integers in memory •](http://slidetodoc.com/presentation_image_h2/5fdb5a30bc64e60035d644b16d2f49bd/image-3.jpg)
Array Recap numbers = new int[10]; • This reserves 10 integers in memory • In Java, since the type of the array elements is simple, they are initialized with a given value of 0 numbers 0 x 3320 aad 2 0 0 0 … 0 0 1 2 … 9 • At this point, we can use any of these elements to store integers the way we like such as for storing grades, scores, ages, etc. • Each of these elements share one thing in common – they are all integers (i. e. same data type)

Object Recap • An object is a variable whose data type is complex (i. e. a class data type) Student you = new Student(); • This creates an object called “you” whose data type is a Student • Student itself is a class that would need to be defined and will contain properties such as name, age, or grade, and methods such as set. Name(), get. Grade(), is. Passing(), etc. • The class allows us to model real world concepts and organize data so your code is more easily managed and readable

Object Recap • Let’s create a simple Book class with the following properties public class Book { private int isbn; private String title; private double price; } • There are other properties like author we could add, but let’s keep it simple for now • The corresponding constructor(s) and set/get methods should follow as you did in previous exercises – make sure those are in place before continuing

Objects and Arrays • Arrays are defined as follows: – An ordered set of elements referred to by the same variable name with each element accessed by an index – Each element is the same data type • The second point is of most significance with classes because remember what a class is: it’s a complex data type! • It then follows that since you can create an array of integers, now you can also create an array of classes… Book[] library = new Book[10]; • This reserves memory for 10 Book objects that can now be created in an array variable called “library”

Objects and Arrays • Arrays of objects need to be treated with care • For arrays of simple data types like integers, the process is to declare the array variable, reserve how many elements you want, and then use the elements as you like • For arrays of complex data types like Books, the pattern of use is the same, but there’s an additional step when using the elements • Recall the restaurant reservation analogy from previous slides – Saying “Book[] library = new Book[10]” is asking for 10 seats to be reserved in the restaurant – The seats are currently empty, so to use a spot, you must create a Book object to take the seat – You would normally create one Book object as “Book my. Book = new Book()” – we want to follow a similar pattern when we have arrays with objects
![Arrays Step By Step Book[] library; • As with an Array with simple data Arrays Step By Step Book[] library; • As with an Array with simple data](http://slidetodoc.com/presentation_image_h2/5fdb5a30bc64e60035d644b16d2f49bd/image-8.jpg)
Arrays Step By Step Book[] library; • As with an Array with simple data types, the declaration of alarms here is only creating the reference with no memory allocated library ? • When we are ready to allocate memory for the library Array, we state the number of Book elements to reserve • Consider the following: – What will the array elements actually look like? – What will the array elements be initialized to?
![Arrays Step By Step library = new Book[10]; • This will reserve 10 Book Arrays Step By Step library = new Book[10]; • This will reserve 10 Book](http://slidetodoc.com/presentation_image_h2/5fdb5a30bc64e60035d644b16d2f49bd/image-9.jpg)
Arrays Step By Step library = new Book[10]; • This will reserve 10 Book references (they are not objects yet) in memory • Key point: each Book element has no Book object created library 0 x 2 d 2 a 1100 ? ? ? … ? 0 1 2 … 9 • All we’ve done at this point is create memory for the array. Each element does not have an actual Book object yet • Now, any element can have a Book object created at any time but until that point, the element is pointing to null
![Arrays Step By Step library[0] = new Book(); library[1] = new Book(123, “Java”, 49. Arrays Step By Step library[0] = new Book(); library[1] = new Book(123, “Java”, 49.](http://slidetodoc.com/presentation_image_h2/5fdb5a30bc64e60035d644b16d2f49bd/image-10.jpg)
Arrays Step By Step library[0] = new Book(); library[1] = new Book(123, “Java”, 49. 99); • This creates 2 Book objects in the first 2 elements of the library array library 0 x 2 d 2 a 1100 0 x 17 f 32 a 20 0 x 44 a 059 f 2 ? … ? 0 1 2 … 9 0 “” 123 0. 00 “Java” 49. 99 • Lots of observations to make with this configuration

Arrays of Objects • Note that coding pattern that is consistent with creating objects • If we had done a standalone Book object like “b”, we would have done it as: Book b = new Book(); • For creating a Book object in the library array, we follow the same pattern, but we must also specify the location in the array where the new Book must go: library[0] = new Book(); library[1] = new Book(123, “Java”, 49. 99);

Arrays of Objects • Some observations to make at this point with the library array – library was first created with and has 10 available elements for Book objects – 2 Book objects have been created – The other 8 library elements are null – In short: 10 Book elements are available, 2 are in use • Once you have a Book object created in the array, you can now use it as you would any other object • With a standalone object, “b. set. Price(10); ” would set the price of the b Book to 10 • You can follow the same coding pattern for an array once you specify which element to use: library[0]. set. Price(25. 99);

Arrays of Objects • You may start to see advantages with this type of coding and organization • As we saw in the Arrays slide presentation, you could create an array of prices to keep track of a collection of pricing data • There is no context on what those prices are applied to though – are they prices for cars, books, houses, or other products? • Using arrays of objects, now we can track a collection of data at a class level • This further helps us model real world concepts as we can use an array like to this handle different questions: – How many books are in my library? – What’s the most expensive book? – What’s the average cost of all my books in the library?

Arrays of Objects • For example, let’s add 2 more Book objects to the library[2] = new Book(456, “C++”, 14. 99); library[3] = new Book(789, “Math”, 74. 99); • We can now use code to determine the average cost of all the Book objects in the library • The logic is the same as we saw in the Arrays slide presentation – Initialize a sum variable to 0 – Use a loop to add each price in the array to sum – After the loop, calculate the average from the total in sum • The difference now is that when we add a price to sum, we have to “get the price of the Book object” in the library array

Arrays of Objects double sum = 0. 0; for (int c = 0; c < 4; c++) sum += library[c]. get. Price(); System. out. println("Average = " + sum / 4); • The code in red is the key difference • “library[c]” is referring to the Book object in library at index location c (with c being the loop counter variable) • Once you have the object from library[c], you can call any method like “get. Price()” for that specific Book object • This opens up many ways to organize data and manage it with code • With increased complexity though, there are some commonly made errors

Arrays of Objects • The most common error to make with Arrays of objects is to attempt to use methods for elements that have not yet been instantiated for(int c = 0; c < library. length; c++) System. out. println(library[c]. get. Title()); • If you add this code and run it, the first problem is that, guess what – it compiles! • This means the error is not a compiler one, but a logical one as you see when you run it • The error you should have when this runs is “java. lang. Null. Pointer. Exception” • This is a very popular run time error – when you receive it, it means you are trying to execute a method (get. Title) on an object that has not yet been created

Arrays of Objects • You may also notice in the run output that the titles of the first few Book objects are printing • This means the error is occurring somewhere later in the array – this furthers the idea that the error is based on an object that has not yet been created • Looking at the code, the problem is with the loop for(int c = 0; c < library. length; c++) System. out. println(library[c]. get. Title()); • library. length returns the capacity of the array and not the actual number of Book objects that are in use • library. length will return 10, so the loop is going from 0 to 1 to 2 to…all the way to 9

Arrays of Objects • This is okay for when c is 0, 1, 2, or 3 because we have Book objects in the library at locations 0 to 3 • When c is 4 though, there is no Book object there • The code inside the loop still executes because c is still less than library. length (i. e. 4 < 10) for(int c = 0; c < library. length; c++) System. out. println(library[c]. get. Title()); • At that point, “library[4]. get. Title()” is trying to call a method on a location in memory (library[4]) that is null • This is the cause for the Null. Pointer. Exception run time error and is very common to make and challenging to debug

Arrays of Objects • A good way to prevent this is to maintain a number. Of. Books variable for how many Book objects in the library have actually been created • We followed a similar pattern in the Arrays presentation (slides 26 -28) int number. Of. Books = 4; for(int c = 0; c < number. Of. Books; c++) System. out. println(library[c]. get. Title()); • Now c will stop at 4 and the loop will only print the titles of Book objects from elements 0 to 3 • This also means you must maintain number. Of. Books appropriately: – If you had create a new Book object, you must add 1 to number. Of. Books – If you delete a Book object, you must subtract 1

Arrays of Objects • Speaking of deleting objects, Java has a nice feature in the background of its environment called the “garbage collector” • Put simply, this process runs in the background whenever your code is running to make sure any memory that has been created that is considered no longer in use is cleaned up • How does Java define garbage? Say you created a separate Book object Book mine = new Book(111, “Music”, 12. 99); • Later on, you may not need that object anymore. To delete it, we would set the object to null mine = null;

Arrays of Objects • Remember that “mine” is actually a reference to some location in memory where the actual object data is stored • When “mine” was created, the location of the object data could be somewhere like 0 x 123456 • When we set mine to null, the 0 x 123456 goes away, but the object data at that location actually still remains for a short period of time • The Java garbage collector eventually sees this and clears up the object data there so we don’t have to worry about it as coders – If this was C++ though, we would have to remove that memory first before setting “mine” to null • Put simply then, to delete an object, simply set its object variable to null • For arrays or objects, though, this adds some complexity

Deleting Objects in Arrays • Let’s say we delete the 2 nd book in the library • Now we might think, “oh, I also need to subtract 1 from number. Of. Books” so we end up doing this library[1] = null; number. Of. Books--; • The problem is that the array has a “hole” in it meaning we have a Book object at index locations 0, 2, and 3 while location 1 is null • Now if we try to run the same loop as before, we will get another Null. Pointer. Exception for(int c = 0; c < number. Of. Books; c++) System. out. println(library[c]. get. Title()); • When c is 1, library[1] is null

Deleting Objects in Arrays • To fix this, we need a process to not only delete the Book object in the array, but also “shift” the other existing Book objects so that there are no holes • This allows loops like calculating price sums or printing book titles to still work because their logic assumes on holes in the array • Here’s the code to delete an object in an array (location variable represents an index of an existing Book object) – see if you can figure out how it works before reading the analysis int location = 1; library[location] = null; for(int c = location; c < number. Of. Books; c++) library[c] = library[c+1]; library[number. Of. Books] = null; number. Of. Books--;
![Deleting Objects in Arrays int location = 1; library[location] = null; for(int c = Deleting Objects in Arrays int location = 1; library[location] = null; for(int c =](http://slidetodoc.com/presentation_image_h2/5fdb5a30bc64e60035d644b16d2f49bd/image-24.jpg)
Deleting Objects in Arrays int location = 1; library[location] = null; for(int c = location; c < number. Of. Books; c++) library[c] = library[c+1]; library[number. Of. Books] = null; number. Of. Books--; • The first 2 lines are doing the actual deletion of the Book object • location is set to 1 but could be any index value like 0, 2, or 3 so long as the value represents an existing Book object in the library array • library[location] = null deletes the object – If you’re more advanced, you’ll notice the loop will actually take care of deleting the object so this line is redundant – we’ll leave it here for now to emphasize the point of a deletion
![Deleting Objects in Arrays int location = 1; library[location] = null; for(int c = Deleting Objects in Arrays int location = 1; library[location] = null; for(int c =](http://slidetodoc.com/presentation_image_h2/5fdb5a30bc64e60035d644b16d2f49bd/image-25.jpg)
Deleting Objects in Arrays int location = 1; library[location] = null; for(int c = location; c < number. Of. Books; c++) library[c] = library[c+1]; library[number. Of. Books] = null; number. Of. Books--; • The loop goes starts from the location of the deleted Book – currently, there’s a hole there • The loop ends at the location of the last Book so c is going from index locations 1 to 3 – number. Of. Books is currently 4, but the loop only goes up to 3 because when c becomes 4, the loop will stop • The code in the loop is doing the shift by saying make the Book at the next location to be the Book at the current location – When c is 1, library[1] equals library[2] – When c is 2, library[2] equals library[3]
![Deleting Objects in Arrays int location = 1; library[location] = null; for(int c = Deleting Objects in Arrays int location = 1; library[location] = null; for(int c =](http://slidetodoc.com/presentation_image_h2/5fdb5a30bc64e60035d644b16d2f49bd/image-26.jpg)
Deleting Objects in Arrays int location = 1; library[location] = null; for(int c = location; c < number. Of. Books; c++) library[c] = library[c+1]; library[number. Of. Books] = null; number. Of. Books--; • The last part is a bit tricky – when the loop ends the Book objects have been shifted to fix the hole • However, the last book at library[3] is still there library 0 x 2 d 2 a 1100 0 x 17 f 32 a 0 0 x 44 a 059 0 x 456123 … null 2 1 Book 3 … 9
![Deleting Objects in Arrays int location = 1; library[location] = null; for(int c = Deleting Objects in Arrays int location = 1; library[location] = null; for(int c =](http://slidetodoc.com/presentation_image_h2/5fdb5a30bc64e60035d644b16d2f49bd/image-27.jpg)
Deleting Objects in Arrays int location = 1; library[location] = null; for(int c = location; c < number. Of. Books; c++) library[c] = library[c+1]; library[number. Of. Books] = null; number. Of. Books--; • These last 2 lines then actually removes the last Book object in the library – the array is correct • number. Of. Books is also correctly decreased to 3 library 0 x 2 d 2 a 1100 0 x 17 f 32 a 0 0 x 44 a 059 0 x 456123 null … null 2 1 Book 3 … 9

Objects as Strings • As object coding becomes more complex, it will become useful to have a standard way of presenting an object and can also help with debugging • A standard data type is the String and is automatically used in Java such as when we want to print a value int age = 21; System. out. println(age);

Objects as Strings • An interesting thing happens though when we try the same pattern with an object: Book my. Book = new Book(222, “Chemistry”, 64. 99); System. out. println(my. Book); • If you were to compile and run this code, you’d see something like the following in the output: classesandarrays. Book@15 db 9742 • Because Book objects contain many properties, when we are trying to print a Book object, println doesn’t know how to do that so it resorts to printing the memory location (0 x 15 db 9742)

Objects as Strings • This automatically happens in Java when the need to provide a “String version” of an object occurs • In this case, the object is my. Book and the need for a String version comes from the println function – Advanced note: By making the my. Book object an input parameter for println, the function recognizes it as an object and looks for the conversion to a String • When this happens, Java automatically looks for a special method in the class of the object called “to. String()” • If it doesn’t exist, then the memory location is used

Objects as Strings • Go to the Book class now and add the following method: public String to. String() { return String. format("%d: %s: $%. 2 f", isbn, title, price); } • The method should be at the same level as all the other methods you have like sets/gets • String. format is like the function printf as we saw earlier using format specifiers – %d will be replaced with the integer in isbn – %s will be replaced with the String in title – %f will be replaced with the double in price

Objects as Strings • The values for these will be those of the respective object • The difference with String. format and printf is that printf will print the String in the output – String. format is only creating the String text from the given values and format specification • This String value is returned – now when you run the same println code in main, you’ll see the individual property of the values of my. Book • This is especially handy with object arrays for (int c = 0; c < number. Of. Books; c++) System. out. println(library[c]); • This goes through each Book object in library and prints out all its property values using the to. String method defined!

Objects as Strings • The guideline with to. String is that they should be as common in every class as having constructors, setters, and getters • Having a String representation of any object is particularly useful when class definitions are modified • Let’s add a new property to Book: private String author; • This will require updates to the existing constructors and adding set. Author and get. Author methods – Advanced note: when you update the constructors, the existing ones defined should remain with their signatures intact – To support the addition of author, you should also additional constructors

Objects as Strings • Once you’ve done those updates, now update the to. String method: public String to. String() { return String. format("%d: %s, %s: $%. 2 f", isbn, title, author, price); } • This updates the method for doing a String representation of a Book object to include the author property • This now has an interesting downstream effect on the code in main • If you run it right now, the code in main hasn’t changed, yet you should see a slight update in the part that prints out all the Book objects

Objects as Strings • To further emphasize it, add code above the loop to set the author of 2 Book objects in the library[1]. set. Author("Bill"); library[2]. set. Author("Jane"); for(int c = 0; c < number. Of. Books; c++) System. out. println(library[c]); • The output from the println should now show these authors that is using the modified to. String

Summary • The to. String method adds robustness to your code and facilitates common actions like printing and debugging objects • In the Object Oriented programming world, a method to provide a String representation of an object is as standard as constructors and set/get • This increases the power of classes and objects and is further magnified when we combine them with using arrays • Arrays and Objects follow the same pattern as arrays with simple data types but we must be careful about Null. Pointer. Exception logic errors • As you get more practice with these techniques, run time errors like these will be frequently occur • Debugging becomes a more necessary skill to develop and as such, there also ways to “catch” these run time errors…
- Slides: 36