Section 12.7. Concepts Summary


[Page 433 (continued)]

12.7. Concepts Summary

In this chapter we have learned about handling exceptions, reading and writing files, reading from the Internet, using import statements, using while loops, manipulating String objects, and using ArrayList objects (dynamic arrays).

12.7.1. Exceptions

An exception occurs when something goes wrong. Exception handling shouldn't be used to handle normal execution of a program, but it is used to handle exceptional events. For example if you try to read from a file and the file doesn't exist, you will get a FileNotFoundException. If you try to write to a file and the disk is full, you will get an IOException. If you try to invoke a method on a object reference that is null, you will get a NullPointerException. Each of these exceptions inherits from java.lang.Exception, and each is an object. Every exception knows how to print the call stack (using the method printStackTrace()) which is helpful in figuring out where the exception occurred and how it got there.


[Page 434]

There are two kinds of exceptions: checked and unchecked. The programmer must do something to handle checked exceptions. You can either catch exceptions or throw them. The programmer is not required to handle unchecked exceptions such as NullPointerException or ArrayIndexOutOfBoundsException.

To catch an exception use:

try {    // statements that can cause exceptions } catch (Exception ex) {    // what to do if an exception happens } finally {    // what to do no matter what happens above }


The finally block is optional. If a finally block is present it will be executed both if an exception occurs and if an exception does not occur.

You can have more than one catch block. All Exception objects inherit from java.lang.Exception. When you catch an Exception object you will also catch all objects that inherit from the type you specified.

12.7.2. Reading and Writing Files

The classes that handle reading and writing files are in the package java.io. Each class in the package is responsible for one task and the classes can be combined in different ways to solve different problems. Classes that work with character data are Reader and Writer classes. Classes that work with binary data are Stream classes. A stream is a series of bits.

To read files we created a BufferedReader using a FileReader to buffer the data from the disk after it is read from the file. We used the readLine() method of BufferedReader to loop reading from the file until the returned String was null. Reading from a file can cause checked exceptions so we enclosed the code in a try block and added catch blocks to catch the exceptions.

To write files we created a BufferedWriter using a FileWriter to buffer the data in before writing it to the file. We used the write method to write String objects to the file and we used the newLine() method to force a new line in the file. Writing to a file can cause checked exceptions so we enclosed the code in a try block and added catch blocks to catch the exceptions.

We also used the File class to get a list of the files in a directory.

12.7.3. Reading from the Internet

To create a program that reads directly from the Internet we used the URL class from the java.net package. We created a URL object from a string representation of a URL. Then we used the openStream() method on the URL object to get back a java.io.InputStream object which knows how to read from a stream of bytes. We used the InputStream object to create a java.io.InputStreamReader object which knows how to turn the bytes into characters. We created a java.io. BufferedReader object from the InputStreamReader to handle the buffering of the data in memory. Then we were able to use the readLine() method of BufferedReader to read from the network.


[Page 435]

12.7.4. Import Statements

Whenever we use classes from a package other than java.lang we have to specify either the full name of the class or use an import statement before the class declaration. The full name of a class is the package name followed by a '.' and then the class name. The full name of the BufferedReader class is java.io.Buffered-Reader. If we want to refer to this in our code as just BufferedReader we need an import statement before the class declaration. We can import this as:

import java.io.BufferedReader;


which imports just that class. Or we can use:

import java.io.*;


which allows us to use all the classes in that package. It doesn't include any code, it just tells the compiler where to look for the class. If you are using more than one class from a package, this second way is easier.

12.7.5. While Loops

Even though for loops and while loops are the same as far as the computer is concerned, people use them in different ways. Use a for loop when you know how many times the loop will execute and a while loop when you want to loop as long as a boolean test is true. We used a while loop to read lines from a file until the line read was null, which indicates that we have reached the end of the file.

// Loop while there is more data while((line = reader.readLine()) != null) {   // print the current line   System.out.println(line); }


Methods Summary

String methods Strings are sequences of characters. The first character is at index 0. You can get the length of a string using the method length(). Here are the other methods we covered:


[Pages 436 - 437]

stringObj.charAt(int position)

Returns the character at the given position in the string. The first character is at position 0, just as the first element of an array is at index 0.

substring(int n,int m)

Returns a new string which is a substring of the string starting at the nth character and preceding up to but not including the mth character. A substring includes part of the original string.

substring(int n)

Returns a new string which is a substring of the string starting at the nth character and including the rest of the characters in the string.

startsWith(String prefix)

Returns true if the string starts with the given prefix, else it will return false.

endsWith(String suffix)

Returns true if the string ends with the given suffix, else it will return false.

indexOf(String str)

Returns the first index of the passed str, if it is found. If str isn't in the current string it will return 1.

indexOf(String str, int fromIndex)

Returns the first index of the passed str at or after the passed fromIndex, if it is found. If str isn't in the current string at or after the fromIndex, it will return 1.

lastIndexOf(String str)

Returns the last index of the passed str, if it is found. If str isn't in the current string it will return 1.

lastIndexOf(String str, int index)

Returns the last index of the passed str found looking backwards starting at index. If str isn't in the current string before the given index it will return 1.

toUpperCase()

Returns a new string with all the characters in uppercase.

toLowerCase()

Returns a new string with all the characters in lowercase.

replace(String oldStr, String newStr)

Returns a new string with the character in the oldStr string replaced with the character in the newStr string for all occurrences of the oldStr string. This is new in Java 1.5.

replaceAll(String regex, String newStr)

Returns a new string with all the matching substrings specified by the regular expression (regex) replaced with the characters in newStr. A regular expression can be just a string of characters or it can also use special characters to indicate that it will match any character, any digit, only uppercase characters, etc.

replaceFirst(String regex, String newStr)

Returns a new string with the first substring that matches the regular expression specified by regex replaced with the characters in newStr. A regular expression can be just a string of characters or it can also use special characters to indicate that it will match any character, any digit, only uppercase characters, etc.

split(String regex)

Returns an array of String objects. It will split the current string into many by breaking it into new strings whenever it matches the regular expression specified in regex.

trim()

Returns a new string with all white space (spaces and tabs) removed from the beginning and end of the string.


ArrayList Methods

An ArrayList is a dynamic array (an array that can grow or shrink as needed). It is in the package java.util. It implements the java.util.List interface and thus an object of the class ArrayList can be referred to by a variable declared as type List. The methods that we covered are:

add(Object o)

Adds the passed object to the end of the list (next open position in the array).

add(int index, Object o)

Adds the passed object to the list at the given index. If another object is at that index it will be moved to (index + 1). If an object was at (index + 1) it will be moved to (index + 2). So, all objects at the passed index or above will change to the location specified by their (current index + 1).

get(int index)

Returns the object at this index in the list

set(int index, Object o)

Sets the value at this index in the list to the passed object. If an object is at that index it will be moved to (index + 1). If an object was at (index + 1) it will be moved to (index + 2). So, all objects at the index or above will change to the location specified by their (current index + 1).

size()

Returns the number of elements in the list

remove(int index)

Removes the object at the passed index. Any objects with a current index value greater than this will change to (current index 1).


File Methods

We have only covered one method of the java.io.File class. The method list() returns an array of String objects which are the names of all the items in the directory represented by the File object.

Random Methods

We have covered two methods of the java.util.Random class. The method nextdouble() will return a double between 0 and 1.0 inclusive. The method nextInt(int num) will return an integer between 0 (inclusive) and num exclusive.



Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
Introduction to Computing & Programming Algebra in Java(c) A Multimedia Approach
ISBN: N/A
EAN: N/A
Year: 2007
Pages: 191

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net