It is called one-dimensional because one index value is used to refer to each element of the array. In Java, index values start at 0 and go up to string length -1.
Initializing arrays
Storage of arrays and copying arrays
The enhanced for
The enhanced for helps express a programming idiom concisely, as no loop counter is required.
Passing string values into main()
Parallel arrays
Partially filled arrays
Meanwhile, in the body, the previously obtained sales amount is put into the matrix and the next value is obtained. It is easy to create an ArrayList from an array as shown in the program below.
Array utilities in Java class libraries
Change Example 5 to display the name of the month when sales were highest. Recall that the two-dimensional memory structure created by the JVM is an array of strings.
Ragged Arrays
Examples
In lines 14-15, this program determines the number of trips for the driver by simply using the length field of the array that includes row i. For example, two matrices with the same number of rows and columns can be added together to produce a third matrix.
Higher Dimensions
Exercises
The following method, given someone's date of birth in the format YYYY-MM-DD, calculates age in years. In this situation, we expect someone's age to be positive - a non-positive age indicates something.
Validating parameters
For example, if the array index is out of bounds, the program terminates with an ArrayOutOfBoundsException exception. The getAge method in the program below throws a Java IllegalArgumentException; this exception is thrown if the passed argument fails the checks performed.
Manipulating Text
34;+" is used to specify one or more of a preceding character, and - is used to specify a range of characters. Each word is then consecutively concatenated into the result (forcing the first letter to be capitalized).
StringBuilder
However, if a program can do a lot of string manipulation, there is another class, StringBuilder, which for many operations does not have the same overhead as String. This example reads the file Readme.txt character by character linking each character to the next.
Exercises
Enums are objects: An enum is a special type of class in the Java language, but an enum can have data and methods. This code is generated for each number and happens to be exactly what one would use (or start with) for a number representing the 7 days of the week.
Comparing enum values
Enum constants are objects
The program is Listing 4.5 has a method to calculate the gross salary and uses the EnhancedDay number.
Summary
Note the final qualifier which means that once set to the value shown, the value cannot be changed.
Exercises
Extend the program of the previous exercise to give the user a hand of 5 cards. Extend the program of the previous exercise to deal five cards from a shuffled deck, display the cards being dealt and the value of the hand. In Java we can define Practitioner as a generalization of Doctor and Pharmacist (this also means that Doctor and Pharmacist are specializations of Practitioner . . . the two terms, generalization and specialization, go hand in hand).
Next, we consider a doctor and a pharmacist, and present a program that instantiates all three types.
The Practitioner Hierarchy
Creating and using objects of the hierarchy
Given the hierarchy, when an instance of Doctor is created, that instance is (at the same time) an instance of Practitioner, and so a Doctor instance includes all the attributes of Practitioner. Similarly, when an instance of Pharmacist is created, that instance is (at the same time) an instance of Practitioner and includes all the properties of Practitioner. However, if we explicitly instantiate a practitioner object, that object is an instance of practitioner, and not an instance of doctor (or pharmacist).
The Java class in Listing 5.5 creates practitioner, doctor, and pharmacist objects, then adds them to an ArrayListofPractitioners, and then displays their first names.
Overriding methods
Calling an overridden superclass method
Note that the superis prefix is required to explicitly call thegetName() method in the superclass.
Exercises
Abstract Classes and Methods
In the next section, we discuss the form hierarchy where the superclass is abstract with an abstract method. The diagram makes it clear that the shape is abstract, and the triangular symbols make it clear that the square and circle are subclasses. Listing 5.7 lists the classes that define this hierarchy with an abstract superclass Shape (lines 1-5), a subclass Circle (lines 6-15), and a subclass Square (lines 16-25).
So the output does show the object type and its area - shown in Figure 5.8 below.
Exercises
Summary
A typical dictionary definition of the word polymorphism is "the quality of polymorphism or state of existing in or taking different forms". Such methods have no body, and somewhere lower in the class hierarchy, abstract methods must have a definition. In the next chapter we look at interfaces; it is possible for a class to implement multiple interfaces.
It is usually the case that some methods are fully defined in an abstract class, but it is possible for an abstract class to have only abstract methods.
Exercises
Comparable is an interface used to provide what is called a natural ordering for objects. Example 2 creates an array of arrays and sorts the arrays using the array method of the Arrays class. To achieve this, Person will implement Comparable, and then we'll demonstrate how simple it is to sort an array of Persons.
This natural ordering will be implemented as part of the Comparable interface (line 1) and the compareTo method (lines 8-12).
Defining an interface
The initial code can be edited in the BlueJ code editor to contain the necessary definition of, say, the player interface shown later in Listing 6.5. The developer of, say, the Team class knows that there can be references to objects of type Player, and that these objects can respond to requests by their name, position, etc. Any object can be treated as an instance of Playeras long as the object's class implements the Player interface.
To complete our sports example, we present the class below in Listing 6-8 and its output in Figure 6-8.
Comparator Interface
There are overloaded versions of Arrays.sort and Collections.sort that provide a second argument, an object of type Comparator. Consider Listing 6.10, which creates, sorts (by year of birth), and then displays the sorted items.
Summary
Exercises
Binary files
Since it is a binary format, the data is generally unreadable for humans, but well suited for computers. If we can write data to a binary file, we store data in a most efficient way in terms of space and time. In the previous section we showed how to write data to a file and now we present how we can retrieve the data later in a separate program.
Note in the table below the method readUTF-it is used to read string data.
XML files
As you can see, it's human readable and it's easy to see where and how their values are encoded. In the previous section we showed how to write primitive data to an XML file, and now we consider returning the same data to a separate program at a later time. ThereadObject method receives the next data encoded in the file, but to use such a value in a program, we need to cast the object to its type.
Objects
Binary files
To serialize an object to a binary file, the objects must belong to a class that implements the Serializable interface. The first example will create a binary file and the second example shows that we can read that file and re-instantiate objects at a later time. Recall listing 5.2 where Practitioner.java is defined; we need to modify the Practitioner class so that it implements Serializable.
This can occur if the binary specifies that an object should be instantiated from a class that the JVM is not aware of.
XML files
In Figure 7.6 we show the first few lines of the XML file created by PractitionersToXML.java. Recall listing 5.5 (Practitioners.java) where there is foreloop that steps through the list and displays information about each practitioner. Listing 7.8 (PractitionersFromXML.java) obtains the ArrayList of practitioners from the XML file practitioners.xml and then displays those practitioners.
The output from the program is shown in Figure 7.7 and is exactly the same as that of Practitioners.java in Chapter 5.
Summary
Exercises
If the main method in Listing 7.2 is executed and the file myData.ser does not exist, a FileNotFoundException is thrown and the program terminates abruptly with a FileNotFoundException. If there were fewer than 5 integers in the file, an EOFException would be thrown and the program would terminate abruptly with an EOFException. Listing 8.1 prompts the user for a file name and attempts to create a reference to the file.
For example, if the file exists, the user sees message dialogs as shown in Figure 8.3.
Designing a custom exception
A recursive method is one that breaks down a problem into smaller problems of the same problem type that can be combined to form a solution. One of the problems with recursive calls is the stack space that can be used up. Some of the artwork he produced has inspired a number of programmers to try similar works.
To run the example, you must also download and compile in the same project, Canvas.java, which is the core class of the BlueJ Shapes example.
Recursive data structures
An interesting aspect of the class is that the supervisor field can have a value that references another employee. There are 5 employees listed above, with John Smith at the bottom of the reporting structure and April Barnes at the top (she has no supervisor). The program that creates these five employees, sets up their reporting structure, and displays a supervisor is shown in Listing 9.6.
Exercises
- Selection Sort
- Insertion Sort
- Bubble Sort
- Quicksort
- Implementation
- Listings
The nature of the algorithm eventually reduces the unsorted sublist to nothing, and the sorted sublist includes all elements. The sorted sublist begins as the empty list, and the unsorted sublist includes all n elements. At this point, we say that the sorted sublist includes the first element, and the unsorted sublist consists of the remaining n−1 elements.
After traversing the unsorted sublist, the unsorted sublist shrinks by 1 element and the sorted sublist grows by 1 element.
Sorting Objects
Searching Algorithms
Searching an Unordered List
Searching an Ordered List
Exercises