09 Handout 1
09 Handout 1
A. Exception Handling
• Exception handling is the process used to change the normal flow of code execution if a
specified exception occurs.
• Exceptions can be caught using a combination of the try and catch keywords. A try/catch
block is placed around the code that might generate an exception.
• Syntax:
try {
//some code
} catch (Exception e) {
//some code to handle exceptions
}
• A try block is a block of code that might throw an exception that can be handled by a
matching catch block. A catch block is a segment of code that can handle an exception
that might be thrown by the try block that precedes it.
• If the type of exception that occurred is listed in a catch block, the exception is passed to
the catch block as an argument is passed into a method parameter.
• For example:
public class MyClass {
public static void main(String[ ] args) {
try {
int a[ ] = new int[2];
System.out.println(a[5]);
} catch (Exception e) {
System.out.println("An error occurred");
}
}
}
//Outputs "An error occurred"
C. Multiple Exceptions
• Only one (1) try block is accepted in a program but there can be multiple catch blocks.
• For example:
System.out.println(colors);
}
}
// Output: [Red, Blue, Orange]
• Other useful methods include the following. Note: As with arrays, the indexing starts with
0.
o contains() - returns true if the list contains the specified element
o get(int index) - returns the element at the specified position in the list
o size() - returns the number of elements in the list
o clear() - removes all of the elements from the list
B. Maps
• Arrays and lists store elements as ordered collections, with each element given an integer
index. A map is used for storing data collections as key and value pairs. One (1) object is
used as a key (index) to another object (the value).
• The HashMap class is used for implementing maps in Java.
• put, remove, and get methods are used to add, delete, and access values in a map.
• Example:
import java.util.HashMap;
public class MyClass {
public static void main(String[ ] args) {
HashMap<String, Integer> points = new HashMap<String,
Integer>();
points.put("Amy", 154);
points.put("Dave", 42);
points.put("Rob", 733);
System.out.println(points.get("Dave"));
}
}
// Outputs 42
• In this map, the keys are of String type and the values are of Integer type.
C. Sets
• A set is a collection that cannot contain duplicate elements. It models the mathematical set
abstraction.
• One (1) of the implementations of the Set interface is the HashSet class. For example:
import java.util.HashSet;
System.out.println(set);
}
}
// Output: [A, B, C]
D. Sorting Lists
• For the manipulation of data in different collection types, the Java API provides a Collections
class, which is included in the java.util package.
• One (1) of the most popular Collections class methods is sort(), which sorts the elements of
your collection type. The methods in the collections class are static, so you do not need a
Collections object to call them.
• For example:
public class MyClass {
public static void main(String[ ] args) {
ArrayList<String> animals = new
ArrayList<String>();
animals.add("tiger");
animals.add("cat");
animals.add("snake");
animals.add("dog");
Collections.sort(animals);
System.out.println(animals);
}
}
/* Outputs:
[cat, dog, snake, tiger]
*/
• You can call the sort() methods on different types of lists, such as Integer.
import java.util.ArrayList;
import java.util.Collections;
Collections.sort(nums);
System.out.println(nums);
}
}
/* Outputs:
[1, 3, 36, 40, 73]
*/
III. Files
A. Using a File
• The java.io package includes a File class that allows you to work with files.
• To start, create a File object and specify the path of the file in the constructor.
import java.io.File;
...
File file = new File("C:\\data\\input-file.txt");
• With the exists() method, you can determine whether a file exists.
import java.io.File;
B. Reading a File
• Files are useful for storing and retrieving data, and there are a number of ways to read
from a file.
• One (1) of the simplest ways is to use the Scanner class from the java.util package.
• The constructor of the Scanner class can take a File object as input.
• To read the contents of a text file at the path "C:\\Java\\test.txt", you would need to create
a File object with the corresponding path and pass it to the Scanner object.
try {
File x = new File("C:\\files\\test.txt");
Scanner sc = new Scanner(x);
}
catch (FileNotFoundException e) {
}
• The Scanner class inherits from the Iterator, so it behaves like one. You can use the
Scanner object's next() method to read the file's contents.
try {
File x = new File("C:\\files\\test.txt");
Scanner sc = new Scanner(x);
while(sc.hasNext()) {
System.out.println(sc.next());
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println("Error");
}
• The file's contents are output word by word because the next() method returns each word
separately.
C. Creating Files
• Formatter, another useful class in the java.util package, is used to create content and
write it to files.
• For example:
import java.util.Formatter;
D. Writing to Files
• Once the file is created, you can write content to it using the same Formatter object's
format() method.
• For example:
import java.util.Formatter;
References:
Deitel, H. & Deitel, P. (2014). Java: How to program-early objects (10th ed.). Prentice Hall: New
Jersey.
Files. (n.d.). Java programming. Retrieved on March 07, 2018 from https://www.files.com/Play/Java#