[go: up one dir, main page]

0% found this document useful (0 votes)
3 views7 pages

09 Handout 1

The document covers exceptions in Java, explaining exception handling using try and catch blocks, the throw statement, and how to manage multiple exceptions. It also introduces the Collections Framework, detailing ArrayLists, Maps, and Sets, including methods for manipulating these collections. Additionally, it discusses file handling in Java, including creating, reading, and writing to files using the File and Formatter classes.

Uploaded by

forestparty223
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views7 pages

09 Handout 1

The document covers exceptions in Java, explaining exception handling using try and catch blocks, the throw statement, and how to manage multiple exceptions. It also introduces the Collections Framework, detailing ArrayLists, Maps, and Sets, including methods for manipulating these collections. Additionally, it discusses file handling in Java, including creating, reading, and writing to files using the File and Formatter classes.

Uploaded by

forestparty223
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

SH1801

Exceptions, Collections Framework, and Files


I. Exceptions
An exception is an event that occurs during the execution of a program that disrupts the normal
flow of instructions.

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"

B. The throw Statement


• A throw statement sends an exception out of a block or a method so it can be handled
elsewhere.
• For example:
int div(int a, int b) throws ArithmeticException {
if(b == 0) {
throw new ArithmeticException("Division by Zero");
} else {
return a / b;
}
}

C. Multiple Exceptions
• Only one (1) try block is accepted in a program but there can be multiple catch blocks.
• For example:

09 Handout 1 *Property of STI


 student.feedback@sti.edu Page 1 of 7
SH1801

II. The Collections Framework


The Java platform includes a collections framework. A collection is an object that represents a
group of objects. A collections framework is a unified architecture for representing and
manipulating collections, enabling collections to be manipulated independently of implementation
details.
• The collections framework consists of collection interfaces, which represent different
types of collections. These interfaces form the basis of the framework. These interfaces
are included in the java.util package. The following are commonly used interfaces:
A. ArrayList
• Standard Java arrays are of a fixed length, which means that after they are created, they
cannot expand or shrink.
• The ArrayList class provides methods to manipulate the size of the array that is used
internally to store the list.
• Create an ArrayList as you would with any object.
import java.util.ArrayList;
//...
ArrayList colors = new ArrayList();
• You can optionally specify a capacity and type of objects the ArrayList will hold:
ArrayList<String> colors = new ArrayList<String>(10);
• The code above defines an ArrayList of Strings with 10 as its initial size.
• The ArrayList class provides a number of useful methods for manipulating its objects. The
add() method inserts new objects to the ArrayList. Conversely, the remove() method
deletes the objects from the ArrayList.
import java.util.ArrayList;

public class MyClass {


public static void main(String[ ] args) {

09 Handout 1 *Property of STI


 student.feedback@sti.edu Page 2 of 7
SH1801

ArrayList<String> colors = new ArrayList<String>();


colors.add("Red");
colors.add("Blue");
colors.add("Green");
colors.add("Orange");
colors.remove("Green");

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;

public class MyClass {


public static void main(String[ ] args) {
HashSet<String> set = new HashSet<String>();
set.add("A");
set.add("B");
set.add("C");

09 Handout 1 *Property of STI


 student.feedback@sti.edu Page 3 of 7
SH1801

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;

public class MyClass {


public static void main(String[ ] args) {
ArrayList<Integer> nums = new ArrayList<Integer>();
nums.add(3);
nums.add(36);
nums.add(73);
nums.add(40);
nums.add(1);

Collections.sort(nums);
System.out.println(nums);
}
}
/* Outputs:
[1, 3, 36, 40, 73]
*/

09 Handout 1 *Property of STI


 student.feedback@sti.edu Page 4 of 7
SH1801

• Other useful methods in the Collection class:


o max(Collection c) - returns the maximum element in c as determined by natural ordering
o min(Collection c) - returns the minimum element in c as determined by natural ordering
o reverse(List list) - reverses the sequences in the list
o shuffle(List list) - shuffles (i.e., randomizes) the elements in the list

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;

public class MyClass {


public static void main(String[ ] args) {
File x = new File("C:\\files\\test.txt");
if(x.exists()) {
System.out.println(x.getName() + "exists!");
}
else {
System.out.println("The file does not exist");
}
}
}

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());
}

09 Handout 1 *Property of STI


 student.feedback@sti.edu Page 5 of 7
SH1801

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;

public class MyClass {


public static void main(String[ ] args) {
try {
Formatter f = new Formatter("C:\\files\\test.txt");
} catch (Exception e) {
System.out.println("Error");
}
}
}
• This creates an empty file at the specified path. If the file already exists, this will
overwrite it.

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;

public class MyClass {


public static void main(String[ ] args) {
try {
Formatter f = new Formatter("C:\\files\\test.txt");
f.format("%s %s %s", "1","John", "Smith \r\n");
f.format("%s %s %s", "2","Amy", "Brown");
f.close();
} catch (Exception e) {
System.out.println("Error");
}
}
}
• The format() method formats its parameters according to its first parameter. %s means a
string and gets replaced by the first parameter after the format. The second %s gets
replaced by the next one, and so on. So, the format %s %s %s denotes three (3) strings
that are separated by spaces. Note: \r\n is the newline symbol in Windows.
• The code above creates a file with the following content:
1 John Smith
2 Amy Brown

09 Handout 1 *Property of STI


 student.feedback@sti.edu Page 6 of 7
SH1801

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#

09 Handout 1 *Property of STI


 student.feedback@sti.edu Page 7 of 7

You might also like