text stringlengths 1 7.76k | source stringlengths 17 81 |
|---|---|
20. Arrays **m m[0] m[1] m[2] m[3] m[0][0] m[0][1] m[0][2] m[1][0] m[1][1] m[1][2] m[2][0] m[2][1] m[2][2] m[3][0] m[3][1] m[3][2] Figure 20.2.: Contiguous Two Dimensional Array. The initial pointer-to-pointers m is initialized to an array of pointers, m[0]..m[3] . A 4 × 3 contiguous array is created and each of the pointers is initialized to the proper location so it can be treated as a two-dimensional array. 20.5. Dynamic Data Structures The C standard library does not provide a variety of advanced, dynamic data structures such as linked lists or sets. As of C89 and POSIX.1 the C standard library does provide hash tables and binary search trees, but does not require implementations of other dynamic data structures. Instead, you must either implement your own or utilize a third-party library such as glibc, the GNU C library (http://www.gnu.org/software/libc/). 324 | ComputerScienceOne_Page_358_Chunk1901 |
21. Strings C has no built-in string type. Instead, strings are represented as arrays of char elements. They differ from, say arrays of int or double types, however, in that they are null terminated arrays. The end of the string must always be denoted with a null-terminating character, '\0' (the 0 valued character in the ASCII table). Failure to properly null-terminate a string may lead to undefined behavior or fatal errors. C provides a good variety of functions in its standard string library (included in the string.h header). All of these functions operate under the assumption that the strings passed to it are null-terminated. It is your responsibility to ensure that they are. Moreover, some of the functions that operate on strings will inset the null-terminating character for us, but others will not. It is important to understand the expectations and guarantees of each function. 21.1. Character Arrays We’ve previously used string literals when using the standard input and output functions, printf() and scanf() . You can also create static strings (as static arrays) using the standard assignment operator. Some examples: 1 char firstName[] = "Tom"; 2 char lastName[] = "Waits"; index char *s H 0 e 1 l 2 l 3 o 4 \0 5 ? 6 ? 7 ? 8 ? 9 Figure 21.1.: A string in C is achieved by using a char array. However, the string is terminated by a null-terminating character, \0 . Though an array may have space for additional characters, they are irrelevant if the null terminator precedes them. 325 | ComputerScienceOne_Page_359_Chunk1902 |
21. Strings This syntax can only be used when creating static strings (they are allocated on the stack and locally scoped). The compiler is able to scan the string literal and determine how many characters are needed and even inserts the null-terminating character for us. Thus, the length of the two strings in the example are 3 and 5 respectively, but the array size created for them will be 4 and 6 respectively to accommodate the null-terminating character. Static strings have the same limitations as static arrays. Since they are allocated on the stack, they cannot be returned from a function. Just as with int and double types, however, we can dynamically allocate memory to hold char types using malloc() . The important difference being that we need to always allocate at least one more character to accommodate the null-terminating character. 1 char *fullName = NULL; 2 fullName = (char *) malloc(sizeof(char) * 10); This example creates a dynamically allocated char array that is able to hold 9 characters (since one will be needed for the null-terminating character). However, once we have created the array, we cannot simply assign an entire string to it using the usual assignment operator. 1 //THIS IS *WRONG*: 2 fullName = "Tom Waits"; This will compile, but doesn’t give us what we want. Recall that fullName is a character pointer. Using the assignment operator simply makes it point to the static, literal string "Tom Waits" . In fact, we lose our reference to the dynamically allocated array that was created with malloc() , resulting in a memory leak. Instead, we need to use a function in the standard library to copy a string. The function in the standard library that allows you to copy strings is as follows. char *strcpy(char *dest, const char *src); The name, strcpy is short for “string copy.”1 Both arguments are character pointers. In keeping with the use of the assignment operator, the second argument (“source”) is copied into the first, “destination” (just as with an assignment operator, the value 1The abbreviations are mostly historic: in the 70s and 80s when memory was measured in kilobytes, saving a few characters made a significant difference. 326 | ComputerScienceOne_Page_360_Chunk1903 |
21.2. String Library on the right-hand-side is copied into the variable on the left-hand-side). Moreover, the second argument has been marked as const indicating that it will not be changed. The contents of the first argument will be changed since we are copying a string into it, erasing whatever contents it had prior. Finally, the function returns a pointer to the dest argument, mostly so that it can be used in nested function calls (though we’ll avoid such confusingly terse “tricks”). From our example: 1 //"assign" (copy) "Tom Waits" into the string fullName: 2 strcpy(fullName, "Tom Waits"); In addition, we can access and modify individual characters in a string using the usual indexing and assignment operator with char literals. 1 //access individual characters: 2 char firstInitial = fullName[0]; //'T' 3 char lastInitial = fullName[4]; //'W' 4 5 //printing: 6 printf("First Initial: %c\n", fullName[0]); 7 8 //modifying: 9 firstInitial[0] = 't'; 10 firstInitial[4] = 'w'; 11 //fullName is now "tom waits" 21.2. String Library The standard string library provides many other convenient functions 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 As with regular arrays, we are responsible for ensuring that we do not access characters outside the character array of a string. Since a string is null-terminated, there is a nice 327 | ComputerScienceOne_Page_361_Chunk1904 |
21. Strings function provided by the string library to determine its length, size_t strlen(const char *s); Recall that size_t can essentially be treated as an integer, indicating the number of bytes in the passed string. Since a character is a single byte, this function tells us how many character are in the given string not including the null-terminating string. This function is an abbreviation for “string length.” Using this function we can easily iterate over each character in a string. 1 int i; 2 for(i=0; i<strlen(fullName); i++) { 3 printf("fullName[%d] = %c\n", i, fullName[i]); 4 } Concatenation A concatenation function is provided that allows you to append one string to the end of another. char *strcat(char *dest, const char *src); Similar to the strcpy() function, strcat() appends the “source” ( src ) string to the end of the “destination” ( dest ) string. It is your responsibility to ensure that the destination string is large enough to accommodate the source string. If it is not, then it could lead to undefined behavior as strcat() overwrites memory after the end of the destination string. Further, strcat() will copy the null-terminating character for you so that the resulting string (now stored in dest ) is a valid null-terminated string. 1 char *formattedName = (char *)malloc(11 * sizeof(char)); 2 //copy "Waits" into formattedName 3 strcpy(formattedName, lastName); 4 //append a ", " to formattedName 5 strcat(formattedName, ", "); 6 //append the firstName to the formattedName 7 strcat(formattedName, firstName); 8 //formattedName now contains "Waits, Tom" 328 | ComputerScienceOne_Page_362_Chunk1905 |
21.2. String Library Byte-Limited Versions C also provides several byte-limited versions of the copy and concatenation functions: char *strncpy(char *dest, const char *src, size_t n); char *strncat(char *dest, const char *src, size_t n); They work similarly in that they copy/concatenate the source, src string into the destination, dest string. However, there is a third parameter, n which specifies at most how many bytes to copy/concatenate. The parameter, n allows you to limit the number of characters that the operation uses. If either of these functions encounters the null-terminating character before n bytes have been copied/concatenated, they stop and copy the null-terminating character for us. However, these functions do not always handle the null-terminating character for us. If the null-terminating character appears in the first n bytes, it will be copied for us, but if it is not, we need to be sure to handle it ourselves. For example, 1 char email[] = "twaits@cse.unl.edu"; 2 char *login = (char *) malloc(7 * sizeof(char)); 3 4 //only copy the first 6 characters: 5 strncpy(login, email, 6); 6 //at this point, login contains "twaits" but is 7 //not null-terminated, so we manually terminate it 8 login[6] = '\0'; Computing a Substring The byte-limited versions of the copy function can be used to compute a substring of another string. The parameter n can be used to limit the length of the string, but how might we specify where the substring should start? For example, in the string "Thomas Alan Waits" we may want to get the substring representing his middle name, "Alan" . The length is 4 and we can specify that the copying should start by using an index. In this case, we want the copying to start at index 7 , the 8th character. If the string is stored in an array named name , this would be name[7] . However, indexing an array like this results in a single character and strncpy() expects a string (a character pointer). Fortunately, we know how to do this: 329 | ComputerScienceOne_Page_363_Chunk1906 |
21. Strings using the referencing operator, we can turn the 8th character into a character pointer, &name[7] . A full example: 1 char name[] = "Thomas Alan Waits"; 2 char *middleName = (char *) malloc(sizeof(char) * 5); 3 strncpy(middleName, &name[7], 5); 4 middleName[4] = '\0'; 5 //middleName now holds "Alan" In the call to malloc() , we included space for a null-terminating character. Furthermore, strncpy() does not insert the null-terminating character for us in this case. In line 4 we manually insert it. 21.3. Arrays of Strings We often need to deal with collections of strings. An array of strings can be viewed as a 2-dimensional character array. Indeed, we’ve seen this before. In the typical C program’s main() function, command line arguments are passed as the second parameter: int main(int argc, char **argv) which is represented as a double character pointer, char ** . Conceptually, each row is a string, char * . The first parameter, argc indicates how many rows there are. The main() function doesn’t need to be told how big each “row” is since strings are null-terminated. We can create our own arrays of strings similar to how we created 2-dimensional arrays of int and double types. 1 //create an array that can hold 5 strings 2 char **names = (char **) malloc(5 * sizeof(char*)); 3 int i; 4 for(i=0; i<5; i++) { 5 //each string can hold at most 19 characters 6 names[i] = (char *) malloc(sizeof(char) * 20); 7 } 8 strcpy(names[0], "Margaret Hamilton"); 9 strcpy(names[1], "Ada Lovelace"); 10 strcpy(names[2], "Grace Hopper"); 330 | ComputerScienceOne_Page_364_Chunk1907 |
21.4. Comparisons 11 strcpy(names[3], "Marie Curie"); 12 strcpy(names[4], "Hedy Lamarr"); 21.4. Comparisons When comparing strings in C, we cannot use the numerical comparison operators such as == , or < . Because strings are represented as arrays, using these operators actually compares the variable’s memory addresses. 1 char *a = (char *) malloc(sizeof(char) * 13); 2 char *b = (char *) malloc(sizeof(char) * 13); 3 strcpy(a, "Hello World!"); 4 strcpy(b, "Hello World!"); 5 6 if(a == b) { 7 printf("strings match!\n"); 8 } 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 malloc() ) they are not equal. The C string library provides a standard comparator function to compare strings based on their content: int strcmp(const char *a, const char *b); The function takes two strings and returns an integer based on the lexicographic ordering of a and b . If a precedes b , strcmp() returns something negative. It returns zero if a and b have the same content. Otherwise it returns something positive if b precedes a . Some examples: 1 int x; 2 x = strcmp("apple", "banana"); //x is negative 3 x = strcmp("zelda", "mario"); //x is positive 331 | ComputerScienceOne_Page_365_Chunk1908 |
21. Strings 4 x = strcmp("Hello", "Hello"); //x is zero 5 6 //shorter strings precede longer strings: 7 x = strcmp("apple", "apples"); //x is negative 8 //uppercase precede lowercase: 9 x = strcmp("Apple", "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 comparisons ignoring case if we need to using the alternative: int strcasecmp(const char *s1, const char *s2); which is a case-insensitive version. Here, strcasecmp("Apple", "apple") will return zero as the two strings are the same ignoring the cases. The comparison functions also have byte-limited versions, int strncmp(const char *s1, const char *s2, size_t n); and int strncasecmp(const char *s1, const char *s2, size_t n); Both will only make comparisons in the first n bytes of the strings. Thus, the comparison, strncmp("apple", "apples", 5) will result in zero as the two strings are equal in the first 5 bytes. 21.5. Conversions We’ve previously examined the functions atoi() and atof() that allow you to convert strings that hold numeric values to int and double values respectively. Another way to convert strings to numbers is to use a function similar to the familiar scanf() function which reads its string from the standard input. The sscanf() function reads its “input” from a string instead of the standard input. 1 char s[] = "103212.3214"; 2 double x; 3 sscanf(s, "%lf", &x); 4 //x now has the value 103212.3214 332 | ComputerScienceOne_Page_366_Chunk1909 |
21.6. Tokenizing The sscanf() function differs in its first argument: the string that contains the value you want to parse. Otherwise, the second two arguments are as in scanf() : the format (as a string) and the variable(s) that the results should be stored in (passed by reference). Likewise, there is a companion sprintf() which is similar to the printf() function, but instead of printing to the standard output, it “prints” to the string. That is, the result is placed in a string. 1 int x = 10; 2 double y = 3.14; 3 char *s = (char *) malloc(sizeof(char) * 50); 4 sprintf(s, "The value of x is %d, y = %f.", x, y); 5 //s now contains "The value of x is 10, y = 3.140000." 21.6. Tokenizing Recall that tokenizing is the process of splitting up a string along 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. The C string library provides a tokenizing function: char *strtok(char *str, const char *delim); which works as follows. The first argument is the string that you want to tokenize and the second contains the delimiter that you want to split along. The second argument is actually a string and allows you to specify more than one delimiter, but we’ll restrict our attention to single character delimiters. The function returns a pointer to the first token in the string. To get the second and all subsequent tokens, we call strtok() again, but we pass it NULL as the first argument to continue parsing the same string. If we pass a new string as the first argument to strtok() the tokenization process will start over on the new string. Note that the first argument does not have the const keyword. This is because strtok() will make changes to the string during the tokenization process. If the string needs to be preserved, tokenization should be performed on a deep copy of the string. When there are no more tokens in the string, strtok() returns NULL to indicate no 333 | ComputerScienceOne_Page_367_Chunk1910 |
21. Strings more tokens are in the string. This logic can be used to write a while loop to iterate over each token. Consider the following example. 1 char data[] = "Smith,Joe,12345678,1985-09-08"; 2 char *token = NULL; 3 //make the initial call to strtok: 4 token = strtok(data, ","); 5 while(token != NULL) { 6 printf("token: %s\n", token); 7 //get the next token: 8 token = strtok(NULL, ","); 9 } This outputs the following: token: Smith token: Joe token: 12345678 token: 1985-09-08 It should be noted that strtok() is not reentrant. It can only work on one string at a time. In a multithreaded application, two threads cannot both use strtok() or they would end up processing each other’s strings. Even in a non-threaded application, we need to be careful. For example, we cannot process a string using strtok() in one function and then call another function that does the same. C does provide a reentrant version, strtok_r() that can be used. 334 | ComputerScienceOne_Page_368_Chunk1911 |
22. File I/O C provides several functions to manipulate and process files. Like other I/O functions, these are all defined in the standard input/output library, stdio.h . Writing binary or plaintext data is determined by which functions you use. Whether or not a file input/output stream is buffered or unbuffered is determined by the system configuration. There are some ways in which this can be changed, but we will not cover them in detail. 22.1. Opening Files Files are represented in C by a FILE * pointer type defined in the standard input/output library. As a pointer, it essentially points to the file stored in memory. To open a file, you use the fopen() function (short for file open) which takes two arguments and returns a FILE * pointer: FILE *fopen(const char *path, const char *mode); The first argument is the file path/name that you want to open for processing. The second argument is a string representing the “mode” that you want to open the file in. There are several supported modes, but the two we will be interested in are reading, in which case you pass it "r" and writing in which case you pass it "w" . The path can be an absolute path, relative path, or may be omitted if the file is in the current working directory. 1 //open a file for reading (input): 2 FILE *input = fopen("/user/apps/data.txt", "r"); 3 //open a file for writing (output): 4 FILE *output = fopen("./results.txt", "w"); 5 6 if(input == NULL) { 7 fprintf(stderr, "Unable to open input file"); 8 exit(1); 9 } 10 11 if(output == NULL) { 335 | ComputerScienceOne_Page_369_Chunk1912 |
22. File I/O 12 fprintf(stderr, "Unable to open output file"); 13 exit(1); 14 } The two checks above check that the file opened successfully. If the file opening failed, fopen() returns NULL . Opening a file can fail for a number of reasons. On POSIX systems for example, additional information can be obtained by accessing the standard error number, errno (see Section 19.1). Some errors that can result: • ENOENT – No such file or directory • EACCES – Permission denied • ENOMEM – Insufficient storage space is available among many other possibilities. These error codes can be used to implement more specific error handling code if desired. 22.2. Reading & Writing When a file is opened, the file pointer returned by fopen() initially points to the beginning of the file. As you read from it or write to it, the pointer advances through the file content. 22.2.1. Plaintext Files To process a plaintext file we use two functions, fprintf() for output and fscanf() for input. These two functions should look familiar. They work almost exactly the same as printf() and scanf() that work with the standard output and standard input respectively. In fact, the standard in/out are both files so it makes sense that they can be read from/written to. The f prefixed versions are simply generalizations that can be used for any file. The only difference is that the first argument for these two functions is the file you want to output to or read from. 1 int x = 10; 2 double y = 3.14; 3 4 //write to a plaintext file 336 | ComputerScienceOne_Page_370_Chunk1913 |
22.2. Reading & Writing 5 fprintf(output, "Hello World!\n"); 6 fprintf(output, "x = %d, y = %f\n", x, y); 7 8 //read from a plaintext file 9 fscanf(input, "%d", &x); 10 fscanf(input, "%lf", &y); 11 12 //these are equivalent to printf, scanf: 13 fprintf(stdout, "Please enter an integer:"); 14 fscanf(stdin, "%d", &x); Using fscanf() for arbitrary string input is potentially dangerous as there is limited bounds checking. We must store the input value from the file into a string (character array), but if the file or line contains more characters than the array can accommodate we may have a buffer overflow. A better way to read input is to use fgets() which allows us to limit the number of bytes that are read. char *fgets(char *s, int size, FILE *stream); The first argument is the string that the input data will be read into. The second parameter is how we limit the number of characters that will be read. It actually reads in one fewer character, size-1 to account for the null-terminating character which fgets() automatically inserts for us. The last argument is the file pointer that we wish to read from. The behavior of fgets() is that it reads up to size-1 characters from the input file and places the results into s . If fgets() encounters either an EOF symbol or an endline character, '\n' it stops reading. In the case of an endline character, it is included in the result and may need to be chomped out (that is, removed). The fgets() function can be used to process a file line by line until the end of the file is reached. Each line can be processed (perhaps tokenized) individually to extract particular pieces of data. This is typically how a CSV or similar file may be processed. To determine if the end of the file has been reached, you can use the return value of the function: it returns NULL when no more characters have been read. 1 FILE *input = fopen("data.txt", "r"); 2 //this assumes that no line is more than 999 characters 3 char line[1000]; 337 | ComputerScienceOne_Page_371_Chunk1914 |
22. File I/O 4 //read the first line 5 char *s = fgets(line, 1000, input); 6 while(s != NULL) { 7 8 //chomp the endline character from line: 9 line[strlen(line)-1] = '\0'; 10 11 //process the current buffer 12 //for demonstration, we simply print it: 13 printf("line = %s\n", line); 14 15 //read the next line 16 s = fgets(line, 1000, input); 17 } A similar function, int fgetc(FILE *stream) allows us to get a single character from the input file (returned as an int ) if we prefer to read character by character. 22.2.2. Binary Files To read and write binary data to files we use two different functions: size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream); for reading from a file and size_t fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream); to write to a file. Both functions have the exact same arguments: 1. ptr is a pointer to the item that is being read/written (possibly an array of elements) 2. size is the number of bytes that each element stored at ptr take, usually determined by using sizeof() 3. nmemb is the number of elements to be written/read 4. stream is the file stream to be read from/written to These functions allow you to read/write an arbitrary amount of binary data. When reading, it is your responsibility, as usual, to ensure that the ptr is large enough to 338 | ComputerScienceOne_Page_372_Chunk1915 |
22.3. Closing Files accommodate the data you are reading into it. 1 int x = 10; 2 3 FILE *binaryOutputFile = fopen("demo.bin", "w"); 4 5 //write a single int to a file: 6 fwrite(&x, sizeof(int), 1, binaryOutputFile); 7 8 FILE *binaryInputFile = fopen("input.bin", "r"); 9 10 //read a single int from the file: 11 fread(&x, sizeof(int), 1, binaryInputFile); 12 13 //read an entire array from the file: 14 int *a = (int *) malloc(10 * sizeof(int)); 15 fread(a, sizeof(int), 10, binaryInputFile); 22.3. Closing Files Once you are done processing a file, you should close it using the fclose() function: int fclose(FILE *fp); which takes a single argument, the FILE pointer of the file you wish to close. Closing an invalid file may result in an error or segmentation fault. In any case, after a file has been closed, it cannot be read from or written to, doing so is undefined behavior. Failure to close a file may result in a corrupted file. 339 | ComputerScienceOne_Page_373_Chunk1916 |
23. Structures Strictly speaking, C is not an object-oriented programming language, it is an imperative (or, relatedly a structured or procedural) programming language. This means that C can be characterized as a language that changes a program’s state through statements and the use of function calls. Though C does not have objects, it does support a “weak” form of encapsulation through the use of structures. Structures are a user-defined type that collects multiple pieces of data together into one logical unit. Once defined, structures can be used in a program just like any other variable type; structure variables can be declared, passed and returned from functions, pointers to structures can be used, etc. Structures form a “weak” form of encapsulation in that they only provide the grouping of data. The protection of data through visibility keywords is not supported. The grouping of functions that act on that data is also not readily supported.1 However, even this weak form provides a very useful and convenient way to collect related pieces of ?ata. 23.1. Defining Structures To define a structure, we use the keyword struct along with the previously introduced keyword typedef . To motivate an example, let’s reconsider a student entity, which has an ID (integer), first and last name (strings), and a GPA (a floating point number). Each of these pieces of data can be encapsulated into a structure as follows. 1 typedef struct { 2 int id; 3 char *firstName; 4 char *lastName; 5 double gpa; 6 } Student; Note the syntax and naming conventions: 1You can define a structure with function pointers as elements, so structures could technically include “methods” but this is not really what most people think of when considering object-oriented paradigms. 341 | ComputerScienceOne_Page_375_Chunk1917 |
23. Structures • The elements of the structure (also referred to as components or members) are included inside curly brackets, delimited using semicolons (in contrast to an enu- merated type which is a list, these elements do not constitute a list). • A structure may contain any number of elements of any type. • The name (identifier) of the structure is provided at the end, ended with a semicolon. • We use a modern naming convention: each element is named using lower camel casing while the name of the structure itself uses upper camel casing. In addition, structure declarations are generally placed in a header file along with any any function prototypes that use the structure as a parameter or a return type. Once you have defined a structure you can use it as you would a built-in variable type. For example, Student s; declares a Student structure with the variable name s . 23.1.1. Alternative Declarations In some examples and code bases you may find an alternative way of declaring a structure that looks like the following. 1 struct Student { 2 ... 3 }; This syntax omits the keyword typedef and places the structure name at the beginning. The difference is a bit technical (the original syntax creates an anonymous structure with the Student identifier placed in the global namespace, while this declaration places the Student identifier in the structure namespace), but one of the consequences of using this type of declaration is that the Student identifier is not in the global scope, so to declare a variable of the type Student you need to further specify that it is a structure using the following syntax. struct Student s; Further, you may also see another style, 342 | ComputerScienceOne_Page_376_Chunk1918 |
23.1. Defining Structures 1 typedef struct Student { 2 ... 3 } Student; Which places the Student identifier in both the global space and in the “structure” space. Which style of declaration you use depends on several factors, but for simplicity we’ll stick with the first style. In addition, you may see some older naming conventions use lowercase underscore naming for structure names. In particular, POSIX systems use names that end with _t (indicating a structure type). You should avoid such naming conventions to avoid conflicts. Finally, though C does not provide a mechanism for the protection of data, many libraries and code bases will begin certain member variables with underscore(s) to indicate that they are “internal” variables used by the library and should not be accessed or modified. For example, _someVariable or __anotherVariable would indicate “private” variables that should not be tampered with. The C language itself would still allow you access and modify the variables, but doing so may violate assumptions and expectations of the library code, leading to undefined behavior. 23.1.2. Nested Structures Consider adding another member variable to the Student structure to model a student’s date of birth. How might we model a date? Unix systems model time as a single integer value that represents the number of milliseconds that have passed since the Unix epoch, January 1st, 1970 (also known as Coordinated Universal Time (UTC)). For example, the New Horizons space probe was launched on January 19th, 2006 at 19:00:00 UTC. This corresponds to 1,137,697,200, roughly 1.137 billion milliseconds since the epoch. Another way to model time is as a string. There are several standards for time representations, but the most common is ISO standard 8601 [22] which specifies time using a format that includes a date, time and an offset from Greenwich Mean Time (GMT). For example, the New Horizons launch date/time would be represented as "2006-01-19T19:00:00+00:00" . To keep things simple, we’ll model our date using three numbers: a year, a month and a date. But how should we implement this? Conceptually, a date is a single entity, separating these three numbers doesn’t make much sense. This is a perfect opportunity to define another structure. 343 | ComputerScienceOne_Page_377_Chunk1919 |
23. Structures 1 typedef struct { 2 int id; 3 char *firstName; 4 char *lastName; 5 double gpa; 6 Date dateOfBirth; 7 } Student; Code Sample 23.1.: A Student structure declaration 1 typedef struct { 2 int year; 3 int month; 4 int date; 5 } Date; Once we have defined a structure we can use it as we would a normal variable, so it makes sense that we could include it in another structure. This is a good illustration of a form of composition where one structure may be composed of other structures. Since the Student structure “owns” an instance of the Date structure, it is necessary to ensure that the Date structure is declared before the Student structure (just as we need to declare variables before we use them. 23.2. Usage 23.2.1. Declaration & Initialization Once we have defined a structure (and included the header file it has been defined in), we can create instances using the usual syntax. 1 Student s; 2 Student t; 344 | ComputerScienceOne_Page_378_Chunk1920 |
23.2. Usage These static declarations will allocate enough space on the stack to hold all of the data associated with the structures (the two char * pointers, int , and double and the three int variables in the Date structure). However, the values stored in each of the structure’s member variables are undefined. With this style of declaration, C does not define default values. Another way to declare instances of our structures is to use the following syntax. 1 Student s = {}; 2 Student t = { 3 12345678, 4 "Grace", 5 "Hopper", 6 4.0, 7 { 8 1906, 9 1, 10 1 11 } 12 }; The first declaration creates a Student structure with default values (zero for any numeric types, null for any pointers). The second creates a Student structure initialized with the values provided in the curly brackets. The order matters here and will match the ordering of the original structure declaration. Since the dateOfBirth is a structure itself, a nested set of values within curly brackets is necessary. One draw back to this type of declaration is that the character pointers are statically declared. The strings "Grace" and "Hopper" are initialized in a read-only segment of memory, any attempts to change the contents of these strings are undefined behavior. The pointers themselves, however, can be reassigned. This static declaration allocates the structure on the stack. Since structures consist of multiple pieces of data, their memory footprint is larger. Allocating larger and larger structures on the stack runs the risk of running out of stack memory resulting in a stack overflow. To solve this, we can instead use dynamically allocated structures. To dynamically allocate a structure, we use a pointer to a structure and a call to malloc() to allocate enough space for the structure. Even though our structure is user-defined, we can still use the sizeof() macro to determine the number of bytes required by the structure. The compiler and macro are “smart” enough to look at the structure declaration and determine the size of each of its variables and add up the total number of bytes required. 345 | ComputerScienceOne_Page_379_Chunk1921 |
23. Structures Student *s = (Student *) malloc(sizeof(Student) * 1); The multiplication by 1 in this example is not strictly necessary, but emphasizes the fact that we are allocating space for one structure and not an array of structures. Initializing a dynamically allocated structure like this does not initialize any of its variables as there are no default values defined by C. Moreover, it does not initialize memory for any pointer member variables. For example the firstName and lastName pointers need to be manually initialized with additional malloc() calls. 23.2.2. Selection Operators Once we have a declared structure, we need to access its member variables and perhaps update them. If we have a statically declared structure, such as Student s; we can use the direct component selector operator, which is simply just a period followed by the member variable we wish to access. Commonly, this is referred to simply as the dot operator. 1 Student s; 2 3 //set values: 4 s.id = 87654321; 5 s.gpa = 3.9; 6 7 //access values: 8 printf("Name: %s, %s\n", s.lastName, s.firstName); 9 printf("GPA: %.2f\n", s.gpa); When structures are nested, we can use the dot operator multiple times to access members variables of member variables. 1 s.dateOfBirth.year = 2525; 2 s.dateOfBirth.month = 12; 3 s.dateOfBirth.date = 25; When we have a pointer to a structure, we cannot directly use the dot operator. Instead, 346 | ComputerScienceOne_Page_380_Chunk1922 |
23.2. Usage we have to change the pointer into a “normal” structure by dereferencing it, then we can use the dot operator. However, the dot operator has a higher order of precedence than the dereferencing operator, thus parentheses are required: 1 Student *s = ...; 2 (*s).id = 87654321; This can be a bit unwieldy, so C provides a convenience operator, the indirect component selector operator, or more commonly, the arrow operator that allows us to select a member variable with a single operator that resembles a right-pointing arrow. 1 Student *s = (Student *) malloc(sizeof(Student)); 2 3 //set values: 4 s->id = 87654321; 5 s->gpa = 3.9; 6 7 //initialize the string variables: 8 s->firstName = (char *) malloc(sizeof(char) * 6); 9 strcpy(s->firstName, "Grace"); 10 s->lastName = (char *) malloc(sizeof(char) * 7); 11 strcpy(s->lastName, "Hopper"); 12 13 //access values: 14 printf("Name: %s, %s\n", s->lastName, s->firstName); 15 printf("GPA: %.2f\n", s->gpa); 16 17 s->dateOfBirth.year = 2525; Note the last line: the dateOfBirth member variable was another structure, but not a pointer to a structure, so we use the dot operator to access the year member variable. Al- ternatively, we could have defined dateOfBirth to be a pointer, Date *dateOfBirth; in the Student structure. If we had, then to access the year member variable using two arrow operators, s->dateOfBirth->year . 347 | ComputerScienceOne_Page_381_Chunk1923 |
23. Structures 23.3. Arrays of Structures Just as we can create arrays of built-in types such as integers, we can also create arrays of our user-defined structures. As an example, the following creates an array of 10 Student structures. Once created, we can treat them like any other array. 1 Student *roster = (Student *) malloc(sizeof(Student) * 10); 2 3 ... 4 5 double sum = 0.0; 6 for(i=0; i<10; i++) { 7 sum += roster[i].gpa; 8 } 9 double averageGpa = sum / 10; As in the example, we can index each element in the array, roster . Once indexed, each element is a regular structure and so we use the dot operator to access each of its member variables. As with any other array, each element takes up a number of bytes, equal to sizeof(Student) . We can swap and reassign each element just like any other variable. For example, the following code swaps the first two elements using a temporary variable. 1 Student temp = roster[0]; 2 roster[0] = roster[1]; 3 roster[1] = temp; Each of these operations copies over every byte that makes up the structure. For small structures, this isn’t that big of a deal. However, for larger structures, this may become an issue, especially if we do this often or pass structures around to functions. As an alternative, we could instead deal indirectly with structures by creating an array of pointers to structures. Swapping elements then involves only copying pointer values rather than every byte that makes up the structure. To do this, we use the familiar pointer-to-pointer syntax. 1 Student **roster = (Student **) malloc(sizeof(Student *) * 10); 2 for(i=0; i<10; i++) { 348 | ComputerScienceOne_Page_382_Chunk1924 |
23.3. Arrays of Structures 3 roster[i] = (Student *) malloc(sizeof(Student) * 1); 4 } 5 6 //access each as pointers and use the arrow operator 7 roster[0]->id = 87654321; 8 roster[0]->gpa = 4.0; 9 10 //swap the first two *pointers*: 11 Student *temp = roster[0]; 12 roster[0] = roster[1]; 13 roster[1] = temp; As in the example above, if each element in the array is a pointer to a structure, then we use the arrow operator to access each member variable. The differences between these two approaches is illustrated in Figures 23.1 and 23.2. As presented, each Student structure takes 40 bytes.2 With the first approach (as in Figure 23.1, each structure instance is stored contiguously in memory. Swapping two records involves copying entire blocks of 40 bytes. In contrast, using pointers to structures as in Figure 23.2 means that structures may be stored non-contiguously in different memory locations. Swapping two structures is done indirectly by swapping pointers (only 8 bytes). The difference in this particular example is not that great (8 vs. 40 bytes), but with larger structures it can become an issue. Each approach has its own advantages and disadvantages and one may be more appropriate than the other in different situations. Hybrid Approach It is also possible to take a “hybrid” approach to storing structures in arrays that stores them both contiguously, but also allows you to reference them indirectly through a pointer array. This is essentially what we did in Section 20.4.1 when we created a contiguous 2-dimensional array of integers. We made a single call to malloc and then had to setup the pointers to each “row.” To do this with structures, we can do something similar. First, we declare and allocate a dynamic array as before. 1 int n = 10; 2 Student *rosterData = (Student *) malloc(n * sizeof(Student)); 2This is just an estimate and may vary on different systems and compilers. Usually, compilers use alignment and may pad structures with extra bytes in order to make it more efficient to store in memory. 349 | ComputerScienceOne_Page_383_Chunk1925 |
23. Structures Student *roster roster[0] (Student) roster[1] (Student) roster[2] (Student) ... roster[n-1] (Student) 40 bytes 40 bytes 40 bytes 40 bytes Figure 23.1.: An array of structures. Each record is stored in a contiguous manner one after the other. Student **roster roster[0] (Student*) roster[1] (Student*) roster[2] (Student*) ... roster[n-1] (Student*) Student (40 bytes) Student (40 bytes) Student (40 bytes) Student (40 bytes) Figure 23.2.: An array of structure pointers. Each record is a pointer that refers to a structure which may be stored non-contiguously in completely different memory locations. 350 | ComputerScienceOne_Page_384_Chunk1926 |
23.4. Using Structures With Functions Then, we can declare an array of Student pointers as well. 1 Student **roster = (Student **) malloc(n * sizeof(Student *)); But now we need to make each roster[i] pointer point to the i-th record in rosterData . Each record, rosterData[i] is a regular structure, but we need a pointer to it. In order to get a pointer, we use the referencing operator, &rosterData[i] and make each pointer point to it. 1 for(i=0; i<n; i++) { 2 roster[i] = &rosterData[i]; 3 } This approach is illustrated in Figure 23.3. Now we can indirectly reference each record in rosterData via a pointer in the roster array. 1 roster[0]->nuid = 12345678; If we wanted to “swap” two records, we simply swap their pointers instead of their data. Indeed, care must be taken not to swap the data in rosterData otherwise the pointers would become invalid and out-of-synch with the data array. 23.4. Using Structures With Functions As with built-in types, we can use structures as parameters to functions as well as the return type of functions. Consider the following examples. 1 void foo(Student s); 2 Student bar(); 351 | ComputerScienceOne_Page_385_Chunk1927 |
23. Structures Student **roster roster[0] (Student*) roster[1] (Student*) roster[2] (Student*) ... roster[n-1] (Student*) Student *rosterData roster[0] (Student) roster[1] (Student) roster[2] (Student) ... roster[n-1] (Student) 40 bytes 40 bytes 40 bytes 40 bytes 8 bytes Figure 23.3.: Hybrid Array of Structures. The rosterData is an array of contiguous structures. The roster array is an array of pointers that refer to each record. Accessing elements in rosterData is done indirectly through a pointer in roster In the first prototype, we would pass a Student structure by value to the function. As we’ve already seen, this would mean that every byte of the structure would be copied onto the stack. For larger structures, we risk a stack overflow while for even smaller structures this can be very inefficient. Likewise, the second prototype would return a structure. When assigned to a variable, every byte is copied. A better solution is to use dynamically allocated structures, passing them by reference to functions, and returning pointers to dynamically allocated instances as return types. For example, the functions above would be better implemented as follows. 1 void foo(const Student *s); 2 Student * bar(); In the first example, we’ve used the const keyword which prevents any changes to the structure’s values (we may omit this if we need to design a function that changes its values). We will now consider several idiomatic examples of using structure with functions. 352 | ComputerScienceOne_Page_386_Chunk1928 |
23.4. Using Structures With Functions 23.4.1. Factory Functions Properly creating and initializing structure instances can be a complex and tedious task. However, it is likely that we will need to repeat this operation over and over. We can simplify our task if we write a utility function that creates a structure instance for us. We provide the function the values we want initialized to. Such functions are sometimes referred to as factory functions as they can be used to manufacture as many instances as we want (in object-oriented programming languages, such methods are called constructors). We will need to take care that we make deep copies of any dynamically allocated elements such as strings. Shallow copies where references are shared may lead to unexpected behavior as changes to one string may affect multiple structures. 1 /** 2 * This function creates a new student structure with the 3 * given values. 4 */ 5 Student * createStudent(const char *firstName, 6 const char *lastName, 7 int id, 8 double gpa) { 9 10 Student *s = NULL; 11 s = (Student *) malloc(sizeof(Student) * 1); 12 13 //make a deep copy of the strings 14 s->firstName = (char *)malloc(sizeof(char)*(strlen(firstName)+1)); 15 strcpy(s->firstName, firstName); 16 s->lastName = (char *)malloc(sizeof(char)*(strlen(lastName)+1)); 17 strcpy(s->lastName, lastName); 18 19 s->id = id; 20 s->gpa = gpa; 21 22 return s; 23 } Another common operation is to create a copy of a given structure. We will want to again ensure that everything is a deep copy so that the two structures are not sharing references. We can easily do this by reusing the functionality we just wrote in the factory 353 | ComputerScienceOne_Page_387_Chunk1929 |
23. Structures function. 1 /** 2 * This function creates a new, deep copy of a Student 3 * structure . 4 */ 5 Student * copyStudent(const Student *s) { 6 return createStudent(s->firstName, s->lastName, s->id, s->gpa); 7 } 23.4.2. To String Functions Another common operation with structures is to output their data as a human-readable string representation. We could write a function that output a structure’s member variables to the standard output using printf() . However, it would more useful if we created a general function that returned a string representation of the structure. That way, we could decide what to do with the string: output it to the standard output, to a file, etc. Not all structure instances will require the same length string. Some students for example may have long names, while others have short. We can handle this by first calculating the length of the string necessary for whatever formatting we’ve chosen. 1 /** 2 * Returns a string representation of the given 3 * Student structure. 4 */ 5 char * studentToString(const Student *s) { 6 7 int n = strlen(s->firstName) + 8 strlen(s->lastName) + 9 8 + //id, assumed to always be at most 8 digits 10 4 + //gpa, assumed to be 0.0 - 4.0 11 19; //other formatting characters 12 13 char *str = (char *) malloc(sizeof(char) * n); 14 15 sprintf(str, "%s, %s, ID = %d (GPA = %.2f)", 16 s->lastName, s->firstName, s->id, s->gpa); 17 18 return str; 354 | ComputerScienceOne_Page_388_Chunk1930 |
23.4. Using Structures With Functions 19 } Here, we’ve utilized a variation on the familiar printf() function, sprintf() which “prints” the result not to the standard output or a file, but to a string, specified as the first argument. This function would end up returning a string similar to the following for our previous example: "Hopper, Grace, ID = 87654321 (GPA = 3.90)" 23.4.3. Passing Arrays of Structures We often also have need to pass arrays of structures to functions. As an example, consider passing an entire roster of students to a function in order to compute the average GPA. If we have an array of structures, we would have a function that looked something like the following. 1 /** 2 * Computes the average GPA of the Student structures in 3 * the given roster (which is of size n). 4 */ 5 double computeAverageGpa(const Student *roster, int n) { 6 double sum = 0.0; 7 int i; 8 for(i=0; i<n; i++) { 9 sum += roster[i].gpa; 10 } 11 return sum / n; 12 } When we pass in the array of structures, it is not passed by value. That is, the total number of bytes for each student is not copied onto the call stack. Nevertheless, as we’ve previously seen it is sometimes preferable to maintain an array of pointers to structures. If we had an array of pointers, we would have a function that looks something like the following. 1 /** 2 * Computes the average GPA of the Student structures in 3 * the given roster (which is of size n). 355 | ComputerScienceOne_Page_389_Chunk1931 |
23. Structures 4 */ 5 double computeAverageGpa(const Student **roster, int n) { 6 double sum = 0.0; 7 int i; 8 for(i=0; i<n; i++) { 9 sum += roster[i]->gpa; 10 } 11 return sum / n; 12 } The only difference here is in how we access the gpa member variable using the arrow operator instead of the dot operator. 356 | ComputerScienceOne_Page_390_Chunk1932 |
24. Recursion C supports recursion with no special syntax necessary. However, as a structured, procedural 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 functions in C. The first example of a recursive function we gave was the toy count down example. In C it could be implemented as follows. 1 void countDown(int n) { 2 if(n==0) { 3 printf("Happy New Year!\n"); 4 } else { 5 printf("%d\n", n); 6 countDown(n-1); 7 } 8 } As another example that actually does something useful, consider the following recursive summation function that takes an array, its size 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 function returns, it adds its result to the i-th element in the array. To invoke this function we would call it with an initial value of 0 for the index variable: recSum(arr, n, 0) . 1 int recSum(const int *arr, int size, int i) { 2 if(i == size) { 3 return 0; 4 } else { 5 return recSum(arr, size, i+1) + arr[i]; 6 } 7 } 357 | ComputerScienceOne_Page_391_Chunk1933 |
24. Recursion This example was not tail-recursive as the recursive call was not the final operation (the sum was the final operation). To make this function tail recursive, we can carry the summation through to each function call ensuring that the summation is done prior to the recursive function call. 1 int recSumTail(const int *arr, int size, int i, int sum) { 2 if(i == size) { 3 return sum; 4 } else { 5 return recSumTail(arr, size, i+1, sum + arr[i]); 6 } 7 } As a final example, consider the following C implementation of the naive recursive Fibonacci sequence. An additional condition has been included to check for “invalid” negative values of n for which zero is returned. 1 int fibonacci(int n) { 2 if(n < 0) { 3 return 0; 4 } else if(n <= 1) { 5 return 1; 6 } else { 7 return fibonacci(n-1) + fibonacci(n-2); 8 } 9 } C is not a language that provides implicit memoization. Instead, we need to explicitly keep track of values using a table. In the following example, the table is passed to the function as an argument. 1 int fibonacciMemoization(int n, int *table) { 2 if(n < 0) { 3 return 0; 4 } else if(n <= 1) { 5 return 1; 358 | ComputerScienceOne_Page_392_Chunk1934 |
6 } else if(table[n] > 0) { 7 return table[n]; 8 } else { 9 int a = fibonacciMemoization(n-1, table); 10 int b = fibonacciMemoization(n-2, table); 11 int result = (a + b); 12 table[n] = result; 13 return result; 14 } 15 } It is the responsibility of the calling function to ensure that the table array is large enough to accommodate all values. In this case should be at least of size (n + 1) to compute the n-th Fibonacci number. 359 | ComputerScienceOne_Page_393_Chunk1935 |
25. Searching & Sorting The standard C library provides several functions to search and sort arrays of any type of element including int , double , or even user-defined structures such as our Student example from Chapter 23. These functions are able to operate on any type of array because they take generic void * pointers. However, these functions still need a way to order the generic elements. To understand how this all works we need to understand both comparator functions and function pointers. 25.1. Comparator Functions 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. Essentially, 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 C this is achieved through a comparator function, which is a function that is responsible for comparing two elements and determining their proper order. A comparator function has the following signature and behavior: int cmp(const void *a, const void *b); • The function takes two generic void * pointers which refer to the elements being compared. • Moreover, the const keyword is used to indicate that no changes will be made to the elements. • The function 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) 361 | ComputerScienceOne_Page_395_Chunk1936 |
25. Searching & Sorting – It returns something positive, > 0 if a comes after b (that is, a > b) Note that 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. The standard string library provides a function, strcmp() that has the same basic contract: it takes two strings and returns something negative, zero or something positive depending on the lexicographic ordering of the two strings. Strictly speaking, however, strcmp() is not a comparator function. It is defined to take two const char * parameters, not const void * pointers. The C language (and thus the compiler) “knows” how to compare built-in primitive types like int and double using the built-in comparison operators. However, to generalize the comparison operation, we use void * pointers so that we can write and use general comparator functions that can be used in generic searching and sorting functions. As an example, let’s write a comparator function that orders integers in ascending order. We’ll call our function cmpInt() and use the signature above. 1 int cmpInt(const void *a, const void *b) { 2 3 } But how might we implement this function? Obviously we want to compare the values stored in the pointer variables, so we need to dereference them. However, the comparison, (*a < *b) for example is not comparing integer values. The variables a and b are void pointers, not int pointers. In general, you cannot dereference a void pointer. Dereferencing an int * or double * is possible because the compiler knows how many bytes each type takes. However, the number of bytes a void type takes is undefined. Thus, the first step is to make them int pointers by doing an explicit type cast: 1 const int *x = (const int *) a; 2 const int *y = (const int *) b; Now the variables x and y are int pointers which can be dereferenced and compared (we preserve the keyword const to ensure we do not make changes to the variables). 1 int cmpInt(const void *a, const void *b) { 2 const int *x = (const int *) a; 3 const int *y = (const int *) b; 362 | ComputerScienceOne_Page_396_Chunk1937 |
25.1. Comparator Functions 4 if(*x < *y) { 5 return -1; 6 } else if(*x == *y) { 7 return 0; 8 } else { 9 return 1; 10 } 11 } What if we wanted to order integers in the opposite order? We could write another comparator in which the comparisons or values are reversed. Even simpler, we could reuse the comparator above and “flip” the sign by multiplying by −1 (the purpose of writing functions is code reuse, after all). Even simpler, we could flip the arguments we pass to cmpInt() to reverse the order. 1 int cmpIntDesc(const void *a, const void *b) { 2 return cmpInt(b, a); 3 } The examples above illustrate the standard implementation pattern of comparator functions: 1. Make the general const void * pointers into a const pointer to the specific type you want to compare by making an explicit type cast. 2. Use the state of the type (one or more components if you are comparing structures) to determine their order. 3. Return an integer that expresses the desired order of elements. The cautious observer may be asking: what happens if I call a comparator and pass it pointers to mismatched elements? For example, what if I pass two double pointers to cmpInt() ? Obviously, the code will not work as intended (it will end up comparing the upper 32 bits of the double values, which leads to unintended behavior). A comparator function is designed with certain expectations. Namely, that a user will always pass it valid pointers to int values. If a user violates these expectations, it is their fault, not ours. This is no different from many other functions in the standard library. Passing non-null terminated strings to most string functions for example is undefined behavior. To illustrate some more examples, consider the Student structure we defined in Code 363 | ComputerScienceOne_Page_397_Chunk1938 |
25. Searching & Sorting Sample 23.1. The following code samples demonstrate various ways of ordering Student structures based on one or more of their components. 1 /** 2 * A comparator function to order Student structures by 3 * last name/first name in alphabetic order 4 */ 5 int studentByNameCmp(const void *s1, const void *s2) { 6 const Student *a = (const Student *)s1; 7 const Student *b = (const Student *)s2; 8 int result = strcmp(a->lastName, b->lastName); 9 if(result == 0) { 10 return strcmp(a->firstName, b->firstName); 11 } else { 12 return result; 13 } 14 } 1 /** 2 * A comparator function to order Student structures by 3 * last name/first name in reverse alphabetic order 4 */ 5 int studentByNameCmpDesc(const void *s1, const void *s2) { 6 return studentByNameCmp(s2, s1); 7 } 1 /** 2 * A comparator function to order Student structures by 3 * id in ascending numerical order 4 */ 5 int studentIdCmp(const void *s1, const void *s2) { 6 const Student *a = (const Student *)s1; 7 const Student *b = (const Student *)s2; 8 if(a->nuid < b->nuid) { 9 return -1; 10 } else if(a->nuid == b->nuid) { 11 return 0; 364 | ComputerScienceOne_Page_398_Chunk1939 |
25.2. Function Pointers 12 } else { 13 return 1; 14 } 15 } 1 /** 2 * A comparator function to order Student structures by 3 * GPA in descending order 4 */ 5 int studentGpaCmp(const void *s1, const void *s2) { 6 const Student *a = (const Student *)s1; 7 const Student *b = (const Student *)s2; 8 if(a->gpa > b->gpa) { 9 return -1; 10 } else if(a->gpa == b->gpa) { 11 return 0; 12 } else { 13 return 1; 14 } 15 } 25.2. Function Pointers Now that we have comparator functions to order elements, we need a way of passing a comparator to a generic search or sort function so that it can be used by that function. To achieve this in C, we use function pointers. Recall that a pointer is simply a reference to some memory location. As we’ve already seen, pointers can point to variables of simple data types such as int or double , arrays of these types or even user-defined structures. We’ve also seen that pointers can be generic using the void keyword. The malloc() function for example, returned a generic void pointer, void * , to allow it to be used to allocate memory for any type. Generic void pointers simply point to the start of a memory block, not necessarily to a memory location of any particular type of variable. As we’ve also already seen, the program code itself lives in memory (the stack). It thus makes sense that we could 365 | ComputerScienceOne_Page_399_Chunk1940 |
25. Searching & Sorting reference a memory location that, instead of containing variables, contains executable code, in particular a function. This is what a function pointer does: it points to a memory location where the code for the function is stored. To declare a function pointer, we need to specify more information than a typical int * or double * pointer. Since it points to a function, we need to specify the function’s signature: its return type and parameter list. Consider the following example: int (*ptrToFunc)(int, double, char) = NULL; In this declaration, we’ve created a function pointer named ptrToFunc . This pointer is capable of pointing to any function whose return type is int (indicated by the first keyword) and which takes three parameters: an int , a double and a char . The assignment operation has initialized this pointer to NULL . Consider another example: let’s declare a function pointer that is capable of pointing to the math library’s sqrt() function. The sqrt() function returns a double and takes a single double parameter. Adapting the syntax above, we would create this pointer as follows. double (*ptrToSqrt)(double) = NULL; Again, we have initialized it to NULL ; it does not yet reference the sqrt() function. To make it reference this function, we need to assign it a value. Recall that to get the memory location of a regular variable, say int x; , we use the referencing operator, &x . Similarly, with functions we can use the referencing function, in this case &sqrt to get the memory address of the sqrt() function, however this is not necessary. Similar to arrays, the identifier (name) of a function serves as its memory address! The identifier sqrt itself is the memory location of the function. Thus to assign ptrToSqrt to point to sqrt() , we simply need to do the following: ptrToSqrt = sqrt; Note the difference: usually we invoke sqrt() by writing parentheses and providing an argument. When referencing the function itself, we omit the parentheses. Additional examples of this syntax can be found in Code Sample 25.1. Callbacks The main use for function pointers is so that references to functions can be passed as parameters to other functions. The passed function is known as a callback. This gives us the ability to write a more abstract and generic function. For example, in GUI programming, we frequently need to associate a particular function with a particular 366 | ComputerScienceOne_Page_400_Chunk1941 |
25.2. Function Pointers event. Suppose we create a button; we need to be able to specify what happens when that button gets clicked. We do so by providing a function as a callback to a registration function that associates the “click” event with the provided function. Thus, whenever a user clicks the button, the callback is invoked (“called back”). Let’s illustrate some syntax usage with another example. Suppose we want to create a getMax() function. We could write one function for arrays of integers, another for arrays of double s, another for Student arrays that gets the student with the maximum GPA, then another for the ID, then another for the name and so on. Or, we could program a generic getMax() function that could be used for any type by taking a comparator function as a callback. To illustrate, consider the following non-generic function for integers. 1 int getMax(const int *arr, int n) { 2 int i, maxIndex = 0; 3 for(i=1; i<n; i++) { 4 if(arr[maxIndex} < arr[i] { 5 //we've found something larger, update the maxIndex: 6 maxIndex = i; 7 } 8 } 9 return maxIndex; 10 } This simple function iterates through the array, keeping track of the maximum value found “so far” and updating it when it finds something larger. Because we’ve specified that arr is an array if int values, we can use the less-than comparison operator (line 4). Now let’s make it more generic: rather than taking an array of int values, it will now take a generic void array. Further, we will pass a function pointer to this function that references a generic comparator function that can be used to replace the less-than comparison operator. 1 int getMax(const void *arr, int n, 2 int(*cmp)(const void *, const void *)) { 3 int i, maxIndex = 0; 4 for(i=1; i<n; i++) { 5 ... 6 } 7 return maxIndex; 8 } 367 | ComputerScienceOne_Page_401_Chunk1942 |
25. Searching & Sorting There are a couple of issues here that we have to deal with. When working with generic void * pointers in C and using arrays, you cannot simply index using the usual 0, 1, 2, etc. indices. Recall that when elements are stored in an array, the index represents an offset of a memory address. If the array is an array of integers or double or some other built-in type, the compiler knows how large each one is and is able to compute the appropriate offset given the usual 0, 1, 2, etc. indices. However, when dealing with void * elements, a function must be told how many bytes each element takes. C uses an unsigned integer type, size_t to indicate a size in bytes, so we’ll use it as well. We modify the function signature above to pass in a size_t size parameter. We now need a way to access each element in the array. The array itself is generic. We cannot simply use indices such as arr[i] to access elements. Since it is a void * pointer, we cannot simply dereference it using an index. The compiler doesn’t know how many bytes each element takes, so it cannot compute an offset using the index variable i . Instead, we need to do the pointer arithmetic ourselves. We could use the size parameter, say arr[i*size] to compute the offset of the i-th element, but this still dereferences a void pointer, which we generally do not want to do. Instead, we can use the pointer arr and do some simple arithmetic; arr is the starting memory location, so if we simply add i*size to it, that gives us the memory location of the i-th element as a void pointer! 1 void *first = arr + 0 * size; //first element 2 void *second = arr + 1 * size; //second element 3 void *third = arr + 2 * size; //third element 4 ... 5 void *x = arr + i * size; //i-th element We can use this in our getMax() function to iterate over each element in the array and pass it to our comparator. The comparator expects generic void pointers, and that is what our pointer arithmetic is computing. Passing two memory addresses to the comparator determines which is the larger of two elements in the array. To do this, we call the comparator on the maximum element we’ve found so far and the i-th element in the loop. If it returns something negative, then we know that the “max” element is less than the i-th element and so update our maxIndex variable. Making these changes results in the this final version. 368 | ComputerScienceOne_Page_402_Chunk1943 |
25.2. Function Pointers 1 int getMax(const void *arr, int n, size_t size, 2 int(*cmp)(const void *, const void *)) { 3 int i, maxIndex = 0; 4 for(i=1; i<n; i++) { 5 if(cmp(arr + maxIndex * size, arr + i * size) < 0) { 6 //we've found something larger, update the max_index: 7 maxIndex = i; 8 } 9 } 10 return maxIndex; 11 } Suppose we have an array of integers and the cmpInt() comparator function above. We can use our getMax() function as follows. 1 int arr[] = {8, 2, 9, 10, 4, 2, 2, 5, 6, 7}; 2 int maxIndex = getMax(arr, 10, sizeof(int), cmpInt); 3 printf("maximum value: %d\n", arr[maxIndex]); In this example, the getMax() function would return the index 3 and print the maximum value stored there, 10. The getMax() function returns the index corresponding to the “maximum” element according to the comparator used. If instead we had used cmpIntDesc() the “maximum” element would have been the least element, (2 in the example above) because it would have been the element ordered “last” by the descending comparator. Consider another example with our Student structure. 1 int n = 10; 2 Student *roster = (Student *) malloc(sizeof(Student) * n); 3 ... 4 int maxIndex = getMax(roster, n, sizeof(Student), studentByNameCmp); Since studentByNameCmp() orders by lexicographic ordering, a student with the last name “Zadora” would have been “larger” than someone with a last name “Anderson.” 369 | ComputerScienceOne_Page_403_Chunk1944 |
25. Searching & Sorting Thus the code above will return an index corresponding to the last student in lexicographic ordering of their name. Similarly, if we had used the studentGpaCmp() comparator instead, getMax() would have returned an index for the student with the lowest GPA as this comparator ordered highest to lowest. Another variation on this function would be to return a pointer to the maximum element rather than an index. The same logic would have applied, but the return type would be a void * pointer and the return statement would return the memory address of the maximum element instead. To avoid warnings, in the final return statement we cast arr as a void pointer (instead of a const void pointer) to make the return value compatible with the return type. 1 void * getMax(const void *arr, int n, size_t size, 2 int(*cmp)(const void *, const void *)) { 3 int i, maxIndex = 0; 4 for(i=1; i<n; i++) { 5 if(cmp(arr + maxIndex * size, arr + i * size) < 0) { 6 //we've found something larger, update the max_index: 7 maxIndex = i; 8 } 9 } 10 return (void *)arr + maxIndex * size; 11 } 370 | ComputerScienceOne_Page_404_Chunk1945 |
25.2. Function Pointers 1 #include <stdio.h> 2 #include <stdlib.h> 3 4 int function01(int a, double b); 5 void function02(double x, char y); 6 7 void runAFunction(int (*theFunc)(int, double)); 8 9 int main(int argc, char **arg) { 10 11 int i = 5; 12 double d = 3.14; 13 char c = 'Q'; 14 15 //calling a function normally... 16 int j = function01(i, d); 17 function02(d, c); 18 19 //function pointer declaration 20 int (*pt2Func01)(int, double) = NULL; 21 void (*pt2Func02)(double, char) = NULL; 22 23 //assignment 24 pt2Func01 = function01; 25 //or: 26 pt2Func01 = &function01; 27 pt2Func02 = &function02; 28 29 //you can invoke a function using a pointer to it: 30 j = pt2Func01(i, d); 31 pt2Func02(d, c); 32 33 //alternatively, you can invoke a function by dereferencing it: 34 j = (*pt2Func01)(i, d); 35 (*pt2Func02)(d, c); 36 37 //With function pointers, you can now pass entire functions as arguments to another function! 38 printf("Calling runAFunction...\n"); 39 runAFunction(pt2Func01); 40 //we should not pass in the second pointer as it would not match the signature: 41 //syntactically okay, compiler warning, undefined behavior 42 //runAFunction(pt2Func02); 43 } 44 45 void runAFunction(int (*theFunc)(int, double)) { 46 47 printf("calling within runAfunction...\n"); 48 int result = theFunc(20, .5); 49 printf("the result was %d\n", result); 50 51 return; 52 } 53 54 int function01(int a, double b) { 55 printf("You called function01 on a = %d, b = %f\n", a, b); 56 return a + 10; 57 } 58 59 void function02(double x, char y) { 60 61 printf("You called function02 on x = %f, y = %c\n", x, y); 62 63 } Code Sample 25.1.: C Function Pointer Syntax Examples 371 | ComputerScienceOne_Page_405_Chunk1946 |
25. Searching & Sorting 25.3. Searching & Sorting We now turn our attention to the search and sorting functions provided by the standard library. Each function is a generic implementation that takes advantage of function pointers and comparator functions. 25.3.1. Searching Linear Search The C search library, search.h provides a linear search function to search arrays, named lfind() (linear find). This function does not require that the array be sorted and performs a linear search algorithm, returning a pointer to the first element such that the comparator returns 0 (indicating equality). The full signature of the function is as follows. 1 void *lfind(const void *key, 2 const void *base, 3 size_t *nmemb, 4 size_t size, 5 int(*compar)(const void *, const void *)); Each argument represents: • key – a “dummy” structure instance matching the element you are searching for. For example, if you are searching for a Student with the last name "Smith" then you can construct an instance with the same last name, ignoring the value of all other components. • base – a pointer to the array to be searched • nmemb – the size of the array (number of “members”) • size – the size, in bytes, of each element in the array (generally you use use sizeof() to determine this) • compar – a pointer to a comparator function to use in the search. As with our getMax() example, lfind() returns a pointer to the element it finds. If no such element is found, this function will return NULL . 372 | ComputerScienceOne_Page_406_Chunk1947 |
25.3. Searching & Sorting In the same library, there is another linear search function: 1 void *lsearch(const void *key, 2 void *base, 3 size_t *nmemb, 4 size_t size, 5 int(*compar)(const void *, const void *)); It differs in that if it does not find a matching element, it still returns NULL but also attempts to insert the element being searched for at the end of the array. The function will assume there is enough room at the end of the array to accommodate the inserted element (if not, the behavior is undefined). This behavior is hinted at by the fact that base is not const . Moreover, nmemb is passed by reference. If the function inserts the element, it will also increment nmemb variable to reflect this new element. It is your responsibility to ensure that there is enough valid memory to accommodate any inserts when using lsearch() . Binary Search In the standard library ( stdlib.h ) there is an additional binary search function that can be used to more efficiently search a sorted array. The prototype: 1 void *bsearch(const void *key, 2 const void *base, 3 size_t nmemb, 4 size_t size, 5 int (*compar)(const void *, const void *)); All parameters are exactly as with lfind() as is the behavior: it returns a pointer to the first element that it finds (though first does not necessarily mean the first in the order of the array) and NULL if no matching element is found. It is an essential requirement that the array be sorted with the same comparator as was used to sort the array or NULL may be returned erroneously. 373 | ComputerScienceOne_Page_407_Chunk1948 |
25. Searching & Sorting 25.3.2. Sorting The standard library also provides a generic sorting function, qsort() . Though the name suggests a Quick Sort implementation, it does not necessarily have to be (it was when the function was originally designed). Modern implementations of qsort() may implement alternatives such as Merge Sort or non-recursive hybrid Quick Sort algorithms. The prototype and parameters are similar to the search functions but do not include a key. The array is also not const indicating that it will be changed (which is the whole point of calling the function). The function will sort elements in ascending order according to the provided comparator function. 1 void qsort(void *base, 2 size_t nmemb, 3 size_t size, 4 int(*compar)(const void *, const void *)) • base – pointer an array of elements • nmemb – the size of the array (number of members) • size – the size (in bytes) of each element (use sizeof() ) • compar – a comparator function used to order elements The advantages to using qsort() (as well as lfind() and bsearch() ) should be clear. There is no need to write a new function that reimplements the same algorithm for every possible ordering of every possible user-defined structure. We need only to create a comparator function and pass it to qsort() . There is less code, and less chance of bugs. The qsort() function is well-designed, optimized, and most importantly well-tested and proven. These functions represent a sort of “weak” form of polymorphic behavior found in more modern object-oriented programming languages and other languages that support “generic programming.” Polymorphism is the characteristic that the same code can be executed on different types, greatly reducing the need for duplicate code. 25.3.3. Examples We illustrate the usage of these functions in Code Samples 25.2 and 25.3. 374 | ComputerScienceOne_Page_408_Chunk1949 |
25.3. Searching & Sorting 1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <search.h> 4 5 #include "student.h" 6 7 int main(int argc, char **argv) { 8 9 int n = 0; 10 Student *roster = loadStudents("student.data", &n); 11 int i; 12 size_t numElems = n; 13 14 15 printf("Roster: \n"); 16 printStudents(roster, n); 17 18 /* Searching */ 19 Student *castro = NULL; 20 Student *castroKey = NULL; 21 Student *sandberg = NULL; 22 char *str = NULL; 23 24 castro = linearSearchStudentByNuid(roster, 10, 131313); 25 str = studentToString(castro); 26 printf("castro: %s\n", str); 27 free(str); 28 29 //create a key that will match according to the NUID 30 int nuid = 23232323; 31 Student * key = createEmptyStudent(); 32 key->nuid = nuid; 33 34 //use lfind to find the first such instance: 35 //sandberg = 36 sandberg = lfind(key, roster, &numElems, sizeof(Student), studentIdCmp); 37 str = studentToString(sandberg); 38 printf("sandberg: %s\n", str); 39 free(str); 40 41 //create a key with only the necessary fields 42 castroKey = createStudent("Starlin", "Castro", 0, 0.0); 43 //sort according to a comparator function 44 qsort(roster, n, sizeof(Student), studentLastNameCmp); 45 46 castro = bsearch(castroKey, roster, n, sizeof(Student), studentLastNameCmp); 47 str = studentToString(castro); 48 printf("castro (via binary search): %s\n", str); 49 free(str); 50 51 //create a key with only the necessary fields 52 castroKey = createStudent(NULL, NULL, 131313, 0.0); 53 //sort according to a comparator function 54 qsort(roster, n, sizeof(Student), studentIdCmp); 55 56 castro = bsearch(castroKey, roster, n, sizeof(Student), studentIdCmp); 57 str = studentToString(castro); 58 printf("castro (via binary search): %s\n", str); 59 free(str); 60 61 return 0; 62 } . Code Sample 25.2.: C Search Examples 375 | ComputerScienceOne_Page_409_Chunk1950 |
25. Searching & Sorting 1 #include <stdio.h> 2 #include <stdlib.h> 3 4 #include "student.h" 5 6 7 int main(int argc, char **argv) { 8 9 int n = 0; 10 Student *roster = loadStudents("student.data", &n); 11 int i; 12 size_t numElems = n; 13 14 printf("Roster: \n"); 15 printStudents(roster, n); 16 17 printf("\n\n\nSorted by last name/first name: \n"); 18 qsort(roster, numElems, sizeof(Student), studentLastNameCmp); 19 printStudents(roster, n); 20 21 printf("\n\n\nSorted by ID: \n"); 22 qsort(roster, numElems, sizeof(Student), studentIdCmp); 23 printStudents(roster, n); 24 25 printf("\n\n\nSorted by ID, descending: \n"); 26 qsort(roster, numElems, sizeof(Student), studentIdCmpDesc); 27 printStudents(roster, n); 28 29 printf("\n\n\nSorted by GPA: \n"); 30 qsort(roster, numElems, sizeof(Student), studentGPACmp); 31 printStudents(roster, n); 32 33 return 0; 34 } . Code Sample 25.3.: C Sort Examples 376 | ComputerScienceOne_Page_410_Chunk1951 |
25.4. Other Considerations 25.4. Other Considerations 25.4.1. Sorting Pointers to Elements Recall that it is sometimes preferable to maintain an array of pointers to structures rather than an array of structures. Sorting is a scenario where this is particularly true. When sorting an array of structure elements, the entire structure is copied back and forth as elements are swapped. Depending on the number of bytes of a structure, this can be quite expensive. It is generally more efficient to sort an array of pointers to structures instead. A prime example of this is sorting an array of strings. An array of strings can be thought of as a 2-dimensional array of char s. Specifically, an array of strings is a char ** type. That is, an array of pointers to pointers of char s. We may be tempted to use strcmp() in the standard string library, passing it to qsort() . Unfortunately this will not work. qsort() requires two const void * types, while strcmp() takes two const char * types. This difference is subtle but important.1 The recommended way of doing this is to define a different comparator function as in Code Sample 25.4. 1 /* compare strings via pointers */ 2 int pstrcmp(const void *p1, const void *p2) 3 { 4 return strcmp(*(char * const *)p1, *(char * const *)p2); 5 } Code Sample 25.4.: C Comparator Function for Strings Observe the behavior of this function: it uses the standard strcmp() function, but makes the proper explicit type casting before doing so. The *(char * const *) casts the generic void pointers as pointers to strings (or pointers to pointers to characters), then dereferences it to be compatible with strcmp() . Another case is when we wish to sort user-defined structures. The Student structure presented earlier is “small” in that it only has a few fields. When structures are stored in an array and sorted, there may be many swaps of individual elements which involves a lot of memory copying. If the structures are small this is not too bad, but for “larger” structures this could be potentially expensive. Instead, it may be preferred to have an array of pointers to structures. Swapping elements involves only swapping pointers 1A full discussion can be found on the c-faq, http://c-faq.com/lib/qsort1.html. 377 | ComputerScienceOne_Page_411_Chunk1952 |
25. Searching & Sorting instead of the entire structure. This is far cheaper as a memory address is likely to be far smaller than the actual structure it points to. This is essentially equivalent to the string scenario: we have an array of pointers to be sorted, our comparator function then needs to deal with pointers to pointers.2 An example appears in Code Sample 25.5. 1 /** 2 * Orders two Student pointers according to the last name/first name 3 */ 4 int studentPtrLastNameCmp(const void *s1, const void *s2) { 5 //we receive a pointer to an individual element in the array 6 //but individual elements are POINTERS to students thus we cast 7 //them as (const Student **) then dereference to get a pointer 8 //to a Student! 9 const Student *a = *(const Student **)s1; 10 const Student *b = *(const Student **)s2; 11 int result = strcmp(a->lastName, b->lastName); 12 if(result == 0) { 13 return strcmp(a->firstName, b->firstName); 14 } else { 15 return result; 16 } 17 } 18 19 20 21 Student **roster = (Student **) malloc(sizeof(Student *) * n); 22 ... 23 qsort(roster, n, sizeof(Student *), studentPtrLastNameCmp); Code Sample 25.5.: Sorting Structures via Pointers Another issue when sorting arrays of pointers is that we may now have to deal with NULL elements. When sorting arrays of elements this is not an issue as a properly initialized array will contain non-null elements (though elements could still be uninitialized, the memory space will be valid). How we handle NULL pointers is more of a design decision. We could ignore it and any attempt to access a NULL structure will result in undefined behavior (or segmentation faults, etc.). Or we could give NULL values an explicit ordering with respect to other 2Again, a full discussion can be found on c-faq, http://c-faq.com/lib/qsort2.html. 378 | ComputerScienceOne_Page_412_Chunk1953 |
25.4. Other Considerations elements. That is, we could order all NULL pointers before non- NULL elements (and consider all NULL pointers to be equal). An example with respect to our Student structure is given in Code Snippet 25.6. 1 int studentPtrLastNameCmpWithNulls(const void *s1, const void *s2) { 2 const Student *a = *(const Student **)s1; 3 const Student *b = *(const Student **)s2; 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 } 11 int result = strcmp(a->lastName, b->lastName); 12 if(result == 0) { 13 return strcmp(a->firstName, b->firstName); 14 } else { 15 return result; 16 } 17 } Code Sample 25.6.: Handling Null Values 379 | ComputerScienceOne_Page_413_Chunk1954 |
Part II. The Java Programming Language 381 | ComputerScienceOne_Page_415_Chunk1955 |
26. Basics The Java programming language was developed in the early 1990s at Sun Microsystems by James Gosling, Mike Sheridan, and Patrick Naughton. Its original intention was to enable cable box sets to be more interactive. By the mid-90s, Java was retargeted toward the WWW. The first public release came on May 23, 1995 with the first Java Development Kit (JDK), Java 1.0 on January 23rd, 1996. A new, updated release has come about every other year. As of 2014, Java 8 is the current stable version. Today, Java is one of the most popular programming languages, consistently ranked as one of the top 2 languages (see http://www.tiobe.com). It is now owned and maintained by Oracle, but there are many open source tools, compilers and runtime environments available. Java is used in everything from mobile devices (Android) and desktop applications to enterprise application servers. From its inception, Java was designed with 5 basic principles: 1. Simple, Object-oriented, familiar 2. Robust and secure 3. Architecture-neutral and portable 4. High performance 5. Interpreted, threaded and dynamic Java offers many key features that have made it popular. It is unique in that it is not entirely compiled nor interpreted. Instead, Java source code is compiled into an intermediate form, called Java bytecode. This bytecode is not directly runnable on a processor. Instead, a JVM, an application that was written and compiled for a particular system, interprets the bytecode and runs the application. This added layer of abstraction means that Java source code can be written once (and compiled once) and then run anywhere on any device that has a JVM. The added layer of abstraction makes development easier, but comes at a cost in performance. However, the most recent JVMs have offered performance that is comparable to native machine code in many applications. Another key feature is that Java has its own automated garbage collection. Some languages require manual memory management, meaning that requesting, managing, 383 | ComputerScienceOne_Page_417_Chunk1956 |
26. Basics 1 package unl.cse; //package declaration 2 3 //imports would go here 4 5 /** 6 * A basic hello world program in Java 7 */ 8 public class HelloWorld { 9 10 //static main method 11 public static void main(String args[]) { 12 System.out.println("Hello World!"); 13 } 14 15 } Code Sample 26.1.: Hello World Program in Java and freeing memory is part of the code that you write as a developer. Failure to handle memory management properly can lead to wasted resources (memory leaks), poor or unstable performance, and even more serious security issues (buffer overflows). In Java, there is no manual memory management. The JVM handles the allocation and clean up of memory automatically. In following with the five design principles, Java is similar in syntax to C (called “C-style syntax”). Executable statements are terminated by semicolons, code blocks are defined by opening/closing curly brackets, etc. Java is also fundamentally a class-based OOP language. With the exception of a few primitive types, in Java everything is a class or belongs to an class. 26.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 out 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, compiler, runtime environment, etc. are functioning properly with a minimal example. A basic Hello World! program in Java can be found in Code Sample 26.1. 384 | ComputerScienceOne_Page_418_Chunk1957 |
26.2. Basic Elements We will not focus on any particular development environment, code editor, or any particular operating system, compiler, or ancillary standards in our presentation. However, as a first step, you should be able to write, compile, 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 JDK and IDE. Eclipse (http://eclipse.org/) is the industry standard, though IntelliJ (https://www.jetbrains.com/idea/) and NetBeans (https://netbeans.org/) are also popular. 26.2. Basic Elements Using the Hello World! program as a starting point, we will now examine the basic elements of the Java language. 26.2.1. Basic Syntax Rules Java’s syntax is adopted from C, referred to as “C-style syntax.” These elements include the following. • Java is a statically typed language so variables must be declared along with their types before using them. • Strings are delimited with double quotes. Single characters, including special escaped characters are delimited by single quotes; "this is a string" , and these are characters: 'A' , '4' , '$' and '\n' • In addition, Java uses Unicode (UTF-16 encoding) to represent characters. This is fully back-compatible with ASCII, but also allows you to specify Unicode characters using special escape sequences and hexadecimal encodings. For example, '\u4FFA' represents a Japanese character: The string "\u4FFA\u306F\u6700\u9AD8\u3060\u305C\uFF01" represents the phrase • Executable statements are terminated by a semicolon, ; • Code blocks are defined using opening and closing curly brackets, { ... } . More- over, code blocks can be nested: code blocks can be defined within other code 385 | ComputerScienceOne_Page_419_Chunk1958 |
26. Basics blocks. • Variables are scoped to the code block in which they are declared and are only valid within that code block. • In general, whitespace between coding elements is ignored. 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. 26.2.2. Program Structure Classes In Java, everything is a class or belongs to a class. A class is an extensible program or blueprint for creating objects. Objects are an integral part of OOP that we’ll explore later. However, to start out our programs will be simple enough that they can be contained in a single class. To declare a class, you use the following syntax. public class HelloWorld { ... } where the contents of the class are placed between the opening/closing curly brackets. In addition, a class must be placed in a Java source file with the same name. In our previous example, the class must be in a file named HelloWorld.java . When naming classes, the most commonly accepted naming convention is to use uppercase camel casing (also called PascalCase) in which each word in the name is capitalized including the first, Employee , SavingsAccount , ImageFile , etc. Class names (as well as their source file names) are case sensitive. Packages Java code is organized into modules called packages. Packages are essentially directories (or folders) which follow a directory tree structure which allows subdirectories and separate directories at the same level. It all starts at the root directory called the “default” package. Within a source file, we declare which package the file belongs to using the keyword package followed by a fully qualified package declaration which is essentially just the 386 | ComputerScienceOne_Page_420_Chunk1959 |
26.2. Basic Elements names of the directories that the file is located in, separated by a period. The declaration is terminated by a semicolon. For example, the package declaration, package unl.cse; would indicate that the file belongs in the directory cse which is a subdirectory of the directory unl . The absence of a package declaration will mean that the file is associated with the default directory. Packages allow you to organize source files and code functionality. Mathematics related classes can be placed in one package while image related classes can be placed in another, etc. It also provides separate name spaces for classes. There could be 3 or 4 different classes named List for example. They could not be located in the same directory; if you wanted to use one which one would you be referring to? By separating them into packages, they can all exist without conflict. When we want to use a particular one, we import that class with its fully qualified package name. Imports An import statement essentially “brings in” another class so that its methods and functionality can be used. For example, there is a class named Scanner (located in the package java.util ) that makes it easy to read input from the standard input. To include it in our program so that we can use its functionality, we would need1 to import it: import java.util.Scanner; Classes in the package java.lang (such as String and Math ) are considered standard and are imported by default without an explicit import statement. You may see some code that uses a wildcard like import java.util.*; which ends up importing every class in that package. This is generally considered bad practice. In general, code should be intentional and specific, importing every class even if they are not used goes against this principle. When naming packages, you must follow the general naming rules for identifiers (see below). Package names cannot begin with a number, no whitespace, etc. Moreover, the general con- vention for package names is to use lowercase underscore casing, here_is_an_example . Moreover, packages and subpackages follow the same convention as directories: the top most directory is the most general and subdirectories are more and more specific. In many of our examples we’ll use unl.cse (UNL, University of Nebraska–Lincoln; CSE, 1You can still use it without importing it, but you’d need to use a fully qualified path name at declaration/instantiation. 387 | ComputerScienceOne_Page_421_Chunk1960 |
26. Basics Function Description Math.abs(x) Absolute value function, |x|a Math.ceil(x) Ceiling function, ⌈46.3⌉= 47.0 Math.floor(x) Floor function, ⌊46.3⌋= 46.0 Math.cos(x) Cosine functionb Math.sin(x) Sine functionb Math.tan(x) Tangent functionb Math.exp(x) Exponential function, ex, e = 2.71828 . . . Math.log(x) Natural logarithm, ln (x)c Math.log10(x) Logarithm base 10, log10 (x)c Math.pow(x,y) The power function, computes xy Math.sqrt(x) Square root functionc Table 26.1.: Several methods defined in the Java Math library. aThere are several versions of the absolute value method, one for each numeric type but all with the same name. ball trigonometric functions assume input is in radians, not degrees. cInput is assumed to be positive, x > 0. Department of Computer Science & Engineering) which illustrates this general-to-specific organization. There are many other important classes and packages provided by the standard JDK that we’ll examine as needed. Of immediate interest is the Math class and its library of common mathematical functions such as the square root and the natural logarithm. Table 26.1 highlights several of these functions. To use them you’d need to invoke them by using the class name and dot operator. For example: 1 double x = 1.5; 2 double y, z; 3 y = Math.sqrt(x); //y now has the value √x = √ 1.5 4 z = Math.sin(x); //z now has the value sin (x) = sin (1.5) In both of the method 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. 388 | ComputerScienceOne_Page_422_Chunk1961 |
26.2. Basic Elements 26.2.3. The main() Method Every executable program has to have a beginning: a point at which the program starts to execute. In Java, a class may contain many variables and methods, but a class is only executable if it contains a main() method. When a Java class is compiled and the JVM is started, the JVM loads the class into memory and starts executing code contained in the main() method. In addition, our main() method takes an array of String types which serve to communicate any command line arguments provided to the program (review Section 2.4.4 for details). The array, args stores the arguments as strings. The number of arguments provided can be determined using the length property of the array. Specifically, args.length is an integer indicating how many arguments were provided. This does not include the name of the program (class) itself as that is already be known to the programmer. To access any one argument, it will be necessary to index the array. The index for the first argument is zero, thus the first argument is args[0] , the second is args[1] , etc. The last one would be at args[args.length-1] . If a user is expected to provide numbers as input, they’ll need to be converted as the args array are only String types. To convert the arguments you can use parsing methods provided by the Integer and Double classes. An example: 1 //converts the "first" command line argument to an integer 2 int x = Integer.parseInt(args[0]); 3 //converts the "third" command line argument to a double: 4 double y = Double.parseDouble(args[1]); 26.2.4. Comments Comments can be written in a Java program 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 slashes is ignored. With a multiline comment, everything in between the forward slash/asterisk is ignored. Comments are ultimately ignored so the amount of comments do not have an effect on the final executable code. Consider the following example. 389 | ComputerScienceOne_Page_423_Chunk1962 |
26. Basics 1 //this is a single line comment 2 int x; //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 double y; 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 compiler error but with color-coded comments its easy to see the mistake visually. Another common comment style convention is the Javadoc (Java Documentation) style of comments. Javadoc style comments are multiline comments that begin with /** . The Javadoc framework allows you to markup your comments with tags and links so that documentation can be automatically generated and published. We will sometimes use this style, but we will not cover the details. 26.3. Variables Java has 8 built-in primitive types supporting numbers (integers and floating point numbers), Booleans, and characters. Table 26.2 contains a complete description of these types. Each of these primitive types also has a corresponding wrapper class defined in the java.lang package. Wrapper classes provide object versions of each of these classes. The object versions have many utility methods that can be used in relation to their type. For example, the aforementioned Integer.parseInt() method is part of the Integer wrapper class. The wrapper classes, however, are different. These are objects, so when a reference is declared for them, by default, that reference refers to null . The keyword null is used to indicate a special memory address that represents “nothing.” In fact, the default value for any object type is null . Care must be taken when mixing primitive types and their wrapper classes (see below) as null references may result in a NullPointerException . Finally, instances of the wrapper classes are immutable. Once they are created, they cannot be changed. References can be made to refer to a different object, but the object’s value cannot be changed. 390 | ComputerScienceOne_Page_424_Chunk1963 |
26.3. Variables Type Description Wrapper Class byte 8-bit signed 2s complement integer Byte short 16-bit signed 2s complement integer Short int 32-bit signed 2s complement integer Integer long 64-bit signed 2s complement integer Long float 32-bit IEEE 754 floating point number Float double 64-bit floating point number Double boolean may be set to true or false Boolean char 16-bit Unicode (UTF-16) character Character Table 26.2.: Primitive types in Java 26.3.1. Declaration & Assignment Java is a statically typed language meaning that all variables must be declared before you can use them or refer to them. In addition, when declaring a variable, you must specify both its type and its identifier. For example: 1 int numUnits; 2 double costPerUnit; 3 char firstInitial; 4 boolean isStudent; Each declaration specifies the variable’s type followed by the identifier and ending with a semicolon. The identifier rules are fairly standard: a name can consist of lowercase and uppercase alphabetic characters, numbers, and underscores but may not begin with a numeric character. We adopt the modern camelCasing naming convention for variables in our code. In general, variables must be assigned a value before you can use them in an expression. You do not have to immediately assign a value when you declare them (though it is good practice), but some value must be assigned before they can be used or the compiler will issue an error.2 The assignment operator is a single equal sign, = and is a right-to-left assignment. That is, 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. Using our variables from before, we can assign them values: 2Instance variables, that is variables declared as part of an object do have default values. For objects, the default is null , for all numeric types, zero is the default value. For the boolean type, false is the default, and the default char value is \0 , the null-terminating character (zero in the ASCII table). 391 | ComputerScienceOne_Page_425_Chunk1964 |
26. Basics 1 numUnits = 42; 2 costPerUnit = 32.79; 3 firstInitial = 'C'; 4 isStudent = true; For brevity, Java allows you to declare a variable and immediately assign it a value on the same line. So these two code blocks could have been more compactly written as: 1 int numUnits = 42; 2 double costPerUnit = 32.79; 3 char firstInitial = 'C'; 4 boolean isStudent = true; As another shorthand, we can declare multiple variables on the same line by delimiting them with a comma. However, they must be of the same type. We can also use an assignment with them. 1 int numOrders, numUnits = 42, numCustomers = 10, numItems; 2 double costPerUnit = 32.79, salesTaxRate; Another useful keyword is final . Though it has several uses, when applied to a variable declaration, it makes it a read-only variable. After a value has been assigned to a final variable, its value cannot be changed. 1 final int secret = 42; 2 final double salesTaxRate = 0.075; Any attempt to reassign the values of final variables will result in a compiler error. 392 | ComputerScienceOne_Page_426_Chunk1965 |
26.4. Operators 26.4. Operators Java supports the standard arithmetic operators for addition, subtraction, multiplication, and division using + , - , * , and / respectively. Each of these operators is a binary operator that acts on two operands which can either be literals or other variables and follow the usual rules of arithmetic when it comes to order of precedence (multiplication and division before addition and subtraction). 1 int a = 10, b = 20, c = 30, d; 2 d = a + 5; 3 d = a + b; 4 d = a - b; 5 d = a + b * c; 6 d = a * b; 7 d = a / b; //integer division and truncation! See below 8 9 double x = 1.5, y = 3.4, z = 10.5, w; 10 w = x + 5.0; 11 w = x + y; 12 w = x - y; 13 w = x + y * z; 14 w = x * y; 15 w = x / y; 16 17 //you can do arithmetic with both types: 18 w = a + x; 19 20 //however you CANNOT assign a double to an integer: 21 d = b + y; //compilation error 22 //but you can do so with an explicit type cast: 23 d = (int) (b + y); //though truncation occurs, d is 23 In addition, you can mix the wrapper classes with their primitive types. You must be careful though. The wrapper classes are object references which can be null . If a null reference is used in an arithmetic expression, it will result in a NullPointerException which can be caught and handled (see Chapter 30). If not caught, it will end up being a fatal error. Some examples: 1 int a = 10, c; 2 Integer b = 20; 393 | ComputerScienceOne_Page_427_Chunk1966 |
26. Basics 3 4 //int and Integer can be mixed: 5 c = a + b; 6 7 double x = 3.14, z; 8 Double y = 2.71; 9 //double and Double can be mixed: 10 z = x + y; 11 12 //all types can be mixed: 13 double u = a + x + b + y; 14 15 //Be careful: 16 Integer d = null; 17 c = a + d; //NullPointerException This works because of a mechanism called autoboxing (or autounboxing in this case). The wrapper class is acting like a “box”: it is an object that stores the value of a primitive type. When it gets used in an arithmetic expression, it gets “unboxed” and converted to a primitive type so that the arithmetic operation is performed on compatible primitive types. This is all done by the compiler and is completely transparent to us. However, that is the reason that we may get a NullPointerExcpetion . Our code actually gets converted from c = a + d; to c = a +d.doubleValue(); . The doubleValue() method returns a double primitive value. However, if d is null , you can’t call a method on it; thus the NullPointerException is thrown as a consequence. Special care must be taken when dealing with int types. For all four operators, if both operands are integers, the result will be an integer. For addition, subtraction, and multiplication this isn’t an issue, but for division it means that when we divide, say (10 / 20) , the result is not 0.5 as expected. The number 0.5 is a floating point number. As such, the fractional part gets truncated (cut offand thrown out) leaving only zero. In the code above, d = a / b; the variable d ends up getting the value zero because of this. A solution to this problem is to use explicit type casting to force at least one of the operands in an integer division to become a double type. For example: 1 int a = 10, b = 20; 2 double x; 3 4 x = (double) a / b; 394 | ComputerScienceOne_Page_428_Chunk1967 |
26.5. Basic I/O Assigning a floating point number to an integer is not allowed in Java and attempting to do so will be treated as a compiler error. This is because Java does not support implicit type casts. However, you can do so if you provide an explicit type cast as in the code above, d = (int) (b + y); In this code, b + y is correctly computed as 20 + 3.4 = 23.4, but the explicit type cast (down to an integer) results in truncation. The .4 gets cutoffand d gets the value 23. Assigning an int value to a double variable is not a problem as the integer 2 becomes the floating point number 2.0. Java also supports the integer remainder operator using the % symbol. This operator gives the remainder of the result of dividing two integers. Examples: 1 int x; 2 3 x = 10 % 5; //x is 0 4 x = 10 % 3; //x is 1 5 x = 29 % 5; //x is 4 26.5. Basic I/O Java provides several ways to perform input and output operations with the standard input/output as part of the System class. The System class contains a standard output stream which can be accessed using System.out . It also has a standard input stream which can be accessed using System.in . For output, there are several methods that can be used but we’ll focus on System.out.println() and System.out.printf() . The first is for printing strings on a single line. The ln at the end indicates that the method will insert an endline character, \n for you. The second is a printf -style output method that takes placeholders like %d and %f (review Section 2.4.3 for details). The easiest way to read input is through the Scanner class. You can create a new instance of the Scanner class and associate it with the standard input using the following 395 | ComputerScienceOne_Page_429_Chunk1968 |
26. Basics 1 Scanner s = new Scanner(System.in); 2 int a; 3 System.out.println("Please enter a number: "); 4 a = s.nextInt(); 5 System.out.printf("Great, you entered %d\n", a); Code Sample 26.2.: Basic Input/Output in Java code. Scanner s = new Scanner(System.in); The variable s is now active and can be read from. You can get specific values from the Scanner by calling various methods such as s.nextInt() to get an int , s.nextDouble() to get a double , etc. When these methods are called, the program blocks until the user enters her input and presses the enter/return key. The conversion to the type you requested is automatic. A full example is depicted in Code Sample 26.2. One potential problem with using Scanner is that the methods cannot force a user to enter good input. In the example above, if the user, instead of entering a number, entered "Hello" , the conversion to a number would fail and result in a InputMismatchException . 26.6. Examples 26.6.1. Converting Units Let’s write a program that will prompt 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 program outline which will include a package and class declaration. We’ll also need to read from the standard input, so we’ll import the Scanner class. We’ll want want our class to be executable, so we need to put a main() method in our class. Finally, we’ll document our program to indicate its purpose. 396 | ComputerScienceOne_Page_430_Chunk1969 |
26.6. Examples 1 package unl.cse; 2 3 import java.util.Scanner; 4 5 /** 6 * This program converts Fahrenheit temperatures to 7 * Celsius 8 */ 9 public class TemperatureConverter { 10 11 public static void main(String args[]) { 12 13 //TODO: implement this 14 15 } 16 } 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, likely into a floating point number as degrees can be fractional 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 package unl.cse; 2 3 import java.util.Scanner; 4 5 /** 6 * This program converts Fahrenheit temperatures to 7 * Celsius 397 | ComputerScienceOne_Page_431_Chunk1970 |
26. Basics 8 */ 9 public class TemperatureConverter { 10 11 public static void main(String args[]) { 12 13 //TODO: implement this 14 //1. Prompt the user for input in Fahrenheit 15 //2. Read the Fahrenheit value from the standard input 16 //3. Compute the degrees Celsius 17 //4. Print the result to the user 18 19 } 20 } 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. It also makes sense that each of these should be double variables as we want to support fractional values. At the top of our main() method, we’ll add the variable declarations: double fahrenheit, celsius; We’ll also need a Scanner , initialized to read from the standard input: Scanner s = new Scanner(System.in); Each of the steps is now straightforward; we’ll use a System.out.println() statement in the first step to prompt the user for input: System.out.println("Please enter degrees in Fahrenheit: "); In the second step, we’ll use our Scanner to read in a value from the user for the fahrenheit variable. Recall that we use the method s.nextDouble() to read a double value from the user. fahrenheit = s.nextDouble(); We can now compute celsius using the formula provided: celsius = (fahrenheit - 32) * (5 / 9); Finally, we use System.out.printf() to output the result to the user: System.out.printf("%f Fahrenheit is %f Celsius\n", fahrenheit, celsius); 398 | ComputerScienceOne_Page_432_Chunk1971 |
26.6. Examples Try typing and running the program as defined above and you’ll find that you don’t get correct answers. In fact, you’ll find that no matter what values you enter, you get zero. This is because of the calculation using (5 / 9) : recall what happens with integer division: truncation! This will always end up being zero. One way we could fix it would be to pull out our calculators and find that 5 9 = 0.55555 . . . and replace (5 / 9) with 0.555555 . But, how many fives? It may be difficult to tell how accurate we can make this floating point number by hardcoding it ourselves. A much better approach would be to let the compiler take care of the optimal computation for us by making at least one of the numbers a double to prevent integer truncation. That is, we should instead use 5.0 / 9 . The full program can be found in Code Sample 26.3. 1 package unl.cse; 2 3 import java.util.Scanner; 4 5 public class TemperatureConverter { 6 7 public static void main(String args[]) { 8 9 double fahrenheit, celsius; 10 Scanner s = new Scanner(System.in); 11 12 //1. Prompt the user for input in Fahrenheit 13 System.out.println("Please enter degrees in Fahrenheit: "); 14 15 //2. Read the Fahrenheit value from the standard input 16 fahrenheit = s.nextDouble(); 17 18 //3. Compute the degrees Celsius 19 celsius = (fahrenheit - 32) * 5.0 / 9; 20 21 //4. Print the result to the user 22 System.out.printf("%f Fahrenheit is %f Celsius\n", 23 fahrenheit, celsius); 24 25 } 26 } Code Sample 26.3.: Fahrenheit-to-Celsius Conversion Program in Java 399 | ComputerScienceOne_Page_433_Chunk1972 |
26. Basics 26.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 a main() method 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. We’ll also need several variables: three for the coefficients a, b, c and two more; one for each root. 1 double a, b, c, root1, root2; 2 Scanner s = new Scanner(System.in); 3 4 System.out.println("Please enter a: "); 5 a = s.nextDouble(); 6 System.out.println("Please enter b: "); 7 b = s.nextDouble(); 8 System.out.println("Please enter c: "); 9 c = s.nextDouble(); Now to compute the roots: we need to adapt the formula so it accurately reflects the order of operations. We also need to use the standard math library’s square root method. 1 root1 = (-b + Math.sqrt(b*b - 4*a*c) ) / (2*a); 2 root2 = (-b - Math.sqrt(b*b - 4*a*c) ) / (2*a); Finally, we print the output using System.out.printf() . The full program can be found in Code Sample 26.4. This program was interactive. As an alternative, we could have read all three of the inputs as command line arguments, taking care that we need to convert them to floating point numbers. Lines 16–21 in the program could have been changed to 400 | ComputerScienceOne_Page_434_Chunk1973 |
26.6. Examples 1 a = Double.parseDouble(args[0]); 2 b = Double.parseDouble(args[1]); 3 c = Double.parseDouble(args[2]); Finally, think about the possible inputs a user could provide that may cause problems for this program. For example: • 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 start to resolve these issues, we’ll need conditionals. 401 | ComputerScienceOne_Page_435_Chunk1974 |
26. Basics 1 package unl.cse; 2 3 import java.util.Scanner; 4 5 /** 6 * This program computes the roots to a quadratic equation 7 * using the quadratic formula. 8 */ 9 public class QuadraticRoots { 10 11 public static void main(String args[]) { 12 13 double a, b, c, root1, root2; 14 Scanner s = new Scanner(System.in); 15 16 System.out.println("Please enter a: "); 17 a = s.nextDouble(); 18 System.out.println("Please enter b: "); 19 b = s.nextDouble(); 20 System.out.println("Please enter c: "); 21 c = s.nextDouble(); 22 23 root1 = (-b + Math.sqrt(b*b - 4*a*c) ) / (2*a); 24 root2 = (-b - Math.sqrt(b*b - 4*a*c) ) / (2*a); 25 26 System.out.printf("The roots of %fx^2 + %fx + %f are: \n", 27 a, b, c); 28 System.out.printf(" root1 = %f\n", root1); 29 System.out.printf(" root2 = %f\n", root2); 30 31 } 32 33 } Code Sample 26.4.: Quadratic Roots Program in Java 402 | ComputerScienceOne_Page_436_Chunk1975 |
27. Conditionals Java supports the basic if, if-else, and if-else-if conditional structures as well as switch statements. Java has Boolean types and logical statements are built using the standard logical operators for numeric comparisons as well as logical operators such as negations, And, and Or that can be used with Boolean types. 27.1. Logical Operators Recall that Java has Boolean types built-in to the language using either the primitive type, boolean or its wrapper class Boolean . Moreover, the keywords true and false can be used to assign and check values. Because Java has Boolean types, it does not allow you to mix logical operators with numeric types. That is, code like the following is invalid. 1 int a = 10; 2 boolean b = true; 3 boolean result = (a || b); //compilation error The standard numeric comparison operators are also supported. Consider the following code snippet: 1 int a = 10; 2 int b = 20; 3 int c = 10; 4 boolean x = true; 5 boolean y = false; The six standard comparison operators are presented in Table 27.1 using these variables as examples. The comparison operators are the same when used with double types as 403 | ComputerScienceOne_Page_437_Chunk1976 |
27. Conditionals Name Operator Syntax Examples Value Equals == a == 10 true b == 10 false a == b false a == c true Not Equals != a != 10 false b != 10 true a != b true a != c false Strictly Less Than < a < 15 true a < 5 false a < b true a < c false Less Than Or Equal To <= a <= 15 true a <= 5 false a <= b true a <= c true Strictly Greater Than > a > 15 false a > 5 true a > b false a > c false Greater Than Or Equal To >= a >= 15 false a >= 5 true a >= b false a >= c true Table 27.1.: Comparison Operators in Java well and int types and can be compared with each other without type casting. Furthermore, because of autoboxing and unboxing, the wrapper classes for numeric types can be compared using the same operators. For example: 1 int a = 10; 2 Integer b = 20; 3 Double x = 3.14; 4 boolean r; 5 r = (a < b); 6 r = (a >= b); 7 r = (x == 2.71); 404 | ComputerScienceOne_Page_438_Chunk1977 |
27.1. Logical Operators Operator Operator Syntax Examples Values Negation ! !x false !y true And && x && true true x && y false Or || x || false true x || y true !x || y false Table 27.2.: Logical Operators in Java with x = true and y = false both being Boolean variables. Operator(s) Associativity Notes Highest ++ , -- left-to-right postfix 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 27.3.: Operator Order of Precedence in Java. Operators on the same level have equivalent order and are performed in the associative order specified. The three basic logical operators are also supported as described in Table 27.2. 27.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 || args.length != 4) It is important to understand the order in which each one gets evaluated. Table 27.3 summarizes the order of precedence for the operators seen so far. This is not an exhaustive list of Java operators. 405 | ComputerScienceOne_Page_439_Chunk1978 |
27. Conditionals 27.1.2. Comparing Strings and Characters The comparison operators in Table 27.1 can also be used for single characters because of the nature of the ASCII text table (see Table 2.4). Each alphanumeric character, including the various symbols and whitespace characters, is associated with an integer 0– 127. We can therefore write statements like ('A' < 'a') , which is true since uppercase letters are ordered before lowercase letters in the ASCII table ( 'A' is 65 and 'a' is 97 and so 65 < 97 is true). Several more examples can be found in Table 27.4. Comparison Example Result ('A' < 'a') true ('A' == 'a') false ('A' < 'Z') true ('0' < '9') true ('\n' < 'A') true (' ' < '\n') false Table 27.4.: Character comparisons in Java Numeric comparison operators cannot be used to compare strings in Java. For example, we could not code something like ("aardvark" < "zebra") . The Java compiler would not allow you to do this because the comparison operator is for numeric types only. However, the following code would compile and run: 1 String s = "aardvark"; 2 String t = "zebra"; 3 boolean b = (s == t); but it wouldn’t necessarily give you what you want. To understand why this is okay, recall that a String is an object; the s and t variables are references to that object in memory. When we use the equality comparison, == we’re asking if s and t are the same memory address. In this case, likely they are not and so the result is false . However, similar code, 1 String s = new String("liger"); 2 String t = new String("liger"); 3 boolean b = (s == t); 406 | ComputerScienceOne_Page_440_Chunk1979 |
27.2. If, If-Else, If-Else-If Statements 1 //example of an if statement: 2 if(x < 10) { 3 System.out.println("x is less than 10"); 4 } 5 6 //example of an if-else statement: 7 if(x < 10) { 8 System.out.println("x is less than 10"); 9 } else { 10 System.out.println("x is 10 or more"); 11 } 12 13 //example of an if-else-if statement: 14 if(x < 10) { 15 System.out.println("x is less than 10"); 16 } else if(x == 10) { 17 System.out.println("x is equal to ten"); 18 } else { 19 System.out.println("x is greater than 10"); 20 } Code Sample 27.1.: Examples of Conditional Statements in Java would also result in false because s and t represent different strings in memory, even though they have the same sequence of characters. We’ll explore how to properly compare strings later. For now, avoid using the equality operators with strings. 27.2. If, If-Else, If-Else-If Statements Conditional statements in Java 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 27.1. 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: 407 | ComputerScienceOne_Page_441_Chunk1980 |
27. Conditionals 1 int x = 15; 2 if(x < 10); { 3 System.out.println("x is less than 10"); 4 } Some compilers may give a warning, but this is valid Java; it will compile and it will run. 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 int x = 15; 2 if(x < 10) { 3 } 4 System.out.println("x is less than 10"); Which is obviously not what we wanted. The semicolon ended up binding 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. First, 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. 27.3. Examples 27.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 408 | ComputerScienceOne_Page_442_Chunk1981 |
27.3. Examples 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 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, Math.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 Math.log(x) / Math.log(b) However, 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 System.out.println("Error: bad input!"); 3 System.exit(1); 4 } This code has something new: System.exit(1) . The exit() function immediately terminates the program regardless of the rest of the code that it 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 1Bases can also be 0 < b < 1, but we’ll restrict our attention to increasing functions only. 409 | ComputerScienceOne_Page_443_Chunk1982 |
27. Conditionals Code Sample 27.2. The program also takes the input as command line arguments. Now that we have conditionals, we can actually 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. 27.3.2. Life & Taxes Let’s adapt the conditional statements we developed in Section 3.6.4 into a full Java program. 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. 1 Scanner s = new Scanner(System.in); 2 double income, baseTax, numChildren, credit, totalTax; 3 4 System.out.println("Please enter your Adjusted Gross Income: "); 5 income = s.nextDouble(); 6 7 System.out.println("How many children do you have?"); 8 numChildren = s.nextDouble(); 9 10 if(income < 0 || numChildren < 0) { 11 System.out.println("Invalid inputs"); 12 System.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 } 410 | ComputerScienceOne_Page_444_Chunk1983 |
27.3. Examples Next we compute the child tax credit, taking care that it does not exceed $3,000. A conditional based on the number of children should suffice 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 negative). 1 if(baseTax - credit >= 0) { 2 totalTax = baseTax - credit; 3 } else { 4 totalTax = 0; 5 } The full program is presented in Code Sample 27.3. 27.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 27.4. 411 | ComputerScienceOne_Page_445_Chunk1984 |
27. Conditionals 1 /** 2 * This program computes the logarithm base b (b > 1) 3 * of a given number x > 0 4 */ 5 public class Logarithm { 6 7 public static void main(String args[]) { 8 9 double b, x, result; 10 if(args.length != 2) { 11 System.out.println("Usage: b x"); 12 System.exit(1); 13 } 14 15 b = Double.parseDouble(args[0]); 16 x = Integer.parseInt(args[1]); 17 18 if(x <= 0) { 19 System.out.println("Error: x must be greater than zero"); 20 System.exit(1); 21 } 22 if(b <= 1) { 23 System.out.println("Error: base must be greater than one"); 24 System.exit(1); 25 } 26 27 result = Math.log(x) / Math.log(b); 28 System.out.printf("log_(%f)(%f) = %f\n", b, x, result); 29 30 } 31 32 } Code Sample 27.2.: Logarithm Calculator Program in Java 412 | ComputerScienceOne_Page_446_Chunk1985 |
27.3. Examples 1 import java.util.Scanner; 2 3 public class Taxes { 4 5 public static void main(String args[]) { 6 7 Scanner s = new Scanner(System.in); 8 double income, baseTax, totalTax, numChildren, credit; 9 10 System.out.println("Please enter your Adjusted Gross Income: "); 11 income = s.nextDouble(); 12 13 System.out.println("How many children do you have?"); 14 numChildren = s.nextDouble(); 15 16 if(income < 0 || numChildren < 0) { 17 System.out.println("Invalid inputs"); 18 System.exit(1); 19 } 20 21 if(income <= 18150) { 22 baseTax = income * .10; 23 } else if(income <= 73800) { 24 baseTax = 1815 + (income -18150) * .15; 25 } else if(income <= 148850) { 26 baseTax = 10162.50 + (income - 73800) * .25; 27 } else if(income <= 225850) { 28 baseTax = 28925.00 + (income - 148850) * .28; 29 } else if(income <= 405100) { 30 baseTax = 50765.00 + (income - 225850) * .33; 31 } else if(income <= 457600) { 32 baseTax = 109587.50 + (income - 405100) * .35; 33 } else { 34 baseTax = 127962.50 + (income - 457600) * .396; 35 } 36 37 if(numChildren <= 3) { 38 credit = numChildren * 1000; 39 } else { 40 credit = 3000; 41 } 42 43 if(baseTax - credit >= 0) { 44 totalTax = baseTax - credit; 45 } else { 46 totalTax = 0; 47 } 48 49 System.out.printf("AGI: $%10.2f\n", income); 50 System.out.printf("Tax: $%10.2f\n", baseTax); 51 System.out.printf("Credit: $%10.2f\n", credit); 52 System.out.printf("Tax Liability: $%10.2f\n", totalTax); 53 54 } 55 56 } Code Sample 27.3.: Tax Program in Java 413 | ComputerScienceOne_Page_447_Chunk1986 |
27. Conditionals 1 /** 2 * This program computes the roots to a quadratic equation 3 * using the quadratic formula. 4 */ 5 public class Roots { 6 7 public static void main(String args[]) { 8 double a, b, c, root1, root2; 9 10 if(args.length != 3) { 11 System.err.println("Usage: a b c\n"); 12 System.exit(1); 13 } 14 15 a = Double.parseDouble(args[0]); 16 b = Double.parseDouble(args[1]); 17 c = Double.parseDouble(args[2]); 18 19 if(a == 0) { 20 System.err.println("Error: a cannot be zero"); 21 System.exit(1); 22 } else if(b*b < 4*a*c) { 23 System.err.println("Error: cannot handle complex roots\n"); 24 System.exit(1); 25 } else if(b*b == 4*a*c) { 26 root1 = -b / (2*a); 27 System.out.printf("Only one distinct root: %f\n", root1); 28 } else { 29 root1 = (-b + Math.sqrt(b*b - 4*a*c) ) / (2*a); 30 root2 = (-b - Math.sqrt(b*b - 4*a*c) ) / (2*a); 31 32 System.out.printf("The roots of %fx^2 + %fx + %f are: \n", 33 a, b, c); 34 System.out.printf(" root1 = %f\n", root1); 35 System.out.printf(" root2 = %f\n", root2); 36 } 37 } 38 39 } Code Sample 27.4.: Quadratic Roots Program in Java With Error Checking 414 | ComputerScienceOne_Page_448_Chunk1987 |
28. Loops Java 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 the blocks of code associated with the loop are enclosed in curly brackets. 28.1. While Loops Code Sample 28.1 contains an example of a basic while loop in C. Just as with conditional statements, our code styling 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 have a semicolon since it is not an executable statement. Just as with an if-statement, if we had included a semicolon it would have led to unintended results. Consider the following: 1 while(i <= 10); { 2 //perform some action 3 i++; //iteration 4 } 1 int i = 1; //Initialization 2 while(i <= 10) { //continuation condition 3 //perform some action 4 i++; //iteration 5 } Code Sample 28.1.: While Loop in Java 415 | ComputerScienceOne_Page_449_Chunk1988 |
28. Loops 1 int i = 1; 2 boolean flag = true; 3 while(flag) { 4 //perform some action 5 i++; //iteration 6 if(i>10) { 7 flag = false; 8 } 9 } Code Sample 28.2.: Flag-controlled While Loop in Java 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 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! Some compilers will warn you about this, others will not. It is valid Java and it will compile and run, but obviously won’t work as intended. Avoid this problem by using proper syntax. Another common use case 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. An example can be found in Code Sample 28.2. 416 | ComputerScienceOne_Page_450_Chunk1989 |
28.2. For Loops 28.2. For Loops For loops in Java use the familiar syntax of placing the initialization, continuation condition, and iteration on the same line as the keyword for . An example can be found in Code Sample 28.3. 1 for(int i=1; i<=10; i++) { 2 //perform some action 3 } Code Sample 28.3.: For Loop in Java Semicolons are placed at the end of the initialization and continuation condition, but not the iteration statement. Just as 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. Another observation: the declaration of the counter variable i was done in the initializa- tion statement. This scopes the variable to the loop itself. The variable i is valid inside the loop body, but will be out-of-scope after the loop body. It is possible to declare the variable prior to the loop, but the variable i would have a much larger scope. It is best practice to limit the scope of variables only to where they are needed. Thus, we will write our loops as above. 28.3. Do-While Loops Finally, Java 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 28.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. 417 | ComputerScienceOne_Page_451_Chunk1990 |
28. Loops 1 int i; 2 do { 3 //perform some action 4 i++; 5 } while(i <= 10); Code Sample 28.4.: Do-While Loop in Java 28.4. Enhanced For Loops Java also supports foreach loops (which were introduced in JDK 1.5.0) which Java refers to as “Enhanced For Loops.” Foreach loops allow you to iterate over each element in a collection without having to define an index variable or otherwise “get” each element. We’ll revisit these concepts in detail in Chapter 31, but let’s take a look at a couple of examples. An enhanced for loop in Java still uses the keyword for but uses different syntax for its control. The example in Code Sample 28.5 illustrates this syntax: (int a : arr) . The last element of this syntax is a reference to the collection that we want to iterate over. The first part is the type and local reference variable that the loop will use. 1 int arr[] = {10, 20, 8, 42}; 2 int sum = 0; 3 for(int a : arr) { 4 sum += a; 5 } Code Sample 28.5.: Enhanced For Loops in Java Example 1 The code (int a : arr) should be read as “for each integer element a in the collection arr ...” Within the enhanced for loop, the variable a will be automatically updated for you on each iteration. Outside the loop body, the variable a is out-of-scope. Java allows you to use an enhanced for loop with any array or collection (technically, anything that implements the Iterable interface). One example is a List , an ordered collection of elements. Code Sample 28.6 contains an example. 418 | ComputerScienceOne_Page_452_Chunk1991 |
28.5. Examples 1 List<Integer> list = Arrays.asList(10, 20, 8, 42); 2 int sum = 0; 3 for(Integer a : list) { 4 sum += a; 5 } Code Sample 28.6.: Enhanced For Loops in Java Example 2 28.5. Examples 28.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 28.7 specifically refers to the value 32145.234 but would work equally well with any value of x . 1 double x = 32145.234; 2 int k = 0; 3 while(x > 10) { 4 x = x / 10; //or: x /= 10; 5 k++; 6 } Code Sample 28.7.: Normalizing a Number with a While Loop in Java 28.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 28.8 We could have easily generalized the code somewhat. 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. 419 | ComputerScienceOne_Page_453_Chunk1992 |
28. Loops 1 int sum = 0; 2 for(int i=1; i<=10; i++) { 3 sum += i; 4 } Code Sample 28.8.: Summation of Numbers using a For Loop in Java 1 for(int i=1; i<=n; i++) { 2 sum += i; 3 } 28.5.3. Nested Loops Recall that you can write loops within loops by nesting them. The inner loop will execute fully for each iteration of the outer loop. An example of two nested of loops in Java can be found in Code Sample 28.9. 1 int i, j; 2 int n = 10; 3 int m = 20; 4 for(i=0; i<n; i++) { 5 for(j=0; j<m; j++) { 6 System.out.printf("(i, j) = (%d, %d)\n", i, j); 7 } 8 } Code Sample 28.9.: Nested For Loops in Java The inner loop execute for j = 0, 1, 2, . . . , 19 < m = 20 for a total of 20 iterations. How- ever, it executes 20 times for each iteration of the outer loop. Since the outer loop execute for i = 0, 1, 2, . . . , 9 < n = 10, the total number of times the System.out.printf() statement execute is 10 × 20 = 200. In this example, the sequence (0, 0), (0, 1), (0, 2), . . . , (0, 19), (1, 0), . . . , (9, 19) will be printed. 420 | ComputerScienceOne_Page_454_Chunk1993 |
28.5. Examples 28.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 math library’s Math.pow() function, we have the following. 1 double monthlyPayment = (monthlyInterestRate * principle) / 2 (1 - pow( (1 + monthlyInterestRate), -n)); However, recall that we may have problems due to accuracy. The monthly payment could 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 Math.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! In Java, we could simply do the following. monthlyPayment = Math.round(monthlyPayment * 100.0) / 100.0; 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 System.out.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 28.10. 421 | ComputerScienceOne_Page_455_Chunk1994 |
28. Loops 1 public class LoanAmortization { 2 3 public static void main(String args[]) { 4 5 if(args.length != 4) { 6 System.err.println("Usage: principle apr terms"); 7 System.exit(1); 8 } 9 10 double principle = Double.parseDouble(args[0]); 11 double apr = Double.parseDouble(args[1]); 12 int n = Integer.parseInt(args[2]); 13 14 double balance = principle; 15 double monthlyInterestRate = apr / 12.0; 16 17 //monthly payment 18 double monthlyPayment = (monthlyInterestRate * principle) / 19 (1 - Math.pow( (1 + monthlyInterestRate), -n)); 20 //round to the nearest cent 21 monthlyPayment = Math.round(monthlyPayment * 100.0) / 100.0; 22 23 System.out.printf("Principle: $%.2f\n", principle); 24 System.out.printf("APR: %.4f%%\n", apr*100.0); 25 System.out.printf("Months: %d\n", n); 26 System.out.printf("Monthly Payment: $%.2f\n", monthlyPayment); 27 28 //for the first n-1 payments in a loop: 29 for(int i=1; i<n; i++) { 30 // compute the monthly interest, rounded: 31 double monthlyInterest = 32 Math.round( (balance * monthlyInterestRate) * 100.0) / 100.0; 33 // compute the monthly principle payment 34 double monthlyPrinciplePayment = monthlyPayment - monthlyInterest; 35 // update the balance 36 balance = balance - monthlyPrinciplePayment; 37 // print i, monthly interest, monthly principle, new balance 38 System.out.printf("%d\t$%10.2f $%10.2f $%10.2f\n", i, monthlyInterest, 39 monthlyPrinciplePayment, balance); 40 } 41 42 //handle the last month and last payment separately 43 double lastInterest = Math.round( 44 (balance * monthlyInterestRate) * 100.0) / 100.0; 45 double lastPayment = balance + lastInterest; 46 47 System.out.printf("Last payment = $%.2f\n", lastPayment); 48 49 } 50 51 } Code Sample 28.10.: Loan Amortization Program in Java 422 | ComputerScienceOne_Page_456_Chunk1995 |
29. Methods As an object-oriented programming language, functions in Java are usually referred to as methods and are essential to writing programs. The distinction is that a function is usually a standalone element while methods are functions that are members of a class. In Java, since everything is a class or belongs to a class, standalone functions cannot be defined. In Java you can define your own methods, but they need to be placed within a class. Usually methods that act on data in the class (or instances of the class, see Chapter 34) or have common functionality are placed into one class. For example, all the basic math methods are part of the java.lang.Math class. It is not uncommon to place similar methods together into one “utility” class. Java supports method overloading, so within the same class you can define multiple methods with the same name as long as they differ in either the number (also called arity) or type of parameters. For example, in the java.lang.Math class, there are 3 versions of the absolute value method, abs() , one that takes/returns an int , one that takes/returns a double and one for float types. Naming conflicts can easily be solved by ensuring that you place your methods in a class/package that is unique to your application. In Java, the 8 primitive types ( int , double , char , boolean , etc.) are always passed by value. All object types, however, such as the wrapper classes Integer , Double as well as String , etc. are passed by reference. That is, the memory address in the JVM is passed to the method. This is done for efficiency. For objects that are “large” it would be inefficient to copy the entire object into the call stack in order to pass it to a method. Though object types are passed by reference, the method cannot necessarily change them. Recall that the wrapper classes Integer , Double and the String class are all immutable, meaning that once created they cannot be modified. Though they are passed by reference, the method that receives them cannot change them. There are many mutable objects in Java. The StringBuilder class for example is a mutable object. If you pass a StringBuilder instance to a method, that method is free to invoke mutator methods on the object such as .append() that change the object’s state. Since it is the same object as in the calling method, the calling method can “see” those changes. 423 | ComputerScienceOne_Page_457_Chunk1996 |
29. Methods As of Java 5, you can write and use vararg methods. The System.out.printf() method is a prime example of this. However, we will not discuss in detail how to do this. Instead, refer to standard Java documentation. Finally, parameters are not optional in Java. This is because Java supports method overloading. You can write multiple versions of the same method that each take a different number of arguments. You can even design them so that the more specific versions (with fewer arguments) invoke the more general versions (with more arguments), passing in sensible “defaults.” 29.1. Defining Methods Defining methods is fairly straightforward. First you create a class to place them in. Then you provide the method signature along with the body of the method. In addition, there are several modifiers that you can place in the method signature to specify its visibility and whether or not the method “belongs” to the class or to instances of the class. This is a concept we’ll explore in Chapter 34. For now, we’ll only focus on what is needed to get started. Typically, the documentation for methods is included with the method definition using “Javadoc” style comments. Consider the following examples. 1 /** 2 * Computes the sum of the two arguments. 3 * @param a 4 * @param b 5 * @return the sum, <code>a + b</code> 6 */ 7 public static int sum(int a, int b) { 8 return (a + b); 9 } 10 11 /** 12 * Computes the Euclidean distance between the 2-D points, 13 * (x1,y1) and (x2,y2). 14 * @param x1 15 * @param y1 16 * @param x2 17 * @param y2 18 * @return 19 */ 20 public static double getDistance(double x1, double y1, 21 double x2, double y2) { 22 double xDiff = (x1-x2); 424 | ComputerScienceOne_Page_458_Chunk1997 |
29.1. Defining Methods 23 double yDiff = (y1-y2); 24 return Math.sqrt( xDiff * xDiff + yDiff * yDiff); 25 } 26 27 /** 28 * Computes a monthly payment for a loan with the given 29 * principle at the given APR (annual percentage rate) which 30 * is to be repaid over the given number of terms. 31 * @param principle - the amount borrowed 32 * @param apr - the annual percentage rate 33 * @param terms - number of terms (usually months) 34 * @return 35 */ 36 public static double getMonthlyPayment(double principle, 37 double apr, int terms) { 38 double rate = (apr / 12.0); 39 double payment = (principle * rate) / (1-Math.pow(1+rate, -terms)); 40 return payment; 41 } In each of the examples above, the first modifier keyword we used was public . This makes the method visible to all other parts of the code base. Any other piece of code can invoke the method and take advantage of the functionality it provides. Alternatively, we could have used the keywords private (which makes it visible only to other methods in the same class) protected or “package protected” by omitting the modifier altogether. We will want our methods to be available to other classes, so we’ll make most of them public . The second modifier is static which makes it so that the method belongs to the class itself rather than instances of the class. We discuss visibility keywords and instances in detail in Chapter 34. For now, we will make all of our methods static . After the modifiers, we provide the method signature including the return type, its identifier (name), and its parameter list. Method names must follow the same naming rules as variables: they must begin with an alphabetic character and may contain alphanumeric characters as well as underscores. However, using modern coding conventions we name methods using lower camel casing. Immediately after the signature we provide a method body which contains the code that will be run upon invocation of the method. The method body is enclosed using opening/closing curly brackets. 425 | ComputerScienceOne_Page_459_Chunk1998 |
29. Methods 29.1.1. Void Methods The keyword void can be used in Java to indicate a method does not return a value, in which case it is called a “void method.” Though it is not necessary, it is still good practice to include a return statement. 1 public static void printCopyright() 2 System.out.println("(c) Bourke 2015"); 3 return; 4 } In the example above, we’ve also illustrated how to define a method that has no input parameters. 29.1.2. Using Methods Once a method has been defined in a class, you can make use of the method as follows. First, you may need to import the class itself depending on where it is. For example, suppose that the examples we’ve presented so far are contained in a class named Utils (short for “utilities”) which is in a package named unl.cse . Then in the class in which we want to call some of these functions we would import it using import unl.cse.Utils; prior to the class declaration. Once the class has been imported, we can invoke a method in the class by first referencing the class and using the dot operator to access one of its methods. For example, 1 int a = 10, b = 20; 2 int c = Utils.sum(a, b); //c contains the value 30 3 4 //invoke a method with literal values: 5 double dist = Utils.getDistance(0.0, 0.0, 10.0, 20.0); 6 7 //invoke a method with a combination: 8 double p = 1500.0; 9 double r = 0.05; 10 double monthlyPayment = Utils.getMonthlyPayment(p, r, 60); 426 | ComputerScienceOne_Page_460_Chunk1999 |
29.1. Defining Methods The Utils.methodName() syntax is used because the methods are static –they belong to the class and so must be invoked through the class using the class’s name. We’ve previously seen this syntax when using System. or Math. with the standard JDK library functions. 29.1.3. Passing By Reference Java does not allow you the ability to specify if a variable is passed by reference or by value. Instead, all primitive types are passed by value while all object types are passed by reference. Moreover, most of the built-in types such as Integer and String are immutable, even though they are passed by reference, any method that receives them cannot change them. Only if the passed object is mutable can the method make changes to it (by invoking its methods). As an example, consider the following piece of code. The StringBuilder class is a mutable string object. You can change the string contents stored in a StringBuilder by calling one of its many methods such as append() , which will add whatever string you give it to the end. In the main method, we create two objects, a String and a StringBuilder and pass it to a method that makes changes to both by appending " world!" to them. Understand what happens here though. The first line in change() actually creates a new string and then changes what the parameter variable s references. The reference to the original string, "Hello" is lost and replaced with the new string. In contrast, the StringBuilder instance is actually changed via its append() method but is still the same object. 1 public class Mutability { 2 3 public static void change(String s, StringBuilder sb) { 4 s = s + " world!"; 5 sb.append(" world!"); 6 7 System.out.println("change: s = " + s); 8 System.out.println("change: sb = " + sb); 9 } 10 11 public static void main(String args[]) { 12 String a = "Hello"; 13 StringBuilder b = new StringBuilder("Hello"); 14 15 System.out.println("main: s = " + a); 427 | ComputerScienceOne_Page_461_Chunk2000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.