Java Reference
In-Depth Information
4. Write a method that throws an exception when you do not want to handle the ex-
ception. It becomes the responsibility of the calling method to handle the exception.
5. A method that overrides a method that does not throw an exception cannot throw an
exception. The only alternative is to use a try - catch statement.
6. Use try -with-resources when opening a file. This will close the file automatically and
will simplify the code.
7. There are three ways to handle an exception: (1) print an error and terminate the
program, (2) print an error message or write to a log file and continue executing the
program, or (3) fix the error (e.g., ask for valid input again). It is up to the programmer
to choose which way to handle exceptions.
8. Every time we write code that opens a file, we need to add exception-handling code.
The reason is that opening a file generates a checked exception that needs to be
handled. Using a try -with-resources block is the easiest way to handle a possible
exception.
9. All classes that will have objects serialized (i.e., objects written to the hard disk) need
to implement the Serializable interface.
10. Java allows objects with cyclic references to be serialized. The programmer does not
need to do anything special. Java will make sure that every object is serialized just
once.
11. When an aggregate object is serialized, all its inner objects that implement the
Serializable interface are also serialized.
13.7 Exercises
1. Create a program that reads a text file, where the name of the file is specified by the
user. The program should print the smallest number in the file. You can assume that
the file contains only integers.
2. Create a program that asks the user to specify an input and output file. The program
should open the input file and copy all the integers from the file into an ArrayList .
It should then use Collections.sort to sort the ArrayList . As a final step, the
program should output the sorted ArrayList into the output file.
3. Create a program that takes as input the name of a file. The program should print
the content of the file.
4. Create a program that takes as input the name of a file that contains integers. The
program should print the number of integers in the file. You can assume that the file
contains only integers.
5. Create a program that takes as input the name of a file. The file does not need
to contain only integers. The program should print the average of the integers as a
double . Use exception handling to skip over elements of the file that are not integers.
 
Search WWH ::




Custom Search