text
stringlengths
1
7.76k
source
stringlengths
17
81
29. Methods 16 System.out.println("main: b = " + b); 17 18 change(a, b); 19 20 System.out.println("main after: s = " + a); 21 System.out.println("main after: b = " + b); 22 23 } 24 } To see this, observe the following output. When we return to the main method, the original string s is unchanged (since it was immutable). However, the StringBuilder has been changed by the method. main: s = Hello main: b = Hello change: s = Hello world! change: sb = Hello world! main after: s = Hello main after: b = Hello world! 29.2. Examples 29.2.1. Generalized Rounding Recall that the math library provides a Math.round() method that rounds a number to the nearest whole number. We’ve had need to round to cents as well. We now have the ability to write a method to do this for us. Before we do, however, let’s think more generally. What if we wanted to round to the nearest tenth? Or what if we wanted to round to the nearest 10s or 100s place? Let’s write a general purpose rounding method that allows us to specify which decimal place to round to. The most natural input would be to specify the place using an integer exponent. That is, if we wanted to round to the nearest tenth, then we would pass it −1 as 0.1 = 10−1, −2 if we wanted to round to the nearest 100th, etc. In the other direction, passing in 0 would correspond to the usual round function, 1 to the nearest 10s spot, and so 428
ComputerScienceOne_Page_462_Chunk2001
29.2. Examples on. We could demonstrate good code reuse (as well as good procedural abstraction) by scaling the input value and reusing the functionality already provided in the math library’s Math.round() method. We could further define a roundToCents() method that used our generalized round method. Finally, we could place all of these methods into RoundUtils Java class for good organization. 1 package unl.cse; 2 3 /** 4 * A collection of rounding utilities 5 * 6 */ 7 public class RoundUtils { 8 9 /** 10 * Rounds to the nearest digit specified by the place 11 * argument. In particular to the (10^place)-th digit 12 * 13 * @param x the number to be rounded 14 * @param place the place to be rounded to 15 * @return 16 */ 17 public static double roundToPlace(double x, int place) { 18 double scale = Math.pow(10, -place); 19 double rounded = Math.round(x * scale) / scale; 20 return rounded; 21 } 22 23 /** 24 * Rounds to the nearest cent (100th place) 25 * 26 * @param x 27 * @return 28 */ 29 public static double roundToCents(double x) { 30 return RoundUtils.roundToPlace(x, -2); 31 } 32 33 } Observe that this class does not contain a main() method. That means that this class 429
ComputerScienceOne_Page_463_Chunk2002
29. Methods is not executable itself. It only provides functionality to other classes in the code base. 430
ComputerScienceOne_Page_464_Chunk2003
30. Error Handling & Exceptions Java supports error handling through the use of exceptions. Java has many different predefined types of exceptions that you can use in your own code. It also allows you to define your own exception types by creating new classes that inherit from the predefined classes. Java uses the standard try-catch-finally control structure to handle exceptions and allows you to throw your own exceptions. 30.1. Exceptions Java defines a base class named Throwable . There are two majors subtypes of Throwable : Error and Exception . The Error class is used primarily for fatal errors such as the JVM running out of memory or some other extreme case that your code cannot reasonably be expected to recover from. There are dozens of types of exceptions that are subclasses of the standard Java Exception class defined by the JDK including IOException (and its subclasses such as FileNotFoundException ) or SQLException (when working with Structured Query Language (SQL) databases). An important subclass of Exception is RuntimeException which represent unchecked exceptions that do not need to be explicitly caught (see Section 30.1.4). We’ll mostly focus on this type of exception. 30.1.1. Catching Exceptions To catch an exception in Java you can use the standard try-catch control block (and optionally use the finally block to clean up any resources). Let’s take, for example, the simple task of reading input from a user using Scanner and manually parsing its value into an integer. If the user enters a non-numeric value, parsing will fail and result in a NumberFormatException that we can then catch and handle. For example, 1 Scanner s = new Scanner(System.in); 2 int n = 0; 3 431
ComputerScienceOne_Page_465_Chunk2004
30. Error Handling & Exceptions 4 try { 5 String input = s.next(); 6 n = Integer.parseInt(input); 7 } catch (NumberFormatException nfe) { 8 System.err.println("You entered invalid data!"); 9 System.exit(1); 10 } In this example, we’ve simply displayed an error message to the standard error output and exited the program. That is, we’ve made the design decision that this error should be fatal. We could have chosen to handle this error differently in the catch block. The code above could have resulted in other exceptions. For example if the Scanner had failed to read the next token from the standard input, it would have thrown a NoSuchElementException . We can add as many catch blocks as we want to handle each exception differently. 1 Scanner s = new Scanner(System.in); 2 int n = 0; 3 4 try { 5 String input = s.next(); 6 n = Integer.parseInt(input); 7 } catch (NumberFormatException nfe) { 8 System.err.println("You entered invalid data!"); 9 System.exit(1); 10 } catch (NoSuchElementException nsee) { 11 System.err.println("Input reading failed, using default..."); 12 n = 20; //a default value 13 } catch(Exception e) { 14 System.err.println("A general exception occurred"); 15 e.printStackTrace(); 16 System.exit(1); 17 } Each catch block catches a different type of exception. Thus, the name of the variable that holds each exception must be different in the chain of catch blocks; nfe , nsee , e . 432
ComputerScienceOne_Page_466_Chunk2005
30.1. Exceptions Note that the last catch block was written to catch a generic Exception . This last block will essentially catch any other type of exception. Much like an if-else-if statement, the first type of exception that is caught is the block that will be executed and they are all mutually exclusive. Thus, a “catch all” block like this should always be the last catch block. The most specific types of exceptions should be caught first and the most general types should be caught last. 30.1.2. Throwing Exceptions We can also manually throw an exception. For example, we can throw a generic RuntimeException using the following. 1 throw new RuntimeException("Something went wrong"); By using a generic RuntimeException , we can attach a message to the exception (which can be printed by code that catches the exception). If we want more fine-grained control over the type of exceptions, we need to define our own exceptions. 30.1.3. Creating Custom Exceptions To create your own exceptions, you need to create a new class to represent the exception and make it extend RuntimeException by using the keyword extends . This makes your exception a subclass or subtype of the RuntimeException . This is a concept known as inheritance in OOP. Consider the example in the previous chapter of computing the roots of a quadratic polynomial. One possible error situation is when the roots are complex numbers. We could define a new Java class as follows. 1 public class ComplexRootException extends RuntimeException { 2 3 /** 4 * Constructor that takes an error message 5 */ 6 public ComplexRootException(String errorMessage) { 7 super(errorMessage); 8 } 9 } 433
ComputerScienceOne_Page_467_Chunk2006
30. Error Handling & Exceptions Now in our code we can throw and catch this new type of exception. 1 //throw this exception: 2 if( b*b - 4*a*c < 0) { 3 throw new ComplexRootException("Cannot Handle complex roots"); 4 } 1 try { 2 r1 = getComplexRoot01(a, b, c); 3 } catch(ComplexRootException cre) { 4 //handle the exception here... 5 } 30.1.4. Checked Exceptions A checked exception in Java is an exception that must be explicitly caught and han- dled. For example, the generic Exception class is a checked exception (others include IOException , SQLException , etc.). If a checked exception is thrown within a block of code then it must either be caught and handled within that block of code or the method must be specified to explicitly throw the exception. For example, the method 1 public static void processFile() { 2 Scanner s = new Scanner(new File("data.csv")); 3 } would not actually compile because Scanner throws a checked FileNotFoundException . Either we would have to explicitly catch the exception: 1 public static void processFile() { 2 Scanner s = null; 3 try { 4 s = new Scanner(new File("data.csv")); 5 } catch (FileNotFoundException e) { 434
ComputerScienceOne_Page_468_Chunk2007
30.1. Exceptions 6 //handle the exception here 7 } 8 } or we would need to specify that the method processFile() explicitly throws the exception: 1 public static void processFile() throws FileNotFoundException { 2 Scanner s = new Scanner(new File("data.csv")); 3 } Doing this, however, would force any code that called the processFile() method to surround it in a try-catch block and explicitly handle it (or once again, throw it back to the calling method). The point of a checked exception is to force code to deal with potential issues that can be reasonably anticipated (such as the unavailability of a file). However, from another point of view checked exceptions represent the exact opposite goal of error handling. Namely, that a function or code block can and should inform the calling function that an error has occurred, but not explicitly make a decision on how to handle the error. A checked exception doesn’t make the full decision for the calling function, but it does eliminate ignoring the error as an option from the calling function. Java also supports unchecked exceptions which do not need to be explicitly caught. For example, NumberFormatException or NullPointerException are unchecked excep- tions. If an unchecked exception is thrown and not caught, it bubbles up through the call stack until some piece of code does catch it. If no code catches it, it results in a fatal error and terminates the execution of the JVM. The RuntimeException class and any of its subclasses are unchecked exceptions. In our ComplexRootException example above, because we extended RuntimeException we made it an unchecked exception, allowing the calling function to decide not only how to handle it, but whether or not to handle it at all. If we had instead decided to extend Exception we would have made our exception a checked exception. There is considerable debate as to whether or not checked exceptions are a good thing (and as to whether or not unchecked exceptions are a good thing). Many1 feel that checked 1The author included. 435
ComputerScienceOne_Page_469_Chunk2008
30. Error Handling & Exceptions exceptions were a mistake and their usage should be avoided. The rationale behind checked exceptions is summed up in the following quote from the Java documentation [7]. Here’s the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception The problem is that the JDK’s own design violates this principle. For example, FileNotFoundException is a checked exception; the reasoning being that a program could reprompt the user for a different file. The problem is the assumption that the program we are writing is always interactive. In fact most software is not interactive and is instead designed to interact with other software. Reprompting is not appropriate or even an option in the vast majority of cases. As another example, consider Java’s SQL library which allows you to programmatically connect to an SQL database. Nearly every method in the API explicitly throws a checked SQLException . It stretches the imagination to understand how our code or even a user would be able to recover (programmatically at least) from a lost internet connection or a bad password, etc. In general, you should use unchecked exceptions. 30.2. Enumerated Types Another way to prevent errors is by restricting the values of a variable that a programmer is allowed to use. Java allows you to define a special class called an enumerated type which allow you to define a fixed list of possible values. For example, the days of the week or months of the year are possible values used in a date. However, they are more-or-less fixed (no one will be adding a new day of the week or month any time soon). An enumerated class allows us to define these values using human-readable keywords. To create an enumerated type class we use the keyword enum (short for enumeration) instead of class . Since an enumerated type is a class, it must follow the same rules. It must be in a .java source file of the same name. Inside the enum we provide a comma-delimited list of keywords to define our enumeration. Consider the following example. 1 public enum Day { 2 SUNDAY, 3 MONDAY, 4 TUESDAY, 5 WEDNESDAY, 6 THURSDAY, 7 FRIDAY, 436
ComputerScienceOne_Page_470_Chunk2009
30.2. Enumerated Types 8 SATURDAY; 9 } In the example, since the name of the enumeration is Day this declaration must be in a source file named Day.java . We can now declare variables of this type. The possible values it can take are restricted to SUNDAY , MONDAY , etc. and we can use these keywords in our program. However these values belong to the class Day and must be accessed statically. For example, 1 Day today = Day.MONDAY; 2 3 if(today == Day.SUNDAY || today == Day.SATURDAY) { 4 System.out.println("Its the weekend!"); 5 } Note the naming conventions: the name of the enumerated type follows the same upper camel casing that all classes use while the enumerated values follow an uppercase underscore convention. Though our example does not contain a value with multiple words, if it had, we would have used an underscore to separate them. Using an enumerated type has two advantages. First, it enforces that only a particular set of predefined values can be used. You would not be able to assign a value to a Day variable that was not already defined by the Day enumeration. Second, without an enumerated type we’d be forced to use a collection of magic numbers to indicate values. Even for something as simple as the days of the week we’d be constantly trying to remember: which day is Wednesday again? Do our weeks start with Monday or Sunday? By using an enumerated type these questions are mostly moot as we can use the more human-readable keywords and eliminate the guess work. 30.2.1. More Tricks Every enum type has some additional built-in methods that you can use. For example, there is a values() method that can be called on the enum that returns an array of the enum ’s values. You can use an enhanced for loop to iterate over them, for example, 437
ComputerScienceOne_Page_471_Chunk2010
30. Error Handling & Exceptions 1 for(Day d : Day.values() { 2 System.out.println(d.name()); 3 } In the example above, we used another feature: each enum value has a name() method that returns the value as a String . This example would end up printing the following. SUNDAY MONDAY TUESDAY WEDNESDAY THURSDAY FRIDAY SATURDAY Of course, we may want more human-oriented representations. To do this we could override the class’s toString() method to return a better string representation. For example: 1 public String toString() { 2 if(this == SUNDAY) { 3 return "Sunday"; 4 } else if(this == MONDAY) { 5 return "Monday"; 6 } 7 ... 8 } else { 9 return "Saturday"; 10 } 11 } Because enum types are full classes in Java, many more tricks can be used that leverage the power of classes including using additional state and constructors. We will cover these topics later. 438
ComputerScienceOne_Page_472_Chunk2011
31. Arrays Java allows you to declare and use arrays. Since Java is statically typed, arrays must also be typed when they are declared and may only hold that particular type of element. Since Java has automated garbage collection, memory management is greatly simplified. Finally, in Java, only locally scoped primitives and references are allocated on the program call stack. As such, there are no static arrays; all arrays are allocated in the heap space. 31.1. Basic Usage To declare an array reference, you use syntax similar to declaring a regular variable, but you use square brackets to designate the variable as an array. Arrays for any type of variable can be created including primitives and objects. 1 int arr[] = null; 2 double values[] = null; 3 String names[] = null; This example1 only declares 3 references that can refer to an array, it doesn’t actually create them as the references are all set to null . To create arrays of a particular size, we need to initialize them using the keyword new . 1 arr = new int[10]; 2 values = new double[20]; 3 names = new String[5]; 1You may see code examples that use the alternative notation int[] arr = null; . Both are acceptable. Some would argue that this way is more correct because it keeps the brackets with the type, avoiding the type-variable name-type separation in our example. Those preferring the int arr[] = null; notation would argue that it is “more natural” because that is how we ultimately index the array. Six of one, half-dozen of the other. 439
ComputerScienceOne_Page_473_Chunk2012
31. Arrays Each of these initializations creates a new array (allocated on the heap) of the specified size (10, 20, and 5 respectively). These arrays can only hold values of the specified type, int , double , and String respectively. The default value for each element in these new arrays will be zero for the numeric types and null for object types. Alternatively, you could use a compound declaration/assignment syntax to initialize specific values: 1 int arr[] = { 2, 3, 5, 7, 11 }; Using this syntax we do not need to specify the size of the array as the compiler is smart enough to count the number of elements we’ve provided. The elements themselves are denoted inside curly brackets and delimited with commas. For both types of syntax, the actual array is always allocated on the heap while the reference variables, arr , values , and names are stored in the program call stack. Indexing Once an array has been created, its elements can be accessed by indexing them. Java uses the standard 0-indexing scheme so the first element is at index 0, the second at index 1, etc. Indexing an element involves using the square bracket notation and providing an integer index. Once indexed, an array element can be treated as a normal variable and can be used with other operators such as the assignment operator or comparison operators. 1 arr[0] = 42; 2 if(arr[4] < 0) { 3 System.out.println("negative!"); 4 } 5 System.out.println("arr[1] = " + arr[1]); Recall that an index is actually an offset. The compiler and system know exactly how many bytes each element takes and so an index i calculates exactly how many bytes from the first element the i-th element is located at. Consequently it is possible to index elements that are beyond the range of the array. For example, arr[-1] or arr[5] would attempt to access an element immediately before the first element and immediately after the last element. Obviously, these elements are not part of the array. If you attempt to access an element outside the bounds of an array, the JVM will throw an IndexOutOfBoundsException which is an unchecked RuntimeException that you can 440
ComputerScienceOne_Page_474_Chunk2013
31.1. Basic Usage catch and handle if you choose. To prevent such an exception you can write code that does not exceed the bounds of the array. Java arrays have a special length property that gives you the size of the array. You can access the property using the dot operator, so arr.length would give the value 5 for the example above. Iteration Using the .length property you can design a for loop that increments an index variable to iterate over the elements in an array. 1 int arr[] = new int[5]; 2 for(int i=0; i<arr.length; i++) { 3 arr[i] = 5 * i; 4 } The for loop above initializes the variable i to zero, corresponding to the first element in the array. The continuation condition specifies that the loop continues while i is strictly less than the size of the array denoted using the arr.length property. This for loop iteration is idiomatic when processing arrays. In addition, Java (as of version 5) supports foreach loops that allow you to iterate over the elements of an array without using an index variable. Java refers to these loops as “enhanced for loops,” but they are essentially foreach loops. 1 for(int a : arr) { 2 System.out.println(a); 3 } The syntax still uses the keyword for , but instead of an index variable, it specifies the type and a the loop-scoped variable identifier followed by a colon and the array that you want to iterate over. Each iteration of the loop updates the variable a to the next value in the array. 441
ComputerScienceOne_Page_475_Chunk2014
31. Arrays 31.2. Dynamic Memory The use of the keyword new dynamically allocates memory space (on the heap) for the array. Because Java has automated garbage collection, if the reference to the array goes out of scope, it is automatically cleaned up by the JVM. This process is automated and essentially transparent to us. There are sophisticated algorithms and heuristics at work that determine the “optimal” time to perform garbage collection. 1 int arr[]; 2 //create a new array of size 10: 3 arr = new arr[10]; 4 //lose the reference by explicitly setting it to null: 5 arr = null; 6 //all references to the old memory are now lost and it is 7 //eligible for garbage collection 8 9 //we can also allocate new memory: 10 arr = new arr[20]; 31.3. Using Arrays with Methods We can pass and return arrays to and from methods in Java. We use the same syntax as when we define them by specifying a type and using square brackets. As an example, the following method takes an array of integers and computes its sum. 1 /** 2 * This method computes the sum of elements in the 3 * given array which contains n elements 4 */ 5 public static int computeSum(int arr[]) { 6 int sum = 0; 7 for(int i=0; i<size; i++) { 8 sum += arr[i]; 9 } 10 return sum; 11 } 442
ComputerScienceOne_Page_476_Chunk2015
31.4. Multidimensional Arrays In Java, arrays are always passed by reference. Though we did not make any changes to the contents of the passed array in the particular example, in general we could have. Any such changes would be realized in the calling method. Unfortunately, there is no mechanism by which we can prevent changes to arrays when passed to methods.2 We can also create an array in a method and return it as a value. For example, the following method creates a deep copy of the given integer array. That is, a completely new array that is a distinct copy of the old array. In contrast, a shallow copy would be if we simply made one reference point to another reference. 1 /** 2 * This method creates a new copy of the given array 3 * and returns it. 4 */ 5 public static int [] makeCopy(int a[]) { 6 int copy[] = new int[a.length]; 7 for(int i=0; i<n; i++) { 8 copy[i] = a[i]; 9 } 10 return copy; 11 } The method returns an integer array. In fact, this method is so useful, that it is already provided as part of the Java Software Development Kit (SDK). The class Arrays contains dozens of utility methods that process arrays. In particular there is a copyOf() method that allows you to create deep copies of arrays and even allows you to expand or shrink their size. 31.4. Multidimensional Arrays Java supports multidimensional arrays, though we’ll only focus on 2-dimensional arrays. To declare and allocate 2-dimensional arrays, we use two square brackets with two specified dimensions. 1 int matrix[][] = new int[10][20]; 2The use of the keyword final only prevents us from changing the array reference, not modifying its contents. 443
ComputerScienceOne_Page_477_Chunk2016
31. Arrays This creates a 2-dimensional array of integers with 10 rows and 20 columns. Once created, we can index individual elements by specifying row and column indices. 1 for(int i=0; i<matrix.length; i++) { 2 for(int j=0; j<matrix[i].length; j++) { 3 matrix[i][j] = 10; 4 } 5 } 31.5. Dynamic Data Structures The Java SDK provides a rich assortment of dynamic data structures as alternatives to arrays including lists, sets and maps. The classes that support and implement these data structures are defined in the Collections library under the java.util package. We will cover how to use some of these data structures, but we will not go into the details of how they are implemented nor the OOP concepts that underly them. The Java List is an interface that defines a dynamic list data structure. This data structure provides a dynamic collection that can grow and shrink automatically as you add and remove elements from it. It is an interface, so it doesn’t actually provide an implementation, just a specification for the publicly available methods that you can use. Two common implementations are ArrayList , which uses an array to hold elements, and LinkedList which stores elements in linked nodes. To create an instance of either of these lists, you use the new keyword and the following syntax. 1 List<Integer> a = new ArrayList<Integer>(); 2 List<String> b = new LinkedList<String>(); The first line creates a new instance of an ArrayList that is parameterized to hold Integer types. The second creates a new instance of a LinkedList that has been parameterized to only hold String types. The parameterization is specified by placing the parameterized type inside the angle brackets. Because of this parameterization, it 444
ComputerScienceOne_Page_478_Chunk2017
31.5. Dynamic Data Structures would be a compiler error to attempt to add anything other than Integer s to the first list or anything other than String s to the second. Once these lists have been created, you can add and remove elements using the add() method. 1 a.add(42); 2 a.add(81); 3 a.add(17); 4 5 b.add("Hello"); 6 b.add("World"); 7 b.add("Computers!"); The order that you add elements is preserved, so in the first list, the first element would be 42, the second 81, and the last 17. You can remove elements by specifying an index of the element to remove. Like arrays, lists are 0-indexed. 1 a.remove(0); 2 3 b.remove(2); 4 b.remove(0); As you remove elements, the indices are “shifted” down, so that after removing the first element in the list a , 81 becomes the new first element. Removing the last then the first element in the list b leaves it with only one element, "World" as the first element (at index 0). You can also retrieve elements from a list using 0-indexing and the get() method. 1 List<Double> values = new ArrayList<Double>(); 2 values.add(3.14); 3 values.add(2.71); 4 values.add(42.0); 5 6 double x = values.get(1); //get the second value, 2.71 7 double y = values.get(2); //get the third value, 42.0 445
ComputerScienceOne_Page_479_Chunk2018
31. Arrays Any attempt to access an element that lies outside the bounds of the List , will result in an IndexOutOfBoundsException just as with arrays. To stay within bounds you can use the size() method to determine how many elements are in the collection. In this example, values.size() would return an integer value of 3. Finally, most collections implement the Iterable interface which allows you iterate over the elements using an enhanced for loop just as with arrays. 1 for(Double x : values) { 2 System.out.println(x); 3 } There are dozens of other methods that allow you to insert, remove, and retrieve elements from a Java List ; refer to the documentation for details. Another type of collection supported by the Collections library is a Set . A set differs from a list in that it is unordered. There is no concept of the first element or last element. Moreover, a Set does not allow duplicate elements.3 A commonly used implementation of the Set interface is the HashSet . 1 Set<String> names = new HashSet<String>(); 2 3 names.add("Robin"); 4 names.add("Little John"); 5 names.add("Marian"); 6 7 //this has no effect since Robin is already part of the set: 8 names.add("Robin"); Since the elements in a Set are unordered, we cannot use an index-based get() method as we did with a List . Fortunately, we can still use an enhanced for loop to iterate over the elements. 1 for(String name : names) { 2 System.out.println(name); 3Duplicates are determined by how the equals() and possibly the hashCode() methods are imple- mented in your particular objects. 446
ComputerScienceOne_Page_480_Chunk2019
31.5. Dynamic Data Structures 3 } When this code executes we cannot expect any particular order of the three names. Any permutation of the three may be printed. If we executed the loop more than once we may even observe a different enumeration of the names! Finally, Java also supports a Map data structure which allows you to store key-value pairs. The keys and values can be any object type and are specified by two parameters when you create the map. A common implementation is the HashMap . 1 //define a map that maps integers (keys) to strings (values): 2 Map<Integer, String> numbers = new HashMap<Integer, String>(); 3 4 //add key-value pairs: 5 numbers.add(10, "ten"); 6 numbers.add(20, "twenty"); 7 8 //retrieve values given a key: 9 String name = numbers.get(20); //name equals "twenty" 10 11 //invalid mappings result in null: 12 name = numbers.get(30); //name is null The Collections library is much more extensive than what we’ve presented here. It includes implementations of stacks, queues, hash tables, balanced binary search trees, and many other dynamic data structure implementations. 447
ComputerScienceOne_Page_481_Chunk2020
32. Strings As we’ve previously seen, Java has a String class in the standard JDK. Internally, Java strings are stored as arrays of characters. However, because of the String class, we never directly interact with this representation. Making using strings much easier than in other languages. Java strings have also supported Unicode since version 1. Java provides many methods as part of the String class that can be used to process and manipulate strings. These methods do not change the strings since strings in Java are immutable. Instead, these methods operate by returning a new modified string that can then be stored in a variable. 32.1. Basics We can declare String variables and assign them values using the regular assignment operator. 1 String firstName = "Thomas"; 2 String lastName = "Waits"; 3 4 //we can also reassign values 5 firstName = "Tom"; Note that the reassignment in the last line in the example does not change the original string. It just makes the variable firstName point to a new string. If there are no other references to the old string, it becomes eligible for garbage collection and the JVM takes care of it. Strings can be copied using the String class’s copy constructor: String copy = new String(firstName); However, since strings are immutable, there is rarely reason to create such a deep copy. Though you can’t change individual characters in a string, you can access them using the 449
ComputerScienceOne_Page_483_Chunk2021
32. Strings charAt() method and providing an index. Characters in a string are 0-indexed just as with elements in arrays. 1 String fullName = "Tom Waits"; 2 //access individual characters: 3 char firstInitial = fullName.charAt(0); //'T' 4 char lastInitial = fullName.charAt(4); //'W' 5 6 if(fullName.charAt(8) == 's') { 7 ... 8 } 32.2. String Methods The String class provides dozens of convenient methods that allow you to process and modify strings. We highlight a few of the more common ones here. A full list of supported functions can be found in standard documentation. Length When accessing individual characters in a string, it is necessary to know the length of the string so that we do not access invalid characters. The length() method returns an int that represents the number of characters in the string. 1 String s = "Hello World!"; 2 char last = s.charAt(s.length()-1); 3 //last is '!' Using this method we can easily iterate over each character in a string. 1 for(int i=0; i<fullName.length(); i++) { 2 System.out.printf("fullName[%d] = %c\n", i, fullName.charAt(i)); 3 } 4 450
ComputerScienceOne_Page_484_Chunk2022
32.2. String Methods 5 //or we can use toCharArray and an enhanced for loop: 6 for(char c : fullName.toCharArray()) { 7 System.out.println(c); 8 } Concatenation Java has a concatenation operator built into the language. The familiar plus sign, + can be used to combine one or more strings by appending them to each other. Concatenation results in a new string. 1 String firstName = "Tom"; 2 String lastName = "Waits"; 3 4 String formattedName = lastName + ", " + firstName; 5 //formattedName now contains "Waits, Tom" Concatenation also works with numeric types and even objects. 1 int x = 10; 2 double y = 3.14; 3 4 String s = "Hello, x is " + x + " and y = " + y; 5 //s contains "Hello, x is 10 and y = 3.14" When used with objects, the concatenation operator internally invokes the object’s toString() method. The plus operator as a concatenation operator is actually syntactic sugar. When the code is compiled, it is actually replaced with equivalent code that uses a series of the StringBuilder class’s (a mutable version of the String class) append() method. The compiler will actually replace the code using the concatenation operator with code that does not use the concatenation operator. The example above would be replaced with something like the following. 451
ComputerScienceOne_Page_485_Chunk2023
32. Strings 1 String firstName = "Tom"; 2 String lastName = "Waits"; 3 4 String formattedName = new StringBuilder(lastName) 5 .append(", ") 6 .append(firstName) 7 .toString(); You can also use the StringBuilder class yourself directly. Computing a Substring There are two methods that allow you to compute a substring of a string. The first allows you to specify a beginning index with the entire remainder of the string being included in the returned string. The second allows you to specify a beginning index as well as an ending index. In both cases, the beginning index is inclusive (that is the resulting string includes the character at that index), but in the second, the ending index is exclusive (the character at the end index is not included). 1 String name = "Thomas Alan Waits"; 2 3 String firstName = name.substring(0, 6); //"Thomas" 4 String middleName = name.substring(7, 11); //"Alan" 5 String lastName = name.substring(12); //"Waits" The result of the two argument substring() method will always have length equal to endIndex - beginIndex . 32.3. Arrays of Strings We often need to deal with collections of strings. In Java, we can define arrays of strings. Indeed, we’ve seen arrays of strings before. In a Java class’s main() method, command line arguments are passed as an array of strings: public static void main(String args[]) 452
ComputerScienceOne_Page_486_Chunk2024
32.4. Comparisons We can create our own arrays of strings similar to how we created arrays of int and double types. 1 //create an array that can hold 5 strings 2 String names[] = new String[5]; 3 4 names[0] = "Margaret Hamilton"; 5 names[1] = "Ada Lovelace"; 6 names[2] = "Grace Hopper"; 7 names[3] = "Marie Curie"; 8 names[4] = "Hedy Lamarr"; Better yet, we can use dynamic collections such as a List or a Set of strings. 1 List<String> names = new ArrayList<String>(); 2 3 names.add("Margaret Hamilton"); 4 names.add("Ada Lovelace"); 5 names.add("Grace Hopper"); 6 names.add("Marie Curie"); 7 names.add("Hedy Lamarr"); 8 9 System.out.println(names.get(2)); //prints "Grace Hopper" 32.4. Comparisons When comparing strings in Java, we cannot use the numerical comparison operators such as == , or < . Because strings are objects, using these operators actually compares the variables’ memory addresses. 1 String a = new String("Hello World!"); 2 String b = new String("Hello World!"); 3 4 if(a == b) { 5 System.out.println("strings match!"); 453
ComputerScienceOne_Page_487_Chunk2025
32. Strings 6 } The code above will not print anything even though the strings a and b have the same content. This is because a == b is comparing the memory address of the two variables. Since they point to different memory addresses (created by two separate calls to the constructors) they will not be equal. Instead, the String class provides a compareTo() method1 that takes another string and returns something negative, zero, or something positive depending on the relative lexicographic ordering of the strings. 1 int x; 2 String a = "apple"; 3 String b = "zelda"; 4 String c = "Hello"; 5 x = a.compareTo("banana"); //x is negative 6 x = b.compareTo("mario"); //x is positive 7 x = c.compareTo("Hello"); //x is zero 8 9 //shorter strings precede longer strings: 10 x = a.compareTo("apples"); //x is negative 11 12 String d = "Apple"; 13 x = d.compareTo("apple"); //x is negative In the last example, "Apple" precedes "apple" since uppercase letters are ordered before lowercase letters according to the ASCII table. We can also make case-insensitive comparisons using the compareToIgnoreCase() method which works the same way. Here, d.compareToIgnoreCase("apple") will return zero as the two strings are the same ignoring the cases. Note that the commonly used equals() method only returns true or false depending on whether or not two strings are the same or different. They cannot be used to provide a relative ordering of two strings. 1This method is part of the String class due to the fact that strings implement the Comparable interface which defines a lexicographic ordering. 454
ComputerScienceOne_Page_488_Chunk2026
32.5. Tokenizing 1 String a = "apple"; 2 String b = "apple"; 3 String c = "Hello"; 4 5 boolean result; 6 result = a.equals(b); //true 7 result = a.equals(c); //false 32.5. Tokenizing Recall that tokenizing is the process of splitting up a string using some delimiter. For example, the comma delimited string, "Smith,Joe,12345678,1985-09-08" contains four pieces of data delimited by a comma. Our aim is to split this string up into four separate strings so that we can process each one. Java provides a very simple method to do this called split() that takes a string delimiter and returns an array of strings containing the tokens. For example, 1 String data = "Smith,Joe,12345678,1985-09-08"; 2 3 String tokens[] = data.split(","); 4 //tokens is { "Smith", "Joe", "12345678", "1985-09-08" } 5 6 String dateTokens[] = tokens[3].split("-"); 7 //dateTokens is now { "1985", "09", "08" } The delimiter this method uses is actually a regular expression; a sequence of characters that define a search pattern in which special characters can be used to define complex patterns. For example, the complex expression, ^[+-]?(\d+(\.\d+)?|\.\d+)([eE][+-]?\d+)?$ will match any valid numerical value including scientific notation. We will not cover regular expressions in depth, but to demonstrate their usefulness, here’s an example by which you can split a string along any and all whitespace: 455
ComputerScienceOne_Page_489_Chunk2027
32. Strings 1 String s = "Alpha Beta \t Gamma \n Delta \t\nEpsilon"; 2 String tokens[] = s.split("[\\s]+"); 3 //tokens is now { "Alpha", "Beta", "Gamma", "Delta", "Epsilon" } 456
ComputerScienceOne_Page_490_Chunk2028
33. File I/O Java provides several different classes and utilities that support manipulating and pro- cessing files. In general, most file operations may result in an IOException , a checked exception that must be caught and handled. 33.1. File Input Though there are several ways that you can do file input, the easiest is to use the familiar Scanner class. We’ve previously used this class to read from the standard input, System.in , but it can also be used to read from a file using the File class (in the java.io package). The File class is just a representation of a file resource and does not represent the actual file (it cannot be opened and closed). To initialize a Scanner to read from a file you can use the following. 1 Scanner s = null; 2 try { 3 s = new Scanner(new File("/user/apps/data.txt")); 4 } catch (FileNotFoundException e) { 5 //handle the exception here 6 } When initializing a Scanner to read from a file, the exception, FileNotFoundException must be caught and handled as it is a checked exception. Otherwise, once created, the Scanner class does not throw any checked exceptions. Once created, you can use the usual methods and functionality provided by the Scanner class including reading the nextInt() , nextDouble() , next string using next() or even the entire nextLine() . This last one can be used in conjunction with hasNext() to read an entire file, line-by-line. 457
ComputerScienceOne_Page_491_Chunk2029
33. File I/O 1 String line; 2 while(s.hasNext()) { 3 line = s.nextLine(); 4 //process the line 5 } Once we are done reading the file, we can close the Scanner to free up resources: s.close(); . We could have placed all this code within one large try-catch block with perhaps a finally block to close the Scanner once were were done to ensure that it would be closed regardless of any exceptions. However, Java 7 introduced a new construct, the try-with-resources statement. The try-with-resources statement allows us to place the initialization of a “closeable” resource (defined by the AutoCloseable interface) into the try statement. The JVM will then automatically close this resource upon the conclusion of the try-catch block. We can still provide a finally block if we wish, but this relieves us of the need to explicitly close the resource in a finally block. A full example: 1 File f = new File("/user/apps/data.txt"); 2 //initialize a Scanner in the try statement 3 try (Scanner s = new Scanner(f)) { 4 String line; 5 while(s.hasNext()) { 6 line = s.nextLine(); 7 //process the line 8 } 9 } catch (Exception e) { 10 //handle the exception here 11 } Using the Scanner class to do file input offers a more abstract interaction with a file. It also uses a buffered input stream for performance. Binary files can still be read using nextByte() . However, when dealing with binary files, the better solution is to use a class that models and abstracts the underlying file. For example, if you are reading or writing an image file, you should use the java.awt.Image class to read and write to files. The JDK and other libraries offer a wide variety of classes to model all kinds of data. 458
ComputerScienceOne_Page_492_Chunk2030
33.2. File Output 33.2. File Output There are several ways to achieve file output, but we’ll look at the simplest and most useful way. Java provides a PrintWriter class which offers many convenient methods for writing primitive and String types in a formatted manner. It has the usual print() and println() methods that we are familiar with as well as a printf() style method for formatting. PrintWriter is also buffered, depending on how you instantiate it, it might “flush” its buffer after every endline character or you may do it manually by invoking the flush() method. 1 int x = 10; 2 double pi = 3.14; 3 PrintWriter pw = null; 4 try { 5 pw = new PrintWriter(new File("data.txt")); 6 } catch(FileNotFoundException fnfe) { 7 throw new RuntimeException(fnfe); 8 } 9 10 pw.println("Hello World!"); 11 pw.println(x); 12 pw.printf("x = %d, pi = %f\n", x, pi); 13 14 pw.close(); The close() method will conveniently close all the underlying resources and flush the buffer for us, writing any buffered data to the file. In addition, PrintWriter implements AutoCloseable and so it can be used in a try-catch-with resources statement. Another “convenience” of PrintWriter is that is “swallows” exceptions (just as the Scanner class did). That means we don’t have to deal explicitly with the checked IOException s that the underlying class(es) throw as the PrintWriter silently catches them (though doesn’t handle them). However, this can also be viewed as a disadvantage in that if we want to do error handling, we need to manually check if there was an error (using checkError() ). The PrintWriter class is intended mostly for formatted output. It does not provide a way to write binary data to an output file. Just as with binary input, it is best to use a class that abstracts the file type and data so that we don’t have to deal with the low-level details of the binary data. 459
ComputerScienceOne_Page_493_Chunk2031
33. File I/O However, if necessary, binary output can be done using a FileOutputStream . Typically, you can load all your data into a byte array and dump it all at once. 1 byte data[] = ...; 2 try (FileOutputStream fos = 3 new FileOutputStream(new File("outfile.bin")) ){ 4 fos.write(data); 5 } catch(IOException ioe) { 6 throw new RuntimeException(ioe); 7 } This example uses a try-with-resources statement so the FileOutputStream will auto- matically be closed for us. You could wrap a FileOutputStream in a BufferedWriter , but it will likely not gain you anything in terms of performance. A buffered output stream is better if your writes are frequent and “small.” Here small means smaller than the size of the buffer ( BufferedWriter is typically 8KB). Writing several individual integer values for example would be better done by buffering them and writing them all at once. In our example, we simply wanted to dump a bunch of data, likely more than 8KB in practice, all at once. Moreover, using a BufferedWriter would lose us the ability to write raw byte data. 460
ComputerScienceOne_Page_494_Chunk2032
34. Objects Java is a class-based object-oriented programming language, meaning that it facilitates the creation of objects through the use of classes. Classes are essentially “blueprints” for creating instances of objects. We’ve been implicitly using classes all along since everything in Java is a class or belongs to a class. Now, however, we will start using classes in more depth rather than simply using static methods. An object is an entity that is characterized by identity, state and behavior. The identity of an object is an aspect that distinguishes it from other objects. The variables and values that a variable takes on within an object is its state. Typically the variables that belong to an object are referred to as member variables. Finally, an object may also have functions that operate on the data of an object. In the context of object-oriented programming, a function that belongs to an object is referred to as a member method. As a class-based object-oriented language, Java implements objects using classes. A class is essentially a blueprint for creating instances of the class. A class simply specifies the member variables and member methods that belong to instances of the class. We can create actual instances through the use of special constructor methods. To begin, let’s define a class that models a student by defining member variables to support a first name, last name, a unique identifier, and GPA. To declare a class, we use the class keyword. Inside the class (denoted by curly brackets), we place any code that belongs to the class. To declare member variables within a class, we use the normal variable declaration syntax, but we do so outside any methods. 1 package unl.cse; 2 3 public class Student { 4 5 //member variables: 6 String firstName; 7 String lastName; 8 int id; 9 double gpa; 10 11 } 461
ComputerScienceOne_Page_495_Chunk2033
34. Objects Recall that a package declaration allows you to organize classes and code within a package (directory) hierarchy. Moreover, source code for a class must be in a source file with the same name (and is case sensitive) with the .java extension. Our Student class would need to be in a file named Student.java and would be compiled to a class named Student.class . 34.1. Data Visibility Recall that encapsulation involves not only the grouping of data, but the protection of data. To provide for the protection of data, Java defines several visibility keywords that specify what segments of code can “see” the variables. Visibility in this context determines whether or not a segment of code can access and/or modify the variable’s value. Java defines four levels of visibility using they keywords public , protected and private (a fourth level is defined by the absence of any of these keywords). Each of these keywords can be applied to both member variables and member methods. • public – This is the least restrictive visibility level and makes the member variable visible to every class. • protected – This is a bit more restrictive and makes it so that the member variable is only visible to the code in the same class, same package, or any subclass of the class.1 • No modifier – the absence of any modifier means that the member variable is visible to any class in the same package. This is also referred to as the default or package protected visibility level. • private – this is the most restrictive visibility level, private member variables are only visible to instances of the class itself. As we’ll see later this also means that the member variables are visible between instances. That is, one instance can see another instance’s variables. Table 34.1 summarizes these four keywords with respect to their access levels. It is important to understand that protection in the context of encapsulation and does not involve protection in the sense of “security.” The protection is this context is a design principle. Limiting the access of variables only affects how the rest of the code base interacts with our class and its data. Encapsulation can easily be “broken” by other 1Subclasses are involved with inheritance, another object-oriented programming concept that we will not discuss here). 462
ComputerScienceOne_Page_496_Chunk2034
34.2. Methods code (through reflection2 or other means) and the values of variables can be accessed or modified. Modifier Class Package Subclass World public Y Y Y Y protected Y Y Y N none (default) Y Y N N private Y N N N Table 34.1.: Java Visibility Keywords & Access Levels We now update our class declaration to incorporate these visibility keywords. In general, it is best practice to make member variables private and control access to them via accessor and mutator methods (see below) unless there is a compelling design reason to increase their visibility. 1 package unl.cse; 2 3 public class Student { 4 5 //member variables: 6 private String firstName; 7 private String lastName; 8 private int id; 9 private double gpa; 10 11 } 34.2. Methods The third aspect of encapsulation involves the grouping of methods that act on an object’s data (its state). Within a class, we can declare member methods using the syntax we’re already familiar with. We declare a member method by providing a signature and body. We can use the same visibility keywords as with member variables in order to allow or restrict access to the methods. With methods, visibility and access determine whether or not the method may be invoked. 2Reflection is a mechanism by which you can write code that modifies other code at runtime. It is more of an aspect-oriented programming paradigm. 463
ComputerScienceOne_Page_497_Chunk2035
34. Objects In contrast to the methods we defined in Chapter 29, when defining a member method, we do not use the static keyword. Making a variable or a method static means that the method belongs to the class and not to instances of the class. We add to our example by providing two public methods that compute and return a result on the member variables. We also use Javadoc style comments to document each member method. 1 package unl.cse; 2 3 public class Student { 4 5 //member variables: 6 private String firstName; 7 private String lastName; 8 private int id; 9 private double gpa; 10 11 /** 12 * Returns a formatted String of the Student's 13 * name as Last, First. 14 */ 15 public String getFormattedName() { 16 return lastName + ", " + firstName; 17 } 18 19 /** 20 * Scales the GPA, which is assumed to be on a 21 * 4.0 scale to a percentage. 22 */ 23 public double getGpaAsPercentage() { 24 return gpa / 4.0; 25 } 26 27 } 34.2.1. Accessor & Mutator Methods Since we have made all the member variables private , no code outside the class may access or modify their values. It is generally good practice to make member variables private to restrict access. However, if we still want code outside the object to access 464
ComputerScienceOne_Page_498_Chunk2036
34.2. Methods or mutate (that is, change) an instance’s variables, we can define accessor and mutator methods (or just simply getter and setter methods) to facilitate this. Each getter method returns the value of the instance’s variable while each setter method takes a value and sets the instance’s variable to the new value. It is common to name each getter/setter by prefixing a get and set to the variable’s name using lower camel casing. For example: 1 public String getFirstName() { 2 return firstName; 3 } 4 5 public void setFirstName(String firstName) { 6 firstName = firstName; 7 } In the setter example, there is a problem: the code has no effect. There are two variables named firstName : the instance’s member variable and the variable in the method parameter. The scoping rules of Java mean that the parameter variable name(s) take precedent. This code has no effect because it is setting the parameter variable to itself. It is essentially doing the following. 1 int a = 10; 2 a = a; To solve this, we use something called open recursion. When an instance of a class is created, for example, Student s = ...; the reference variable s is how we can refer to it. This variable, however, exists outside the class. Inside the class, we need a way to refer to the instance itself. In Java we use the keyword this to refer to the instance inside the class. For example, the member variables of an instance can be accessed using the this keyword along with the dot operator (more below). In our example, this.firstName would refer to the instance’s firstName and not to the parameter variable. Even when it is not necessary to use the this keyword (as in the getter example above) it is still best practice to do so. Our updated getters and setter methods would thus look like the following. 465
ComputerScienceOne_Page_499_Chunk2037
34. Objects 1 public String getFirstName() { 2 return this.firstName; 3 } 4 5 public void setFirstName(String firstName) { 6 this.firstName = firstName; 7 } One advantage to using getters and setters (as opposed to naively making everything public ) is that you can have greater control over the values that your variables can take. For example, we may want to do some data validation by rejecting null values or invalid values. For example: 1 public void setFirstName(String firstName) { 2 if(firstName == null) { 3 throw new IllegalArgumentException("names cannot be null"); 4 } else { 5 this.firstName = firstName; 6 } 7 } 8 9 public void setGpa(double gpa) { 10 if(gpa < 0.0 || gpa > 4.0) { 11 throw new IllegalArgumentException("GPAs must be in [0, 4.0]"); 12 } else { 13 this.gpa = gpa; 14 } 15 } Controlling access of member variables through getters and setters is good encapsulation. Doing so makes your code more predictable and more testable. Making your member variables public means that any piece of code can change their values. There is no way to do validation or prevent bad values. In fact, it is good practice to not even have setter methods. If the value of member variables cannot be changed, it makes the object immutable. We’ve seen this before with the built-in wrapper classes ( Integer , String , etc.). Immutability is a nice property because it makes instances of the class thread-safe. That is, we can use instances of 466
ComputerScienceOne_Page_500_Chunk2038
34.3. Constructors the class in a multithreaded program without having to worry about threads changing the state of instances on one another. Immutable classes are also safer to use in certain collections such as a Set . Elements in a Set are unique; attempting to add a duplicate element will have no effect on the Set . However, if the elements we add are mutable, we could end up with duplicates (see Section 34.5). 34.3. Constructors If we make the (good) design decision to make our class immutable, we still need a way to initialize the object’s member variables. This is where constructors come in. A constructor is a special method that specifies how an object is constructed. With built-in primitive variables such as an int , the Java language (compiler and JVM) “know” how to interpret and assign a value to such a variable. However, with user-defined objects such as our Student class, we need to specify how the object is created. A constructor method has special syntax. Though it may still one of the visibility keywords, it has no return type and its name is the same as the class. A constructor may take any number of parameters. For example, the following constructor allows someone to construct a Student instance and specify all four member variables. 1 public Student(String firstName, String lastName, 2 int id, double gpa) { 3 this.firstName = firstName; 4 this.lastName = lastName; 5 this.id = id; 6 this.gpa = gpa; 7 } Java allows us to define multiple constructors, or even no constructor at all. If we do not specify a constructor, Java provides a default, no argument constructor. This constructor uses default values for all member variables (zero for numerical types, false for boolean types, and null for objects). If we do specify a constructor, this default constructor becomes unavailable. However, we can always “restore” it by explicitly defining it. 1 public Student() { 2 this.firstName = null; 3 this.lastName = null; 4 this.id = 0; 467
ComputerScienceOne_Page_501_Chunk2039
34. Objects 5 this.gpa = 0.0; 6 } Alternatively, we can define constructors that accept a subset of variable values. 1 public Student(String firstName, String lastName) { 2 this.firstName = firstName; 3 this.lastName = lastName; 4 this.id = 0; 5 this.gpa = 0.0; 6 } In both of these examples, we repeated a lot of code. One shortcut is to make all your constructors call the most general constructor. To invoke another constructor, we use the this keyword as a method call. For example: 1 public Student() { 2 this(null, null, 0, 0.0); 3 } 4 5 public Student(String firstName, String lastName) { 6 this(firstName, lastName, 0, 0.0); 7 } Another, very useful type of constructor is the copy constructor that allows you to make a copy of an instance by passing it to a constructor. The following example copies each of the member variables of s into this . 1 public Student(Student s) { 2 this(s.firstName, s.lastName, s.id, s.gpa); 3 } 468
ComputerScienceOne_Page_502_Chunk2040
34.4. Usage 34.4. Usage Once we have defined our class and its constructors, we can create and use instances of it. Just as with regular variables, we need to declare instances of a class by providing the type and a variable name. For example: 1 Student s = null; 2 Student t = null; Both of these declarations are simply just reference variables. They may refer to an instance of the class Student , but we have initialized them to null . To make these variables refer to valid instances, we invoke a constructor by using the new keyword and providing arguments to the constructor. 1 Student s = new Student("Alan", "Turing", 1234, 3.4); 2 Student t = new Student("Margaret", "Hamilton", 4321, 3.9); The process of creating a new instance by invoking a constructor is referred to as instantiation. Once instances have been instantiated, they can be used by invoking their methods via the dot operator. The dot operator is used to select a member variable (if public ) or member method. 1 System.out.println(s.getFormattedName()); 2 3 if(s.getGpa() < t.getGpa()) { 4 System.out.println(t.getFirstName() + " has a better GPA"); 5 } 34.5. Common Methods Every class in Java has several methods that they inherit from the java.lang.Object class. Here, we will highlight three of these important methods. 469
ComputerScienceOne_Page_503_Chunk2041
34. Objects The toString() method returns a String representation of the object. However, the default behavior that all classes inherit from the Object class is that it returns a string containing the fully qualified class name (package and class name) along with a hexadeci- mal representation of the JVM memory address at which the instance is stored. An exam- ple with our Student class may produce something like: unl.cse.Student@272d7a10 . We can override this functionality and change the behavior of the toString() method to return whatever we want. To do so, we simply define the function (with a signature that matches the toString() method in the Object class) in our class. 1 public String toString() { 2 return String.format("%s, %s (ID = %d); %.2f", 3 this.lastName, 4 this.firstName, 5 this.id, 6 this.gpa); 7 } This example would return a String containing something similar to "Hamilton, Margaret (ID = 4321); 3.90" The toString() method is a very convenient way to print instances of your class. Two other methods, the equals() and the hashCode() method are used extensively by other classes such as the Collections library. The equals() method: public boolean equals(Object obj) takes another object obj and returns true or false depending on whether or not the instance is “equal” to obj . Recall that identity is one of the defining characteristics of objects. This method is how Java achieves identity; this method allows you to define what “equality” means. By default, the behavior inherited from the Object class simply checks if the object, this and the passed object, obj are located at the same memory address, essentially (this == obj) . However, conceptually we may want different behavior. For example, two Student objects may be the same if they have the same id value (it is, after all supposed to be a unique identifier). Alternatively, we may consider two objects to be the same if every member variable holds the same value. Even with only a four member variables, the logic can get quite complicated, especially if we have to account for null values. For 470
ComputerScienceOne_Page_504_Chunk2042
34.5. Common Methods this reason, many IDEs provide functionality to automatically generate such methods. The following example was generated by an IDE. 1 public boolean equals(Object obj) { 2 if (this == obj) { 3 return true; 4 } 5 if (obj == null) { 6 return false; 7 } 8 if (!(obj instanceof Student)) { 9 return false; 10 } 11 Student other = (Student) obj; 12 if (firstName == null) { 13 if (other.firstName != null) { 14 return false; 15 } 16 } else if (!firstName.equals(other.firstName)) { 17 return false; 18 } 19 if (Double.doubleToLongBits(gpa) != 20 Double.doubleToLongBits(other.gpa)) { 21 return false; 22 } 23 if (lastName == null) { 24 if (other.lastName != null) { 25 return false; 26 } 27 } else if (!lastName.equals(other.lastName)) { 28 return false; 29 } 30 if (nuid != other.nuid) { 31 return false; 32 } 33 return true; 34 } Related, the hashCode() method, public int hashCode() returns an integer representation of the object. As with the equals() method, the default behavior is to return a value associated with the memory address of the instance. In general, however, the behavior should be overridden to be based on the entire state of the object. A hash is simply a function that maps data to a “small” set of values. In this context, we are mapping object instances to integers so that they can be used in hash table-based data structures such as HashSet or HashMap . The hashCode() method is used to map an instance to an integer so that it can be used as an index in these data structures. Again, most IDEs will provide functionality to generate a good implementation for the hashCode() method (as the example below is). How ever you design the equals() and hashCode() method, there is a requirement: 471
ComputerScienceOne_Page_505_Chunk2043
34. Objects if two instances are equal (that is, equals() returns true ) then they must have the same hashCode() value. This requirement is necessary to ensure that hash table-based data structures operate properly. It is okay if unequal objects have equal or unequal hash values. This rule only applies when the objects are equal. 1 public int hashCode() { 2 final int prime = 31; 3 int result = 1; 4 result = prime * result + ((firstName == null) ? 0 : 5 firstName.hashCode()); 6 long temp; 7 temp = Double.doubleToLongBits(gpa); 8 result = prime * result + (int) (temp ^ (temp >>> 32)); 9 result = prime * result + ((lastName == null) ? 0 : 10 lastName.hashCode()); 11 result = prime * result + nuid; 12 return result; 13 } 34.6. Composition Another important concept when designing classes is composition. Composition is a mechanism by which an object is made up of other objects. One object is said to “own” an instance of another object. We’ve already seen this with our Student example: the Student class owns two instances of the String class. To illustrate the importance of composition, we could extend the design of our Student class to include a date of birth. However, a date of birth is also made up of multiple pieces of data (a year, a month, a date, and maybe even a time and/or locale). We could design our own date/time class to model this, but its generally best to use what the language already provides. Java 8 introduced the java.time package in which there are many updated and improved classes for dealing with dates and times. The class LocalDate for example, could be used to model a date of birth: 1 private LocalDate dateOfBirth; 472
ComputerScienceOne_Page_506_Chunk2044
34.6. Composition We can take this concept further and design our classes to own collections of other classes. For example, we could define a Course class and then update our Student class to own a collection of Course objects representing a student’s class schedule (this type of collection ownership is sometimes referred to as aggregation rather than strict composition). 1 private Set<Course> schedule; Both of these updates beg the question: who is responsible for instantiating the instances of dateOfBirth and the schedule ? Should we force the “outside” user of our Student class to build the LocalDate instance and pass it to a constructor? Should we allow the outside code to simply provide us a date of birth as a string? Both of these design choices have advantages and disadvantages that have to be considered. What about the course schedule? We could require that a user provide the constructor with a pre-computed Set of courses, but care must be taken. Consider the following (partial) example. 1 public Student(..., Set<Course> schedule) { 2 ... 3 this.schedule = schedule; 4 } This is an example of a shallow copy: the instance’s schedule variable is referencing the same collection as the parameter variable. If a change is made, say a course is added, via one of these references, then the change is effectively made for both. If we are going to design it this way, it would be better to make a deep copy of the set of courses: 1 public Student(..., Set<Course> schedule) { 2 ... 3 this.schedule = new HashSet<Course>(schedule); 4 } This is the same pattern we described above: almost every data structure in the Java Collections library has a (deep) copy constructor. 473
ComputerScienceOne_Page_507_Chunk2045
34. Objects Alternatively, we could make our design a bit more flexible by allowing the construction of a Student instance without having to provide a course schedule. Instead, we could add a method that allowed the outside code to add a course to the schedule . Something like the following. 1 public void addCourse(Course c) { 2 this.schedule.add(c); 3 } This adds some flexibility to our object, but removes the immutability property. Design is always a balance and compromise between competing considerations. 34.7. Example We present the full and completed Student class in Code Sample 34.1. 474
ComputerScienceOne_Page_508_Chunk2046
34.7. Example 1 package unl.cse; 2 3 public class Student { 4 5 private String firstName; 6 private String lastName; 7 private int id; 8 private double gpa; 9 10 public Student(String firstName, String lastName, int id, double gpa) { 11 this.firstName = firstName; 12 this.lastName = lastName; 13 this.id = id; 14 this.gpa = gpa; 15 } 16 17 public Student() { 18 this(null, null, 0, 0.0); 19 } 20 21 public Student(String firstName, String lastName) { 22 this(firstName, lastName, 0, 0.0); 23 } 24 25 public String getFirstName() { 26 return firstName; 27 } 28 29 public String getLastName() { 30 return lastName; 31 } 32 33 public int getId() { 34 return id; 35 } 36 37 public double getGpa() { 38 return gpa; 39 } 40 41 /** 42 * Returns a formatted String of the Student's 43 * name as Last, First. 44 */ 45 public String getFormattedName() { 46 return lastName + ", " + firstName; 475
ComputerScienceOne_Page_509_Chunk2047
34. Objects 47 } 48 49 /** 50 * Scales the GPA, which is assumed to be on a 51 * 4.0 scale to a percentage. 52 */ 53 public double getGpaAsPercentage() { 54 return gpa / 4.0; 55 } 56 57 @Override 58 public String toString() { 59 return String.format("%s, %s (ID = %d); %.2f", 60 this.lastName, 61 this.firstName, 62 this.id, 63 this.gpa); 64 } 65 66 @Override 67 public int hashCode() { 68 final int prime = 31; 69 int result = 1; 70 result = prime * result + ((firstName == null) ? 0 : firstName.hashCode()); 71 long temp; 72 temp = Double.doubleToLongBits(gpa); 73 result = prime * result + (int) (temp ^ (temp >>> 32)); 74 result = prime * result + id; 75 result = prime * result + ((lastName == null) ? 0 : lastName.hashCode()); 76 return result; 77 } 78 79 80 @Override 81 public boolean equals(Object obj) { 82 if (this == obj) { 83 return true; 84 } 85 if (obj == null) { 86 return false; 87 } 88 if (!(obj instanceof Student)) { 89 return false; 90 } 91 Student other = (Student) obj; 92 if (firstName == null) { 476
ComputerScienceOne_Page_510_Chunk2048
34.7. Example 93 if (other.firstName != null) { 94 return false; 95 } 96 } else if (!firstName.equals(other.firstName)) { 97 return false; 98 } 99 if (Double.doubleToLongBits(gpa) != Double.doubleToLongBits(other.gpa)) { 100 return false; 101 } 102 if (id != other.id) { 103 return false; 104 } 105 if (lastName == null) { 106 if (other.lastName != null) { 107 return false; 108 } 109 } else if (!lastName.equals(other.lastName)) { 110 return false; 111 } 112 return true; 113 } 114 115 116 117 } Code Sample 34.1.: The completed Java Student class. 477
ComputerScienceOne_Page_511_Chunk2049
35. Recursion Java supports recursion with no special syntax necessary. However, as an object-oriented language, recursion is generally expensive and iterative or other non-recursive solutions are generally preferred. We present a few examples to demonstrate how to write recursive methods in Java. The first example of a recursive method we gave was the toy count down example. In Java it could be implemented as follows. 1 public static void countDown(int n) { 2 if(n == 0) { 3 System.out.println("Happy New Year!"); 4 } else { 5 System.out.println(n); 6 countDown(n-1); 7 } 8 } As another example that actually does something useful, consider the following recursive summation method that takes an array and an index variable. The recursion works as follows: if the index variable has reached the size of the array, it stops and returns zero (the base case). Otherwise, it makes a recursive call to recSum() , incrementing the index variable by 1. When the method returns, it adds its result to the i-th element in the array. To invoke this method we would call it with an initial value of 0 for the index variable: recSum(arr, 0) . 1 public static int recSum(int arr[], int i) { 2 if(i == arr.length) { 3 return 0; 4 } else { 5 return recSum(arr, i+1) + arr[i]; 6 } 7 } This example was not tail-recursive as the recursive call was not the final operation (the sum was the final operation). To make this method tail recursive, we can carry the summation through to each method call ensuring that the summation is done prior to 479
ComputerScienceOne_Page_513_Chunk2050
35. Recursion the recursive method call. 1 public static int recSumTail(int arr[], int i, int sum) { 2 if(i == arr.length) { 3 return sum; 4 } else { 5 return recSumTail(arr, i+1, sum + arr[i]); 6 } 7 } As another example, consider the following Java implementation of the naive recursive Fibonacci sequence. An additional condition has been included to check for “invalid” negative values of n for which an exception is thrown. 1 public static int fibonacci(int n) { 2 if(n < 0) { 3 throw new IllegalArgumentException("Undefined for n < 0"); 4 } else if(n <= 1) { 5 return 1; 6 } else { 7 return fibonacci(n-1) + fibonacci(n-2); 8 } 9 } Java is not a language that provides implicit memoization. Instead, we need to explicitly keep track of values using a table. In the following example, we use a Map data structure to store previously computed values. 1 public static int fibMemoization(int n, Map<Integer, Integer> m) { 2 if(n < 0) { 3 throw new IllegalArgumentException("Undefined for n < 0"); 4 } else if(n <= 1) { 5 return 1; 6 } else { 7 Integer result = m.get(n); 8 if(result == null) { 9 Integer a = fibMemoization(n-1, m); 10 Integer b = fibMemoization(n-2, m); 11 result = a + b; 12 m.put(n, result); 13 } 480
ComputerScienceOne_Page_514_Chunk2051
14 return result; 15 } 16 } Java provides an arbitrary precision data type, BigInteger that can be used to compute arbitrarily large integer values. Since Fibonacci numbers grow exponentially, using an int we could only represent up to to F45. Using BigInteger we can support much larger values. An example: 1 public static BigInteger fibMem(int n, Map<Integer, BigInteger> m) { 2 if(n < 0) { 3 throw new IllegalArgumentException("Undefined for n < 0"); 4 } else if(n <= 1) { 5 return BigInteger.ONE; 6 } else { 7 BigInteger result = m.get(n); 8 if(result == null) { 9 BigInteger a = fibMem(n-1, m); 10 BigInteger b = fibMem(n-2, m); 11 result = a.add(b); 12 m.put(n, result); 13 } 14 return result; 15 } 16 } 481
ComputerScienceOne_Page_515_Chunk2052
36. Searching & Sorting Java provides several methods to search and sort arrays as well as List s of elements of any type. These methods are able to operate on collections of any type because there are several overloaded versions of these functions as well as versions that take a Comparator object that specifies how the elements should be ordered. 36.1. Comparators Let’s consider a “generic” Quick Sort algorithm as was presented in Algorithm 12.6. The algorithm itself specifies how to sort elements, but it doesn’t specify how they are ordered. The difference is subtle but important. Quick Sort needs to know when two elements, a, b are in order, out of order, or equivalent in order to decide which partition each element goes in. However, it doesn’t “know” anything about the elements a and b themselves. They could be numbers, they could be strings, they could be user-defined objects. A sorting algorithm still needs to be able to determine the proper ordering in order to sort. In Java this is achieved by using a Comparator object, which is responsible for comparing two elements and determining their proper order. A Comparator<T> is an interface in Java that specifies a single method: public int compare(T a, T b) • A Comparator<T> is parameterized to operate on any type T . The parameteriza- tion of T is basically a variable for a type. When you create a Comparator , you specify an actual type just as we did with with ArrayList<Integer> . However, the implementation itself is generic and can operate on any type. • The method takes two instances, a and b whose type matches the parameterized type T • The method returns an integer indicating the relative ordering of the two elements: – It returns something negative, < 0 if a comes before b (that is, a < b) – It returns zero if a and b are equal (a = b) – It returns something positive, > 0 if a comes after b (that is, a > b) There is no guarantee on the value’s magnitude, it does not necessarily return −1 or +1; it just returns something negative or positive. We’ve previously seen this pattern when comparing strings and other wrapper classes. Each of the standard types implements 483
ComputerScienceOne_Page_517_Chunk2053
36. Searching & Sorting something similar, the Comparable interface, that specifies a compareTo() method with the same basic contract. Strings for example, are ordered in lexicographic ordering. Numeric types such as Integer and Double also have compareTo() methods that order elements in ascending order. Java refers to these built-in orderings as “natural” orderings. For user-defined classes, however, we need to specify how to order them. We could use the Comparable<T> interface as the built-in wrapper classes have, but using a Comparator is more flexible. Making a class Comparable locks you into one “natural” ordering. If you wanted a different ordering, you would still have to use a Comparator . Even for the wrapper classes, if we wanted a descending order, we would need to use a Comparator . As an example, let’s write a Comparator that orders Integer types in ascending order, matching the “natural” ordering already defined. 1 Comparator<Integer> cmpInt = new Comparator<Integer>(){ 2 public int compare(Integer a, Integer b) { 3 if(a < b) { 4 return -1; 5 } else if(a == b) { 6 return 0; 7 } else { 8 return 1; 9 } 10 } 11 }; This is new syntax. When we create a Comparator in Java we are creating a new instance of a class. However, we didn’t define a class. We didn’t use public class... nor did we place it into a .java source file. Instead, this is an anonymous class declaration. The class we’ve created has no name; the cmpInt is the variable’s name, but the class itself has no name, its “anonymous.” This syntax allows us to define and instantiate a class inline without having to create a separate class source file. This is an advantage because we generally do not need multiple instances of a Comparator ; they would all have the same functionality anyway. An anonymous class allows us to create ad-hoc classes with a one-time (or a single purpose) use. Another issue with this method is that it may not be able to handle null values. When a and b get unboxed for the comparisons, if they are null , a NullPointerException will be thrown. We discuss how to deal with this below in Section 36.3.2. Another issue with this Comparator is the second case where we use the equality operator == to compare values. With the less-than operator, the two integers get unboxed and their values are compared. However, when we use the == operator on object instances, it is comparing memory addresses in the JVM, not the actual values. We could solve 484
ComputerScienceOne_Page_518_Chunk2054
36.1. Comparators this issue by rearranging our cases so that the equality is our final case, avoiding the use of the equality operator. Even better, however, we can exploit the built-in natural ordering of the integers by using the compareTo() method. 1 Comparator<Integer> cmpInt = new Comparator<Integer>(){ 2 public int compare(Integer a, Integer b) { 3 return a.compareTo(b); 4 } 5 }; What if we wanted to order integers in the opposite, descending order? We could simply write another Comparator that reversed the ordering: 1 Comparator<Integer> cmpIntDesc = new Comparator<Integer>(){ 2 public int compare(Integer a, Integer b) { 3 return b.compareTo(a); 4 } 5 }; We might be tempted to instead reuse the original comparator and write line 3 above simply as return cmpInt(b, a); However, Java will not allow you to reference another “outside” variable like this inside a Comparator object. An anonymous class in Java is a sort-of closure; a function that has a scope in which variables are bound. In this case, the anonymous class has a reference to the cmpInt variable, but it is not necessarily “bound” as the variable could be reassigned outside the Comparator . If we want to do something like this, Java forces us to make the cmpInt variable final so that it cannot be changed. To illustrate some more examples, consider the Student object we defined in Code Sample 34.1. The following Code Samples demonstrate various ways of ordering Student instances based on one or more of their member variable values. 1 /** 2 * This Comparator orders Student objects by 3 * last name/first name 4 */ 5 Comparator<Student> byName = new Comparator<Student>() { 6 @Override 7 public int compare(Student a, Student b) { 8 if(a.getLastName().equals(b.getLastName())) { 485
ComputerScienceOne_Page_519_Chunk2055
36. Searching & Sorting 9 return a.getFirstName().compareTo(b.getFirstName()); 10 } else { 11 return a.getLastName().compareTo(b.getLastName()); 12 } 13 } 14 }; 1 /** 2 * This Comparator orders Student objects by 3 * last name/first name in descending (Z-to-A) order 4 */ 5 Comparator<Student> byNameDesc = new Comparator<Student>() { 6 @Override 7 public int compare(Student a, Student b) { 8 if(b.getLastName().equals(a.getLastName())) { 9 return b.getFirstName().compareTo(a.getFirstName()); 10 } else { 11 return b.getLastName().compareTo(a.getLastName()); 12 } 13 } 14 }; 1 /** 2 * This Comparator orders Student objects by 3 * id in ascending order 4 */ 5 Comparator<Student> byId = new Comparator<Student>() { 6 @Override 7 public int compare(Student a, Student b) { 8 return a.getId().compareTo(b.getId()); 9 } 10 }; 1 /** 2 * This Comparator orders Student objects by 3 * GPA in descending order 486
ComputerScienceOne_Page_520_Chunk2056
36.2. Searching & Sorting 4 */ 5 Comparator<Student> byGpa = new Comparator<Student>() { 6 @Override 7 public int compare(Student a, Student b) { 8 return b.getGpa().compareTo(a.getGpa()); 9 } 10 }; 36.2. Searching & Sorting We now turn our attention to the search and sorting methods provided by the JDK. Most of these methods are generic implementations that either sort an array or collection using the natural ordering or take a take a parameterized Comparator<T> to determine the ordering. 36.2.1. Searching Linear Search Java Set and List collections provide several linear search methods. Both have a public boolean contains(Object o) method that returns true or false depend- ing on whether or not an object matching o is in the collection. The List collection has an additional public int indexOf(Object o) method that returns the index of the first matched element and −1 if no such element is found ( Set s are unordered and have no indices, so this method would not apply). All of these functions are equality-based and they do not take a Comparator object. Instead, the elements are compared using the object’s equals() (and possibly hashCode() ) method. The first element x such that x.equals(o) returns true is the element that is determined to match. For this reason, it is important to override both of these methods when designing objects (see Section 36.3.3). Binary Search The Arrays and Collections classes provide many variations on methods that imple- ment binary search. All of these methods assume that the array or List being searched are sorted appropriately (you cannot use binary search on a Set as it is an unordered collection). The Arrays class provides several binarySearch() methods, one for each primitive type as well as variations that allow you to search within a specified range of elements. The most generally useful version is as follows: 487
ComputerScienceOne_Page_521_Chunk2057
36. Searching & Sorting public static <T> int binarySearch(T[] a, T key, Comparator<T> c) That is, it takes an array of elements as well as key and a Comparator all of the same type T . It returns an integer representing the index at which it finds the first matching element (there is no guarantee that the first element in the sorted list is returned). If no match is found, then the method returns something negative.1 Another version has the same behavior but can be called without a Comparator , relying instead on the natural ordering of elements. For this variation, the type of elements must implement the Comparable interface. The Collections class provides a similar method, public static <T> int binarySearch(List<T> list, T key, Comparator<T> c) The only difference is that the method takes a List instead of an array. Otherwise, the behavior is the same. We present several examples in Code Sample 36.1. 36.2.2. Sorting As with searching, the Arrays and Collections classes provide parameterized sorting methods to sort arrays and List s. In Java 6 and prior, the implementation was a hybrid merge/insertion sort. Java 7 switched the implementation to Tim Sort. Here too, there are several variations that rely on the natural ordering or allow you to sort a subpart of the collection. The Arrays provides the following method, which sorts arrays of a particular type with a Comparator for that type. public static <T> void sort(T[] a, Comparator<T> c) Likewise, Collections provides the following method. public static <T> void sort(List<T> list, Comparator<T> c) Several examples of the usage of these methods are presented in Code Sample 36.2. 36.3. Other Considerations 36.3.1. Sorted Collections The Java Collections framework also provides several sorted data structures. Though an ordered collection such as a List can be sorted calling the Collections.sort() method, a sorted data structure maintains an ordering. As you add elements to the data structure, they are inserted in the appropriate spot. Such data structures also prevent you from arbitrarily inserting elements in any order. Java defines the SortedSet<T> interface for sorted collections with a TreeSet<T> implementation.2 You can construct a TreeSet<T> by providing it a Comparator<T> 1It actually returns a negative value corresponding to the insertion point at which the element would be if it had existed. 2As the name implies, the implementation is a balanced binary search tree, in particular a red-black tree. 488
ComputerScienceOne_Page_522_Chunk2058
36.3. Other Considerations 1 ArrayList<Student> roster = ... 2 3 Student castroKey = null; 4 int castroIndex; 5 6 //create a "key" that will match according to the 7 // Student.equals() method 8 castroKey = new Student("Starlin", "Castro", 131313, 3.95); 9 castroIndex = roster.indexOf(castroKey); 10 System.out.println("at index " + castroIndex + ": " + 11 roster.get(castroIndex)); 12 13 //create a key with only the necessary fields to match 14 / the comparator 15 castroKey = new Student("Starlin", "Castro", 0, 0.0); 16 //sort the list according to the comparator 17 Collections.sort(roster, byName); 18 castroIndex = Collections.binarySearch(roster, castroKey, byName); 19 System.out.println("at index " + castroIndex + ": " + 20 roster.get(castroIndex)); 21 22 //create a key with only the necessary fields to match 23 // the comparator 24 castroKey = new Student(null, null, 131313, 0.0); 25 //sort the list according to the comparator 26 Collections.sort(roster, byId); 27 castroIndex = Collections.binarySearch(roster, castroKey, byId); 28 System.out.println("at index " + castroIndex + ": " + 29 roster.get(castroIndex)); Code Sample 36.1.: Java Search Examples to use to maintain the ordering (alternatively, you may omit the Comparator and the TreeSet will use the natural ordering of elements). 1 Comparator<Integer> cmpIntDesc = new Comparator<Integer>() { ... }; 2 SortedSet<Integer> sortedInts = new TreeSet<Integer>(cmpIntDesc); 3 sortedInts.add(10); 4 sortedInts.add(30); 5 sortedInts.add(20); 489
ComputerScienceOne_Page_523_Chunk2059
36. Searching & Sorting 1 List<Student> roster = ... 2 Student rosterArr[] = ... 3 Comparator byName = ... 4 Comparator byGPA = ... 5 6 //sort by name: 7 Collections.sort(roster, byName); 8 Arrays.sort(rosterArr, byName); 9 10 //sort by GPA: 11 Collections.sort(roster, byGPA); 12 Arrays.sort(rosterArr, byGPA); Code Sample 36.2.: Using Java Collection’s Sort Method 6 //sortedInts has elements 30, 20, 10 in descending order 7 8 SortedSet<Student> sortedStudents = new TreeSet<Student>(byName); 9 //add students, they will be sorted by name 10 for(Student s : sortedStudents) { 11 System.out.println(s); 12 } When using a SortedSet it is important that the Comparator properly orders all elements. A SortedSet is still a Set : it does not allow duplicate elements. If the Comparator you use returns zero for any element that you attempt to insert, it will not be inserted. To demonstrate how this might fail, consider our byName Comparator for Student objects. Suppose two students have the same first name and last name, “John Doe” and “John Doe,” but have different IDs (as they are different people). The Comparator would return 0 for these two objects because they have the same first/last name, even though they are distinct people. Only one of these objects could exist in the SortedSet . To solve this problem, it is important to define Comparator s that “break ties” appropriately. In this case, we would want to modify the Comparator to return a comparison of IDs if the first and last name are the same. 36.3.2. Handling null values When sorting collections or arrays of objects, we may need to consider the possibility of uninitialized null objects. Some collections allow null element(s) while others do 490
ComputerScienceOne_Page_524_Chunk2060
36.3. Other Considerations not. How we handle these is a design decision. We could ignore it, in which case such elements would likely result in a NullPointerException and expect the user to prevent or handle such instances. This may be the preferable choice in most instances, in fact. Alternatively, we could handle null objects in the design of our Comparator . Code Sample 36.3 presents a Comparator for our Student class that orders null instances first. 1 Comparator<Student> byNameWithNulls = new Comparator<Student>() { 2 @Override 3 public int compare(Student a, Student b) { 4 if(a == null && b == null) { 5 return 0; 6 } else if(a == null && b != null) { 7 return -1; 8 } else if(a != null && b == null) { 9 return 1; 10 } else { 11 if(a.getLastName().equals(b.getLastName())) { 12 return a.getFirstName().compareTo(b.getFirstName()); 13 } else { 14 return a.getLastName().compareTo(b.getLastName()); 15 } 16 } 17 } 18 }; Code Sample 36.3.: Handling Null Values in Java Comparators This solution only handles null Student values not null values within the Student object. If the getters used in the Comparator return null values, then we could still have NullPointerException s. 36.3.3. Importance of equals() and hashCode() Methods Recall that in Chapter 34 we briefly discussed the importance of overloading the equals() and hashCode() methods of our objects. We reiterate this in the con- text of searching. Recall that the Set and List collections provide linear search methods that do not require the use of a Comparator . This is because the collections use the object’s equals() to determine when a particular instance has been found. In the case of hash-based data structures such as HashSet , the hashCode() method is 491
ComputerScienceOne_Page_525_Chunk2061
36. Searching & Sorting also important. To illustrate the importance of these methods, consider the following code. 1 Student a = new Student("Joe", "Smith", 1234, 3.5); 2 Student b = new Student("Joe", "Smith", 1234, 3.5); 3 4 Set<Student> s = new HashSet<Student>(); 5 s.add(a); 6 s.add(b); If we do not override the equals() and hashCode() methods, at the end of this code snippet, the set will contain both of the Student instances even though they are conceptually the same object (all of their member variables will have the same values). However, if we do override the equals() and hashCode() methods as described in Section 34.5, then the code snippet above would result in the Set only having one object (the first one added). This is because during the attempt to add the second instance, the equals() method would have returned true when compared to the first instance and the duplicate element would not have been added to the Set (as Set s do not allow duplicates). Also recall that we saw some of the advantages of immutable objects. Again, we point out another advantage. Suppose that we properly override the equals() and the hashCode() methods in our Student object. Further, suppose that we make our Student class mutable: allowing a user to change the ID via a setter. Consider the following code snippet. 1 Student a = new Student("Joe", "Smith", 1234, 3.5); 2 Student b = new Student("Joe", "Smith", 5679, 3.5); 3 4 Set<Student> s = new HashSet<Student>(); 5 s.add(a); 6 s.add(b); 7 //s now contains both students 8 b.setId(1234); When we instantiate the two Student instances, they are distinct as their IDs are different. So when we add them to the set, their equals() method returns false and they are both added to the Set . However, when we change the ID using the setter on the last line, both objects are now identical, violating the no-duplicates property of the Set . This is not a failing of the Set class, just one of the many consequences of designing mutable objects. 492
ComputerScienceOne_Page_526_Chunk2062
36.3. Other Considerations 36.3.4. Java 8: Lambda Expressions Java 8 introduced a lot of functional-style syntax, including lambda expressions. Lambda expressions are essentially anonymous functions that can be passed around to other methods or objects. One use for lambda expressions is if we want to sort a List with respect to one data field, we need not build a full Comparator . Instead we can use the following syntax. 1 List<Student> roster = ... 2 3 roster.sort((a, b) -> a.getLastName().compareTo(b.getLastName())); The new syntax is the use of the arrow operator as a lambda expres- sion. In this case, it maps a pair, (a, b) to the value of the expression a.getLastName().compareTo(b.getLastName()) (which takes advantage of the fact that strings implement the Comparable interface). With respect to Comparator s, we can use the following syntax to build a more complex ordering. 1 Comparator<Student> c = 2 (a, b) -> a.getLastName().compareTo(b.getLastName()); 3 c = c.thenComparing( (a, b) -> 4 a.getFirstName().compareTo(b.getFirstName())); 5 c = c.thenComparing( (a, b) -> a.getGpa().compareTo(b.getGpa())); 6 7 //pass the comparator to the sort method: 8 roster.sort(c); We can make this even more terse using method references, another new feature in Java 8. 1 //using getters as key extractors 2 myList.sort( 3 Comparator.comparing(Student::getLastName) 4 .thenComparing(Student::getFirstName) 5 .thenComparing(Student::getGpa)); There are several other convenient methods provided by the updated Comparator interface. For example, the reversed() member method returns a new Comparator that defines the reversed order. The static methods, nullsFirst() and nullsLast() 493
ComputerScienceOne_Page_527_Chunk2063
36. Searching & Sorting can be used to modify a Comparator to order null values. 494
ComputerScienceOne_Page_528_Chunk2064
Part III. The PHP Programming Language 495
ComputerScienceOne_Page_529_Chunk2065
37. Basics In the mid-1990s the World Wide Web was in its infancy but becoming more and more popular. For the most part, web pages contained static content: articles and text that was “just-there.” Web pages were far from the fully interactive and dynamic applications that they’ve become. Rasmus Lerdorf had a home page containing his resume and he wanted to track how many visitors were coming to his page. With purely static pages, this was not possible. So, in 1994 he developed PHP/FI which stood for Personal Home Page tools and Forms Interpreter. This was a series of binary tools written in C that operated through a web server’s Common Gateway Interface. When a user visited a webpage, instead of just retrieving static content, a script was invoked: it could do a number of operations and send back HTML formatted as a response. This made web pages much more dynamic. By serving it through a script, a counter could be maintained that tracked how many people had visited the site. Lerdorf eventually released his source code in 1995 and it became widely used. Today, PHP is used in a substantial number of pages on the web and is used in many Content Management System (CMS) applications such as Drupal and WordPress. Because of its history, much of the syntax and aspects of PHP (now referred to as “PHP: Hypertext Preprocessor”) are influenced or inspired by C. In fact, many of the standard functions available in the language are directly from the C language. PHP is a scripting language and is not compiled. Instead, PHP code is interpreted by a PHP interpreter. Though there are several interpreters available, the de facto PHP interpreter is the Zend Engine, a free and open source project that is widely available on many platforms, operating systems, and web servers. Because it was originally intended to serve web pages, PHP code can be interleaved with static HTML tags. This allows PHP code to be embedded in web pages and dynamically interpreted/rendered when a user requests a webpage through a web browser. Though rendering web pages is its primary purpose, PHP can be used as a general scripting language from the command line. PHP is a dirty, ugly language held together by duct tape, cracked asbestos-filled spackle and sadness (http://phpsadness.com/). It is the cockroach of languages: it is invasive and it is a survivor. It is a hydra; rewrite one PHP app and two more pop up. It is much maligned and a source of ridicule. It is the source of hundreds of bad practices, thousands of bad programmers, millions of bugs and an infinite abyss of security holes and vulnerabilities. It is a language that was born in the wild and raised in the darkness by two schizophrenic monkeys. But its got character; and in this world, that’s enough. 497
ComputerScienceOne_Page_531_Chunk2066
37. Basics 1 <?php 2 3 printf("Hello World\n"); 4 5 ?> Code Sample 37.1.: Hello World Program in PHP 1 <html> 2 <head> 3 <title>Hello World PHP Page</title> 4 </head> 5 <body> 6 <h1>A Simple PHP Script</h1> 7 8 <?php printf("<p>Hello World</p>"); ?> 9 10 </body> 11 </html> Code Sample 37.2.: Hello World Program in PHP with HTML 37.1. Getting Started: Hello World The hallmark of an introduction to a new programming language is the Hello World! program. It consists of a simple program whose only purpose is to print the message “Hello World!” to the user. The simplicity of the program allows the focus to be on the basic syntax of the language. It is also typically used to ensure that your development environment, interpretrer, runtime environment, etc. are functioning properly with a minimal example. A basic Hello World! program in PHP can be found in Code Sample 37.1. A version in which the PHP code is interleaved in HTML is presented in Code Sample 37.2. We will not focus on any particular development environment, code editor, or any particular operating system, interpreter, or ancillary standards in our presentation. However, as a first step, you should be able to write and run the above program on the environment you intend to use for the rest of this book. This may require that you download and install a basic PHP interpreter/development environment (such as a standard LAMP, WAMP or MAMP technology stack) or a full IDE (such as Eclipse, PhpStorm, etc.). 498
ComputerScienceOne_Page_532_Chunk2067
37.2. Basic Elements 37.2. Basic Elements Using the Hello World! program as a starting point, we will examine the basic elements of the PHP language. 37.2.1. Basic Syntax Rules PHP has adopted many aspects of the C programming language (the interpreter itself is written in C). However, there are some major aspects in which it differs from C. The major aspects and syntactic elements of PHP include the following. • PHP is an interpreted language: it is not compiled. Instead it is interpreted through an interpreter that parses commands in a script file line-by-line. Any syntax errors, therefore, become runtime errors. • PHP is dynamically typed: you do not declare variables or specify a variable’s type. Instead, when you assign a variable a value, the variable’s type dynamically changes to accommodate the assigned value. Variable names always begin with a dollar sign, $ . • Strings and characters are essentially the same thing (characters are strings of length 1). Strings and characters can be delimited by either single quotes or double quotes. "this is a string" , 'this is also a string' ; 'A' and "a" are both single character strings. • Executable statements are terminated by a semicolon, ; • Code blocks are defined by using opening and closing curly brackets, { ... } . Moreover, code blocks can be nested: code blocks can be defined within other code blocks. • A complete list of reserved and keywords can be found in the PHP Manual: http:// php.net/manual/en/reserved.php and http://php.net/manual/en/reserved. keywords.php PHP also supports aspects of OOP including classes and inheritance. There is also no memory management in PHP: it has automated garbage collection. Though not a syntactic requirement, the proper use of whitespace is important for good, readable code. Code inside code blocks is indented at the same indentation. Nested code blocks are indented further. Think of a typical table of contents or the outline of a formal paper or essay. Sections and subsections or points and subpoints all follow proper indentation with elements at the same level at the same indentation. This convention is used to organize code and make it more readable. 499
ComputerScienceOne_Page_533_Chunk2068
37. Basics 37.2.2. PHP Tags PHP code can be interleaved with static HTML or text. Because of this, we need a way to indicate what should be interpreted as PHP and what should be treated as static text. We can do this using PHP tags: the opening tag is <?php and the closing tag is ?> . Anything placed between these tags will be interpreted as PHP code which must adhere to the syntax rules of the language. A file can contain multiple opening/closing PHP tags to allow you to interleave multiple sections of HTML or text. When an interpreter runs a PHP script, it will start processing the script file. Whenever it sees the opening PHP tag, it begins to execute the commands and stops executing commands when it sees the closing tag. The text outside the PHP tags is treated as raw data. The interpreter includes it as part of its output without modifying or processing it. 37.2.3. Libraries PHP has many built-in functions that you can use. These standard libraries are loaded and available to use without any special command to import or include them. Full docu- mentation on each of these functions is maintained in the PHP manual, available online at http://php.net/. The manual’s web pages also contain many curated comments from PHP developers which contain further explanations, tips & tricks, suggestions, and sample code to provide further assistance. There are many useful functions that we’ll mention as we progress through each topic. One especially useful collection of functions is the math library. This library is directly adapted from C’s standard math library so all the function names are the same. It provides many common mathematical functions such as the square root and natural logarithm. Table 37.1 highlights several of these functions; full documentation can be found in the PHP manual (http://php.net/manual/en/ref.math.php). To use these, you simply “call” them by providing input and assigning the output to a variable. 1 $x = 1.5; 2 $y = sqrt($x); //y now has the value √x = √ 1.5 3 $z = sin($x); //z now has the value sin (x) = sin (1.5) In both of the function calls above, the value of the variable $x is “passed” to the math function which computes and “returns” the result which then gets assigned to another variable. 37.2.4. Comments Comments can be written in PHP code either as a single line using two forward slashes, //comment or as a multiline comment using a combination of forward slash and asterisk: /* comment */ . With a single line comment, everything on the line after the forward 500
ComputerScienceOne_Page_534_Chunk2069
37.2. Basic Elements Function Description abs($x) Absolute value, |x| ceil($x) Ceiling function, ⌈46.3⌉= 47.0 floor($x) Floor function, ⌊46.3⌋= 46.0 cos($x) Cosine functiona sin($x) Sine functiona tan($x) Tangent functiona exp($x) Exponential function, ex, e = 2.71828 . . . log($x) Natural logarithm, ln (x)b log10($x) Logarithm base 10, log10 (x)b pow($x,$y) The power function, computes xyc sqrt($x) Square root functionb Table 37.1.: Several functions defined in the PHP math library. aAll trigonometric functions assume input is in radians, not degrees. bInput is assumed to be positive, x > 0. cAlternatively, PHP supports exponentiation by using x ** y . 501
ComputerScienceOne_Page_535_Chunk2070
37. Basics slashes is ignored. With a multiline comment, everything in between the forward slash/asterisk is ignored. Comments are ultimately ignored by the interpreter. Consider the following example. 1 //this is a single line comment 2 $x = 10; //this is also a single line comment, but after some code 3 4 /* 5 This is a comment that can 6 span multiple lines to format the comment 7 message more clearly 8 */ 9 $y = 3.14; Most code editors and IDEs will present comments in a special color or font to distinguish them from the rest of the code (just as our example above does). Failure to close a multiline comment will likely result in a fatal interpreter error but with color-coded comments its easy to see the mistake visually. 37.2.5. Entry Point & Command Line Arguments Every PHP script begins executing at the top of the script file and proceed in a linear, sequential manner top-to-bottom. In addition, you can provide a PHP script with inputs when you run it from the command line. These command line arguments are stored in two variables, $argc and $argv . The first variable, $argc is an integer that indicates the number of arguments provided including the name of the script file being executed. The second, $argv is an array (see Section 42) of strings consisting of the command line arguments. To access them, you can index them starting at zero, the first being $argv[0] , the second $argv[1] , the last one would be $argv[$argc-1] . The first one is always the name of the script file being run. The remaining are the command line arguments provided by the user when the script is executed. We’ll see several examples later. 37.3. Variables PHP is a dynamically typed language. As a consequence, you do not declare variables before you start using them. If you need to store a value into a variable, you simply name the variable and use an assignment operator to assign the value. Since you do not declare variables, you also do not specify a variable’s type. If you assign a string value to a variable, its type becomes a string. If you assign an integer to a variable, its type becomes an integer. If you reassign the value of a variable to a value with a different type, the variable’s type also changes. 502
ComputerScienceOne_Page_536_Chunk2071
37.3. Variables Internally PHP supports several different types: Booleans, integers, floating point numbers, strings, arrays, and objects. The way that integers are represented may be platform dependent, but are usually 32-bit signed two’s complement integers, able to represent integers between −2, 147, 483, 648 and 2,147,483,647. Floating point numbers are also platform dependent, but are usually 64-bit double precision numbers defined by the IEEE 754 standard, providing about 16 digits of precision. Strings and single characters are the same thing in PHP. Strings are represented as sequences of characters from the extended ASCII text table (see Table 2.4) which includes all characters in the range 0–255. PHP does not have native Unicode support for international characters. 37.3.1. Using Variables To use a variable in PHP, you simply need to assign a value to a named variable identifier and the variable is in scope. Variable names always begin with a single dollar sign, $ . The assignment operator is a single equal sign, = and is a right-to-left assignment. The variable that we wish to assign the value to appears on the left-hand-side while the value (literal, variable or expression) is on the right-hand-size. For example: 1 $numUnits = 42; 2 $costPerUnit = 32.79; 3 $firstInitial = "C"; Each assignment also implicitly changes the variable’s type. Each of the variables above becomes an integer, floating point number, and string respectively. Assignment statements are terminated by a semicolon like most executable statements in PHP. The identifier rules are fairly standard: a variable’s name can consist of lowercase and uppercase alphabetic characters, numbers, and underscores. You can also use the extended ASCII character set in variable names but it is not recommended (umlauts and other diacritics can easily be confused). Variable names are case sensitive. As previously mentioned, variable names must always begin with a dollar sign, $ . Stylistically, we adopt the modern lower camel casing naming convention for variables in our code. If you do not assign a value to a variable, that variable remains undefined or “unset.” Undefined variables are treated as null in PHP. The concept of “null” refers to uninitialized, undefined, empty, missing, or meaningless values. In PHP the keyword null is used which is case insensitive ( null , Null and NULL are all the same), but for consistency, we’ll use null . When null values are used in arithmetic expressions, null is treated as zero. So, (10 + null) is equal to 10. When null is used in the context of strings, it is treated as an empty string and ignored. When used in a Boolean expression or conditional, null is treated as false . PHP also allows you to define constants: values that cannot be changed once set. To define a constant, you invoke a function named define and providing a name and value. 503
ComputerScienceOne_Page_537_Chunk2072
37. Basics 1 define("PI", 3.14159); 2 define("INSTITUTION", "University of Nebraska-Lincoln"); 3 define("COST_PER_UNIT", 2.50); Constant names are case sensitive. By convention, we use uppercase underscore casing. An attempt to redefine a constant value will raise a script warning, but will ultimately have no effect. When referring to constants later in the script, you use the constant’s name. You do not treat it as a string, nor do you use a dollar sign. For example: $area = $r * $r * PI; 37.4. Operators PHP supports the standard arithmetic operators for addition, subtraction, multiplication, and division using + , - , * , and / respectively. Each of these operators is a binary op- erator that acts on two operands which can either be literals, variables or expressions and follow the usual rules of arithmetic when it comes to order of precedence (multiplication and division before addition and subtraction). 1 $a = 10, $b = 20, $c = 30; 2 $d = $a + 5; 3 $d = $a + $b; 4 $d = $a - $b; 5 $d = $a + $b * $c; 6 $d = $a * $b; //d becomes a floating point number with a value .5 7 8 $x = 1.5, $y = 3.4, $z = 10.5; 9 $w = $x + 5.0; 10 $w = $x + $y; 11 $w = $x - $y; 12 $w = $x + $y * $z; 13 $w = $x * $y; 14 $w = $x / $y; 15 16 //mixing integers and floating point numbers is no problem 17 $w = $a + $x; PHP also supports the integer remainder operator using the % symbol. This operator gives the remainder of the result of dividing two integers. Examples: 504
ComputerScienceOne_Page_538_Chunk2073
37.4. Operators 1 $x = 10 % 5; //x is 0 2 $x = 10 % 3; //x is 1 3 $x = 29 % 5; //x is 4 37.4.1. Type Juggling The expectations of an arithmetic expression involving two variables that are either integers or floating point numbers are straightforward. We expect the sum/product/etc. as a result. However, since PHP is dynamically typed, a variable involved in an arithmetic expression could be anything, including a Boolean, object, array, or string. When a Boolean is involved in an arithmetic expression, true is treated as 1 and false is treated as zero. If an array is involved in an expression, it is usually a fatal error.1 Non-null objects are treated as 1 and null is treated as 0. However, when string values are involved in an arithmetic expression, PHP does something called type juggling. When juggled, an attempt is made to convert a string variable into a numeric value by parsing it. The parsing goes over each numeric character, converting the value to a numeric type (either an integer or floating point number). The first type a non-numeric character is encountered, the parsing stops and the value parsed so far is the value used in the expression. Consider the examples in Code Sample 37.3. In the first segment, $a is type juggled to the value 10, then added to 5 , resulting in 15. In the second example, $a represents a floating point number, and is converted to 3.14, the result of adding to 5 is thus 8.14. In the third example, the string does not contain any numerical values. In this case, the parsing stops at the first character and what has been parsed so far is zero! Finally, in the last example, the first two characters in $a are numeric, so the parsing ends at the third character, and what has been parsed so far is 10. Relying on type juggling to convert values can be ugly and error prone. You can write much more intentional code by using the several conversion functions provided by PHP. For example: 1 $a = intval("10"); 2 $b = floatval("3.14"); 3 $c = intval("ten"); //c has the value zero In all three of the examples above, the strings are converted just as they are when type juggled. However, the variables are guaranteed to have the type indicated (integer or floating point number). 1PHP does allow you to “add” two arrays together which results in their union. 505
ComputerScienceOne_Page_539_Chunk2074
37. Basics 1 $a = "10"; 2 $b = 5 + $a; //b = 15 3 4 $a = "3.14"; 5 $b = 5 + $a; //b = 8.14 6 7 $a = "ten"; 8 $b = 5 + $a; //b = 5 9 10 //partial conversions also occur: 11 $a = "10ten"; 12 $b = 5 + $a; //b = 15 Code Sample 37.3.: Type Juggling in PHP There are several utility functions that can be used to help determine the type of variable. The function is_numeric($x) returns true if $x is a numeric (integer or floating point number) or represents a pure numeric string. The functions is_int($x) and is_float($x) each return true or false depending on whether or not $x is of that type. 1 $a = 10; 2 $b = "10"; 3 $c = 3.14; 4 $d = "3.14"; 5 $e = "hello"; 6 $f = "10foo"; 7 8 is_numeric($a); //true 9 is_numeric($b); //true 10 is_numeric($c); //true 11 is_numeric($d); //true 12 is_numeric($e); //false 13 is_numeric($f); //false 14 15 is_int($a); //true 16 is_int($b); //false 17 is_int($c); //false 18 is_int($d); //false 19 is_int($e); //false 506
ComputerScienceOne_Page_540_Chunk2075
37.4. Operators Value of $var isset($var) empty($var) is_null($var) 42 bool(true) bool(false) bool(false) "" (an empty string) bool(true) bool(true) bool(false) " " (space) bool(true) bool(false) bool(false) false bool(true) bool(true) bool(false) true bool(true) bool(false) bool(false) array() (an empty array) bool(true) bool(true) bool(false) null bool(false) bool(true) bool(true) "0" (0 as a string) bool(true) bool(true) bool(false) 0 (0 as an integer) bool(true) bool(true) bool(false) 0.0 (0 as a float) bool(true) bool(true) bool(false) var $var; (declared with no value) bool(false) bool(true) bool(true) NULL byte ( "\0" ) bool(true) bool(false) bool(false) Table 37.2.: Results for various variable values 20 is_int($f); //false 21 22 is_float($a); //false 23 is_float($b); //false 24 is_float($c); //true 25 is_float($d); //false 26 is_float($e); //false 27 is_float($f); //false A more general way to determine the type of a variable is to use the function gettype($x) which returns a string representation of the type of the variable $x . The string returned by this function is one of the following depending on the type of $x : "boolean" , "integer" , "double" , "string" , "array" , "object" , "resource" , "NULL" , or "unknown type" . Other checker functions allow you to determine if a variable has been set, if its null, “empty” etc. For example, is_null($x) returns true if $x is not set or is set, but has been set to null . The function isset($x) returns true only if $x is set and it is not null . The function empty($x) returns true if $x represents an empty entity: an empty string, false , an empty array, null , "0" , 0, or an unset variable. Several examples are presented in Table 37.2. 507
ComputerScienceOne_Page_541_Chunk2076
37. Basics 37.4.2. String Concatenation Strings in PHP can be concatenated (combined) in several different ways. One way you can combine strings is by using the concatenation operator. In PHP the string concatenation operator is a single period. 1 $s = "Hello"; 2 $t = "World!"; 3 $msg = $s . " " . $t; //msg contains "Hello World!" Another way you can combine strings is by placing variables directly inside a string. The variables inside the string are replaced with the variable’s values. Example: 1 $x = 13; 2 $name = "Starlin"; 3 $msg = "Hello, $name, your number is $x"; 4 //msg contains the string "Hello, Starlin, your number is 13" 37.5. Basic I/O Recall the main purpose of PHP is as a scripting language to serve dynamic webpages. However, it does support input and output from the standard input/output. There are several ways to print output to the standard output. The keywords print and echo (which are aliases of each other) allow you to print any variable or string. PHP also has a printf() function to allow formatted output. Some examples: 1 $a = 10; 2 $b = 3.14; 3 4 print $a; 5 print "The value of a is $a\n"; 6 7 echo $a; 8 echo "The value of a is $a\n"; 9 10 printf("The value of a is %d, and b is %f\n", $a, $b); There are also several ways to perform standard input, but the easiest is to use fgets 508
ComputerScienceOne_Page_542_Chunk2077
37.6. Examples (short for file get string) using the keyword STDIN (Standard Input). This function will return, as a string, everything the user enters up to and including the enter key (interpreted as the endline character, \n ). To remove the endline character, you can use another function, trim which removes leading and trailing whitespace from a string. A full example: 1 //prompt the user to enter input 2 printf("Please enter a number: "); 3 $a = fgets(STDIN); 4 $a = trim($a); Alternatively, lines 3–4 could be combined into one: $a = trim(fgets(STDIN)); The call to fgets waits (referred to as “blocking”) for the user to enter input. The user is free to start typing. When the user is done, they hit the enter key at which point the program resumes and reads the input from the standard input buffer, and returns it as a string value which we assign to the variable $a . The standard input is unstructured. The user is free to type whatever they want. If we prompt the user for a number but they just start mashing the keyboard giving non-numerical input, we may get incorrect results. We can use the conversion functions mentioned above to attempt to properly convert the values. However, this only guarantees that the resulting variable is of the type we want (integer or floating point value for example). The standard input is not a good mechanism for reading input, but it provides a good starting point to develop a few simple programs. 37.6. Examples 37.6.1. Converting Units Let’s write a program that prompts the user to enter a temperature in degrees Fahrenheit and convert it to degrees Celsius using the formula C = (F −32) · 5 9 We begin with the basic script shell with the opening and closing PHP tags and some comments documenting the purpose of our script. 1 <?php 2 3 /** 4 * This program converts Fahrenheit temperatures to 5 * Celsius 509
ComputerScienceOne_Page_543_Chunk2078
37. Basics 6 */ 7 8 //TODO: implement this 9 10 ?> It is common for programmers to use a comment along with a TODO note to themselves as a reminder of things that they still need to do with the program. Let’s first outline the basic steps that our program will go through: 1. We’ll first prompt the user for input, asking them for a temperature in Fahrenheit 2. Next we’ll read the user’s input and use a conversion function to ensure the input is a floating point number 3. Once we have the input, we can calculate the degrees Celsius by using the formula above 4. Lastly, we will want to print the result to the user to inform them of the value Sometimes it is helpful to write an outline of such a program directly in the code using comments to provide a step-by-step process. For example: 1 <?php 2 3 /** 4 * This program converts Fahrenheit temperatures to 5 * Celsius 6 */ 7 8 //TODO: implement this 9 10 //1. Prompt the user for input in Fahrenheit 11 //2. Read the Fahrenheit value from the standard input 12 //3. Compute the degrees Celsius 13 //4. Print the result to the user 14 15 ?> As we read each step it becomes apparent that we’ll need a couple of variables: one to hold the Fahrenheit (input) value and one for the Celsius (output) value. We’ll want to ensure that these are floating point numbers which we can do by making some explicit conversion. We use a printf() statement in the first step to prompt the user for input. 510
ComputerScienceOne_Page_544_Chunk2079
37.6. Examples printf("Please enter degrees in Fahrenheit: "); In the second step, we’ll use the standard input to read the $fahrenheit variable value from the user. Recall that we can use fgets to read from the standard input, but may have to trim the trailing whitespace. $fahrenheit = trim(fgets(STDIN)); If we want to ensure that the variable $fahrenheit is a floating point value, we can use floatval() : $fahrenheit = floatval($fahrenheit); We can now compute $celsius using the formula provided: $celsius = ($fahrenheit - 32) * (5 / 9); Finally, we use printf() again to output the result to the user: printf("%f Fahrenheit is %f Celsius\n", $fahrenheit, $celsius); The full program can be found in Code Sample 37.4. 1 <?php 2 3 /** 4 * This program converts Fahrenheit temperatures to 5 * Celsius 6 */ 7 8 //1. Prompt the user for input in Fahrenheit 9 printf("Please enter degrees in Fahrenheit: "); 10 11 //2. Read the Fahrenheit value from the standard input 12 $fahrenheit = trim(fgets(STDIN)); 13 $fahrenheit = floatval($fahrenheit); 14 15 //3. Compute the degrees Celsius 16 $celsius = ($fahrenheit - 32) * (5/9); 17 18 //4. Print the result to the user 19 printf("%f Fahrenheit is %f Celsius\n", $fahrenheit, $celsius); 20 21 ?> Code Sample 37.4.: Fahrenheit-to-Celsius Conversion Program in PHP 511
ComputerScienceOne_Page_545_Chunk2080
37. Basics 37.6.2. Computing Quadratic Roots Some programs require the user to enter multiple inputs. The prompt-input process can be repeated. In this example, consider asking the user for the coefficients, a, b, c to a quadratic polynomial, ax2 + bx + c and computing its roots using the quadratic formula, x = −b ± √ b2 −4ac 2a As before, we can create a basic program with PHP tags and start filling in the details. In particular, we’ll need to prompt for the input a, then read it in; then prompt for b, read it in and repeat for c. Thus, we have 1 printf("Please enter a: "); 2 $a = floatval(trim(fgets(STDIN))); 3 printf("Please enter b: "); 4 $b = floatval(trim(fgets(STDIN))); 5 printf("Please enter c: "); 6 $c = floatval(trim(fgets(STDIN))); We need to take care that we correctly adapt the formula so it accurately reflects the order of operations. We also need to use the math library’s square root function. 1 $root1 = (-$b + sqrt($b*$b - 4*$a*$c) ) / (2*$a); 2 $root2 = (-$b - sqrt($b*$b - 4*$a*$c) ) / (2*$a); Finally, we print the output using printf() . The full program can be found in Code Sample 37.5. This program was interactive. As an alternative, we could have read all three of the inputs as command line arguments, taking care to convert them to floating point numbers. Lines 8–13 in the program could have been changed to 1 $a = floatval($argv[1]); 2 $b = floatval($argv[2]); 3 $c = floatval($argv[3]); Finally, think about the possible input a user could provide that may cause problems for this program. For example: 512
ComputerScienceOne_Page_546_Chunk2081
37.6. Examples 1 <?php 2 3 /** 4 * This program computes the roots to a quadratic equation 5 * using the quadratic formula. 6 */ 7 8 printf("Please enter a: "); 9 $a = floatval(trim(fgets(STDIN))); 10 printf("Please enter b: "); 11 $b = floatval(trim(fgets(STDIN))); 12 printf("Please enter c: "); 13 $c = floatval(trim(fgets(STDIN))); 14 15 $root1 = (-$b + sqrt($b*$b - 4*$a*$c) ) / (2*$a); 16 $root2 = (-$b - sqrt($b*$b - 4*$a*$c) ) / (2*$a); 17 18 printf("The roots of %fx^2 + %fx + %f are: \n", $a, $b, $c); 19 printf(" root1 = %f\n", $root1); 20 printf(" root2 = %f\n", $root2); 21 22 ?> Code Sample 37.5.: Quadratic Roots Program in PHP • What if the user entered zero for a? • What if the user entered some combination such that b2 < 4ac? • What if the user entered non-numeric values? • For the command line argument version, what if the user provided less than three arguments? Or more? How might we prevent the consequences of such bad input? How might we handle the event that a user enters bad input and how do we communicate these errors to the user? To begin to resolve these issues, we’ll need conditionals. 513
ComputerScienceOne_Page_547_Chunk2082
38. Conditionals PHP supports the basic if, if-else, and if-else-if conditional structures as well as switch statements. Logical statements are built using the standard logical operators for numeric comparisons as well as logical operators such as negations, And, and Or. 38.1. Logical Operators PHP has a built-in Boolean type and supports the keywords true and false . However, any variable can be treated as a Boolean if used in a logical expression. Depending on the variable, it could evaluate to true or false! For example, an empty string, "" , null , or a numeric value of zero, 0 are all considered false. A non-empty string, a non-zero numeric value, or a non-empty array all evaluate to true. It is best to avoid these issues by writing clean code that uses clear, explicit statements. Because PHP is dynamically typed, comparison operators work differently depending on how they are used. First, let’s consider the four basic inequality operators, < , <= , > , and >= . When used to compare numeric types to numeric types, these operators work as expected and the value of the numbers are compared. 1 $a = 10; 2 $b = 20; 3 $c = 20; 4 5 $r = ($a < $b); //true 6 $r = ($a <= $b); //false 7 $r = ($b <= $c); //true 8 $r = ($a > $b); //false 9 $r = ($a >= $b); //false 10 $r = ($b >= $c); //true When these operators are used to compare strings to strings, the strings are compared lexicographically according to the standard ASCII text table. Some examples follow, but it is better to use a function (in particular strcmp see Chapter 43) to do string comparisons. 515
ComputerScienceOne_Page_549_Chunk2083
38. Conditionals 1 $s = "aardvark"; 2 $t = "zebra"; 3 4 $r = ($s < $t); //true 5 $r = ($s <= $t); //true 6 $r = ($s >= $t); //false 7 $r = ($s > $t); //false However, when these operators are used to compare strings to numeric types, the strings are converted to numbers using the same type juggling that happens when strings are mixed with arithmetic operators. In the following example, $b gets converted to a numeric type when compared to $a which give the results indicated in the comments. 1 $a = 10; 2 $b = "10"; 3 4 $r = ($a <= $b); //true 5 $r = ($a < $b); //false 6 $r = ($a >= $b); //true 7 $r = ($a > $b); //false With the equality operators, == and != , something similar happens. When the types of the two operands match, the expected comparison is made: when numbers are compared to numbers their values are compared; when strings are compared to strings, their content is compared (case sensitively). However, when the types are different they are type juggled and strings are converted to numbers for the purpose of comparison. Thus, a comparison like (10 == "10") ends up being true! The operators are == and != are referred to as loose comparison operators because of this. What if we want to ensure that we’re comparing apples to apples? To rectify this, PHP offers another set of comparison operators, strict comparison operators, === and !== (each has an extra equals sign, = ). These operators will make a comparison without type juggling either operand first. Now a similar comparison, (10 === "10") ends up evaluating to false. The operator === will only evaluate to true if the both the operands’ type and value are the same. 1 $a = 10; 2 $b = "10"; 3 4 $r = ($a == $b); //true 5 $r = ($a != $b); //false 516
ComputerScienceOne_Page_550_Chunk2084
38.2. If, If-Else, If-Else-If Statements Operator(s) Associativity Notes Highest ++ , -- left-to-right increment operators - , ! right-to-left unary negation operator, logical not * , / , % left-to-right + , - left-to-right addition, subtraction < , <= , > , >= left-to-right comparison == , != , === , !== left-to-right equality, inequality && left-to-right logical And || left-to-right logical Or Lowest = , += , -= , *= , /= right-to-left assignment and compound assign- ment operators Table 38.1.: Operator Order of Precedence in PHP. Operators on the same level have equivalent order and are performed in the associative order specified. 6 $r = ($a === $b); //false 7 $r = ($a !== $b); //true The three basic logical operators, not ! , and && , and or || are also supported in PHP. 38.1.1. Order of Precedence At this point it is worth summarizing the order of precedence of all the operators that we’ve seen so far including assignment, arithmetic, comparison, and logical. Since all of these operators could be used in one statement, for example, ($b*$b < 4*$a*$c || $a === 0 || $argc != 4) it is important to understand the order in which each one gets evaluated. Table 38.1 summarizes the order of precedence for the operators seen so far. This is not an exhaustive list of PHP operators. 38.2. If, If-Else, If-Else-If Statements Conditional statements in PHP utilize the keywords if , else , and else if . Condi- tions are placed inside parentheses immediately after the if and else if keywords. Examples of all three can be found in Code Sample 38.1. Observe that the statement, if($x < 10) does not have a semicolon at the end. This is because it is a conditional statement that determines the flow of control and not an executable statement. Therefore, no semicolon is used. Suppose we made a mistake and did include a semicolon: 517
ComputerScienceOne_Page_551_Chunk2085
38. Conditionals 1 //example of an if statement: 2 if($x < 10) { 3 printf("x is less than 10\n"); 4 } 5 6 //example of an if-else statement: 7 if($x < 10) { 8 printf("x is less than 10\n"); 9 } else { 10 printf("x is 10 or more \n"); 11 } 12 13 //example of an if-else-if statement: 14 if($x < 10) { 15 printf("x is less than 10\n"); 16 } else if($x === 10) { 17 printf("x is equal to ten\n"); 18 } else { 19 printf("x is greater than 10\n"); 20 } Code Sample 38.1.: Examples of Conditional Statements in PHP 518
ComputerScienceOne_Page_552_Chunk2086
38.3. Examples 1 $x = 15; 2 if($x < 10); { 3 printf("x is less than 10\n"); 4 } This PHP code will run without error or warning. However, it will end up printing x is less than 10 , even though x = 15! Recall that a conditional statement binds to the executable statement or code block immediately following it. In this case, we’ve provided an empty executable statement ended by the semicolon. The code is essentially equivalent to 1 $x = 15; 2 if($x < 10) { 3 } 4 printf("x is less than 10\n"); This is obviously not what we wanted. The semicolon was bound to the empty executable statement and the code block containing the print statement immediately followed, but was not bound to the conditional statement which is why the print statement executed regardless of the value of x. Another convention that we’ve used in our code is where we have placed the curly brackets. If a conditional statement is bound to only one statement, the curly brackets are not necessary. However, it is best practice to include them even if they are not necessary and we’ll follow this convention. Second, the opening curly bracket is on the same line as the conditional statement while the closing curly bracket is indented to the same level as the start of the conditional statement. Moreover, the code inside the code block is indented. If there were more statements in the block, they would have all been at the same indentation level. 38.3. Examples 38.3.1. Computing a Logarithm The logarithm of x is the exponent that some base must be raised to get x. The most common logarithm is the natural logarithm, ln (x) which is base e = 2.71828 . . .. But logarithms can be in any base b > 1.1 What if we wanted to compute log2 (x)? Or logπ (x)? Let’s write a program that will prompt the user for a number x and a base b and computes logb (x). Arbitrary bases can be computed using the change of base 1Bases can also be 0 < b < 1, but we’ll restrict our attention to increasing functions only. 519
ComputerScienceOne_Page_553_Chunk2087
38. Conditionals formula: logb(x) = loga (x) loga (b) If we can compute some base a, then we can compute any base b. Fortunately we have such a solution. Recall that the standard library provides a function to compute the natural logarithm, log() ). This is one of the fundamentals of problems solving: if a solution already exists, use it. In this case, a solution exists for a different, but similar problem (computing the natural logarithm), but we can adapt the solution using the change of base formula. In particular, if we have variables b (base) and x , we can compute logb (x) using log(x) / log(b) We have a problem similar to the examples in the previous section. The user could enter invalid values such as b = −10 or x = −2.54 (logarithms are undefined for non-positive values in any base). We want to ensure that b > 1 and x > 0. With conditionals, we can now do this. Once we have read in the input from the user we can make a check for good input using an if statement. 1 if($x <= 0 || $b <= 1) { 2 printf("Error: bad input!\n"); 3 exit(1); 4 } This code has something new: exit(1) . The exit() function immediately terminates the script regardless of the rest of the code that may remain. The argument passed to exit is an integer that represents an error code. The convention is that zero indicates “no error” while non-zero values indicate some error. This is a simple way of performing error handling: if the user provides bad input, we inform them and quit the program, forcing them to run it again and provide good input. By prematurely terminating the program we avoid any illegal operation that would give a bad result. Alternatively, we could have split the conditions into two statements and given a more descriptive error message. We use this design in the full program which can be found in Code Sample 38.2. The program also takes the input as command line arguments. Now that we have conditionals, we can check that the correct number of arguments was provided by the user and quit in the event that they don’t provide the correct number. 38.3.2. Life & Taxes Let’s adapt the conditional statements we developed in Section 3.6.4 into a full PHP script. The first thing we need to do is establish the variables we’ll need and read them in from the user. At the same time we can check for bad input (negative values) for both the inputs. 520
ComputerScienceOne_Page_554_Chunk2088
38.3. Examples 1 //prompt for income from the user 2 printf("Please enter your Adjusted Gross Income: "); 3 4 $income = floatval(trim(fgets(STDIN))); 5 6 //prompt for children 7 printf("How many children do you have? "); 8 $numChildren = intval(trim(fgets(STDIN))); 9 10 if($income < 0 || $numChildren < 0) { 11 printf("Invalid inputs"); 12 exit(1); 13 } Next, we can code a series of if-else-if statements for the income range. By placing the ranges in increasing order, we only need to check the upper bounds just as in the original example. 1 if($income <= 18150) { 2 $baseTax = $income * .10; 3 } else if($income <= 73800) { 4 $baseTax = 1815 + ($income -18150) * .15; 5 } else if($income <= 148850) { 6 ... 7 } else { 8 $baseTax = 127962.50 + ($income - 457600) * .396; 9 } Next we compute the child tax credit, taking care that it does not exceed $3,000. A conditional based on the number of children suffices as at this point in the program we already know it is zero or greater. 1 if($numChildren <= 3) { 2 $credit = $numChildren * 1000; 3 } else { 4 $credit = 3000; 5 } Finally, we need to ensure that the credit does not exceed the total tax liability (the credit is non-refundable, so if the credit is greater, the tax should only be zero, not 521
ComputerScienceOne_Page_555_Chunk2089
38. Conditionals negative). 1 if($baseTax - $credit >= 0) { 2 $totalTax = $baseTax - $credit; 3 } else { 4 $totalTax = 0; 5 } The full program is presented in Code Sample 38.3. 38.3.3. Quadratic Roots Revisited Let’s return to the quadratic roots program we previously designed that uses the quadratic equation to compute the roots of a quadratic polynomial by reading coefficients a, b, c in from the user. One of the problems we had previously identified is if the user enters “bad” input: if a = 0, we would end up dividing by zero; if b2 −4ac < 0 then we would have complex roots. With conditionals, we can now check for these issues and exit with an error message. Another potential case we might want to handle differently is when there is only one distinct root (b2 −4ac = 0). In that case, the quadratic formula simplifies to −b 2a and we can print a different, more specific message to the user. The full program can be found in Code Sample 38.4. 522
ComputerScienceOne_Page_556_Chunk2090
38.3. Examples 1 <?php 2 3 /** 4 * This program computes the logarithm base b (b > 1) 5 * of a given number x > 0 6 */ 7 8 if($argc != 3) { 9 printf("Usage: %s b x \n", $argv[0]); 10 exit(1); 11 } 12 13 $b = floatval($argv[1]); 14 $x = floatval($argv[2]); 15 16 if($x <= 0) { 17 printf("Error: x must be greater than zero\n"); 18 exit(1); 19 } 20 if($b <= 1) { 21 printf("Error: base must be greater than one\n"); 22 exit(1); 23 } 24 25 $result = log($x) / log($b); 26 printf("log_(%f)(%f) = %f\n", $b, $x, $result); 27 28 ?> Code Sample 38.2.: Logarithm Calculator Program in C 523
ComputerScienceOne_Page_557_Chunk2091
38. Conditionals 1 <?php 2 //prompt for income from the user 3 printf("Please enter your Adjusted Gross Income: "); 4 5 $income = floatval(trim(fgets(STDIN))); 6 7 //prompt for children 8 printf("How many children do you have? "); 9 $numChildren = intval(trim(fgets(STDIN))); 10 11 if($income < 0 || $numChildren < 0) { 12 printf("Invalid inputs"); 13 exit(1); 14 } 15 16 if($income <= 18150) { 17 $baseTax = $income * .10; 18 } else if($income <= 73800) { 19 $baseTax = 1815 + ($income -18150) * .15; 20 } else if($income <= 148850) { 21 $baseTax = 10162.50 + ($income - 73800) * .25; 22 } else if($income <= 225850) { 23 $baseTax = 28925.00 + ($income - 148850) * .28; 24 } else if($income <= 405100) { 25 $baseTax = 50765.00 + ($income - 225850) * .33; 26 } else if($income <= 457600) { 27 $baseTax = 109587.50 + ($income - 405100) * .35; 28 } else { 29 $baseTax = 127962.50 + ($income - 457600) * .396; 30 } 31 32 if($numChildren <= 3) { 33 $credit = $numChildren * 1000; 34 } else { 35 $credit = 3000; 36 } 37 38 if($baseTax - $credit >= 0) { 39 $totalTax = $baseTax - $credit; 40 } else { 41 $totalTax = 0; 42 } 43 44 printf("AGI: $%10.2f\n", $income); 45 printf("Tax: $%10.2f\n", $baseTax); 46 printf("Credit: $%10.2f\n", $credit); 47 printf("Tax Liability: $%10.2f\n", $totalTax); 48 49 ?> Code Sample 38.3.: Tax Program in PHP 524
ComputerScienceOne_Page_558_Chunk2092
38.3. Examples 1 <?php 2 3 /** 4 * This program computes the roots to a quadratic equation 5 * using the quadratic formula. 6 */ 7 8 if($argc != 4) { 9 printf("Usage: %s a b c\n", $argv[0]); 10 exit(1); 11 } 12 13 $a = floatval($argv[1]); 14 $b = floatval($argv[2]); 15 $c = floatval($argv[3]); 16 17 if($a === 0) { 18 printf("Error: a cannot be zero\n"); 19 exit(1); 20 } else if($b*$b < 4*$a*$c) { 21 printf("Error: cannot handle complex roots\n"); 22 exit(1); 23 } else if($b*$b === 4*$a*$c) { 24 $root1 = -$b / (2*$a); 25 printf("Only one distinct root: %f\n", $root1); 26 } else { 27 $root1 = (-$b + sqrt($b*$b - 4*$a*$c) ) / (2*$a); 28 $root2 = (-$b - sqrt($b*$b - 4*$a*$c) ) / (2*$a); 29 30 printf("The roots of %fx^2 + %fx + %f are: \n", $a, $b, $c); 31 printf(" root1 = %f\n", $root1); 32 printf(" root2 = %f\n", $root2); 33 } 34 35 ?> Code Sample 38.4.: Quadratic Roots Program in PHP With Error Checking 525
ComputerScienceOne_Page_559_Chunk2093
39. Loops PHP supports while loops, for loops, and do-while loops using the keywords while , for , and do (along with another while ). Continuation conditions for loops are enclosed in parentheses, (...) and blocks of code associated with the loop are enclosed in curly brackets. 39.1. While Loops Code Sample 39.1 contains an example of a basic while loop in PHP. As with conditional statements, our code style places the opening curly bracket on the same line as the while keyword and continuation condition. The inner block of code is also indented and all lines in the block are indented to the same level. In addition, the continuation condition does not contain a semicolon since it is not an executable statement. Just as with an if-statement, if we had placed a semicolon it would have led to unintended results. Consider the following: 1 while($i <= 10); { 2 //perform some action 3 $i++; //iteration 4 } A similar problem occurs. The while keyword and continuation condition bind to the next executable statement or code block. As a consequence of the semicolon, the executable statement that gets bound to the while loop is empty. What happens is 1 $i = 1; //Initialization 2 while($i <= 10) { //continuation condition 3 //perform some action 4 $i++; //iteration 5 } Code Sample 39.1.: While Loop in PHP 527
ComputerScienceOne_Page_561_Chunk2094
39. Loops 1 $i = 1; 2 $flag = true; 3 while($flag) { 4 //perform some action 5 $i++; //iteration 6 if($i>10) { 7 $flag = false; 8 } 9 } Code Sample 39.2.: Flag-controlled While Loop in PHP even worse: the program will enter an infinite loop. To see this, the code is essentially equivalent to the following: 1 while($i <= 10) { 2 } 3 { 4 //perform some action 5 $i++; //iteration 6 } In the while loop, we never increment the counter variable $i , the loop does nothing, and so the computation will continue on forever! It is valid PHP and will run, but obviously won’t work as intended. Avoid this problem by using proper syntax. Another common use for a while loop is a flag-controlled loop in which we use a Boolean flag rather than an expression to determine if a loop should continue or not. Since PHP has built-in Boolean types, we can use a variable along with the keywords true and false . An example can be found in Code Sample 39.2. 39.2. For Loops For loops in PHP use the familiar syntax of placing the initialization, continuation condition, and iteration on the same line as the for keyword. An example can be found in Code Sample 39.3. Semicolons are placed at the end of the initialization and continuation condition, but not the iteration statement. With while loops, the opening curly bracket is placed on the same line as the for keyword. Code within the loop body is indented, all at the same indentation level. 528
ComputerScienceOne_Page_562_Chunk2095
39.3. Do-While Loops 1 $i; 2 for($i=1; $i<=10; $i++) { 3 //perform some action 4 } Code Sample 39.3.: For Loop in PHP 1 $i; 2 do { 3 //perform some action 4 $i++; 5 } while($i <= 10); Code Sample 39.4.: Do-While Loop in PHP 39.3. Do-While Loops PHP also supports do-while loops. Recall that the difference between a while loop and a do-while loop is when the continuation condition is checked. For a while loop it is prior to the beginning of the loop body and in a do-while loop it is at the end of the loop. This means that a do-while always executes at least once. An example can be found in Code Sample 39.4. The opening curly bracket is again on the same line as the keyword do . The while keyword and continuation condition are on the same line as the closing curly bracket. In a slight departure from previous syntax, a semicolon does appear at the end of the continuation condition even though it is not an executable statement. 39.4. Foreach Loops Finally, PHP supports foreach loops using the keyword foreach . Some of this will be a preview of Section 42 where we discuss arrays in PHP,1 In short you can iterate over the elements of an array as follows. 1 $arr = array(1.41, 2.71, 3.14); 2 foreach($arr as $x) { 3 //x now holds the "current" element in arr 1Actually, PHP supports associative arrays, which are not the same thing as traditional arrays. 529
ComputerScienceOne_Page_563_Chunk2096
39. Loops 4 } In the foreach syntax we specify the array we want to iterate over, $arr and use the keyword as . The last element in the statement is the variable name that we want to use within the loop. This should be read as “ foreach element $x in the array $arr ...”. Inside the loop, the variable $x will be automatically updated on each iteration to the next element in $arr . 39.5. Examples 39.5.1. Normalizing a Number Let’s revisit the example from Section 4.1.1 in which we normalize a number by continually dividing it by 10 until it is less than 10. The code in Code Sample 39.5 specifically refers to the value 32145.234 but would work equally well with any value of $x . 1 $x = 32145.234; 2 $k = 0; 3 while($x > 10) { 4 $x = $x / 10; 5 $k++; 6 } Code Sample 39.5.: Normalizing a Number with a While Loop in PHP 39.5.2. Summation Let’s revisit the example from Section 4.2.1 in which we computed the sum of integers 1 + 2 + · · · + 10. The code is presented in Code Sample 39.6 We could easily generalize this code. Instead of computing a sum up to a particular number, we could have written it to sum up to another variable $n , in which case the for loop would instead look like the following. 1 for($i=1; $i<=$n; $i++) { 2 $sum += $i; 3 } 530
ComputerScienceOne_Page_564_Chunk2097
39.5. Examples 1 $sum = 0; 2 for($i=1; $i<=10; $i++) { 3 $sum += $i; 4 } Code Sample 39.6.: Summation of Numbers using a For Loop in PHP 39.5.3. Nested Loops Recall that you can write loops within loops. The inner loop will execute fully for each iteration of the outer loop. An example of two nested of loops in PHP can be found in Code Sample 39.7. 1 $n = 10; 2 $m = 20; 3 for($i=0; $i<$n; $i++) { 4 for($j=0; $j<$m; $j++) { 5 printf("(i, j) = (%d, %d)\n", $i, $j); 6 } 7 } Code Sample 39.7.: Nested For Loops in PHP The inner loop executes for j = 0, 1, 2, . . . , 19 < m = 20 for a total of 20 itera- tions. However, it executes 20 times for each iteration of the outer loop. Since the outer loop executes for i = 0, 1, 2, . . . , 9 < n = 10, the total number of times the printf() statement executes is 10 × 20 = 200. In this example, the sequence (0, 0), (0, 1), (0, 2), . . . , (0, 19), (1, 0), . . . , (9, 19) will be printed. 39.5.4. Paying the Piper Let’s adapt the solution for the loan amortization schedule we developed in Section 4.7.3. First, we’ll read the principle, terms, and interest as command line inputs. Adapting the formula for the monthly payment and using the standard math library’s pow() function, we get 1 $monthlyPayment = ($monthlyInterestRate * $principle) / 2 (1 - pow( (1 + $monthlyInterestRate), -$n)); 531
ComputerScienceOne_Page_565_Chunk2098
39. Loops The monthly payment may come out to be a fraction of a cent, say $43.871. For accuracy, we need to ensure that all of the figures for currency are rounded to the nearest cent. The standard math library does have a round() function, but it only rounds to the nearest whole number, not the nearest 100th. However, we can adapt the “off-the-shelf” solution to fit our needs. If we take the number, multiply it by 100, we get 4387.1 which we can now round to the nearest whole number, giving us 4387. We can then divide by 100 to get a number that has been rounded to the nearest 100th! $monthlyPayment = round($monthlyPayment * 100) / 100; We can use the same trick to round the monthly interest payment and any other number expected to be whole cents. To output our numbers, we use printf() and take care to align our columns to make make it look nice. To finish our adaptation, we handle the final month separately to account for an over/under payment due to rounding. The full solution can be found in Code Sample 39.8. 532
ComputerScienceOne_Page_566_Chunk2099
39.5. Examples 1 <?php 2 if($argc != 4) { 3 printf("Usage: %s principle apr terms\n", $argv[0]); 4 exit(1); 5 } 6 7 $principle = floatval($argv[1]); 8 $apr = floatval($argv[2]); 9 $n = intval($argv[3]); 10 11 $balance = $principle; 12 $monthlyInterestRate = $apr / 12; 13 14 //monthly payment 15 $monthlyPayment = ($monthlyInterestRate * $principle) / 16 (1 - pow( (1 + $monthlyInterestRate), -$n)); 17 //round to the nearest cent 18 $monthlyPayment = round($monthlyPayment * 100) / 100; 19 20 printf("Principle: $%.2f\n", $principle); 21 printf("APR: %.4f%%\n", $apr * 100.0); 22 printf("Months: %d\n", $n); 23 printf("Monthly Payment: $%.2f\n", $monthlyPayment); 24 25 //for the first n-1 payments in a loop: 26 for($i=1; $i<$n; $i++) { 27 // compute the monthly interest, rounded: 28 $monthlyInterest = 29 round( ($balance * $monthlyInterestRate) * 100) / 100; 30 // compute the monthly principle payment 31 $monthlyPrinciplePayment = $monthlyPayment - $monthlyInterest; 32 // update the balance 33 $balance = $balance - $monthlyPrinciplePayment; 34 // print i, monthly interest, monthly principle, new balance 35 printf("%d\t$%10.2f $%10.2f $%10.2f\n", $i, $monthlyInterest, 36 $monthlyPrinciplePayment, $balance); 37 } 38 39 //handle the last month and last payment separately 40 $lastInterest = round( ($balance * $monthlyInterestRate) * 100) / 100; 41 $lastPayment = $balance + $lastInterest; 42 43 printf("Last payment = $%.2f\n", $lastPayment); 44 ?> Code Sample 39.8.: Loan Amortization Program in PHP 533
ComputerScienceOne_Page_567_Chunk2100