Module 3: Exceptions, lists and threads Flashcards

1
Q

What is an exception?

A

Exceptions are errors that occur during runtime, they can be caught with the try…catch keywords.

Syntax:

try {
// Some code} catch (Exception e) {
// Some code to handle errors}

  • try (Allows you to define a block of code to be tested for errors)
  • catch (Allows you to define a block of code to be executed, if an error occurs in the try block)

The catch parameters specifies the type of exception/s you are trying to catch, separate multiple by a comma. “Exception e” catches all possible exceptions.

Ex:

public class Test {
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 has occurred!”);}}}

There is also a finally keyword that allows code to be executed regardless of the result of the try…catch statements.

Ex:

public class Test {
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 has occurred!”);} finally {System.out.println(“The try catch is finished.”);}}}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How can you manually generate exceptions?

A

Use the throws and throw keywords. Throws defines the type of exceptions the method can produce, you can use multiple exceptions separated by a comma. Throw generates the corresponding exception with a custom message.

Ex:

public class Program {static int div(int a, int b) throws ArithmeticException {if (b==0) {throw new ArithmeticException(“Division by zero!”);} else {return a/b;}}

Also, single try blocks can have multiple catch blocks. Catch blocks should be organized from most specific to most general. You can use the Exception e to handle all other possible exceptions after the specific ones.

Syntax:

try {
//Some code}
catch (Exceptiontype1 e1) {//Catch block}
catch (Exceptiontype2 e2) {//Catch block}
catch (Exceptiontype3 e3) {//Catch block}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is a thread?

A

A separate thread that runs in parallel to other processes at the same time. Threads can be created in 2 ways:

  1. Extend the Thread class (Inherit from “Thread” class, override its run() method, then create a new object of your class and call the start() method to run the thread)

Ex:

class Loader extends Thread {public void run() {System.out.println(“Hello”);}}

class Test {public static void main(String[] args) {Loader obj = new Loader(); obj.start();}}

  1. Implementing Runnable interface (Implement runnable, override the run() method, create a new thread object with a new class instance (your class) in its constructor, then call the start() method)

Ex:

class Loader implements Runnable {public void run() {System.out.println(“Hello”);}}

class Test {public static void main(String[] args) {Thread t = new Thread(new Loader()); t.start();}}

Implementing runnable is the preferred way to start a thread because it allows you to extend from another class.

Threads have a priority system that determine the order to schedule threads. It ranges from 1-10 and the default is 5, you can change this with the setPriority() method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What’s the difference between runtime and checked exceptions?

A

Checked exceptions are checked when the program compiles, and runtime exceptions are checked when the program is running.

Ex: Checked exception

public class Test {public static void main(String[] args) {try{Thread.sleep(1000);} catch (InterruptedException e) {// Some code}}}

Ex: Runtime exception

public class Program {static int div(int a, int b) throws ArithmeticException {if (b==0) {throw new ArithmeticException(“Division by zero!”);} else {return a/b;}}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is an ArrayList?

A

An array that can change sizes and holds objects. ArrayList is part of the java.util package. You need to use a wrapper class when specifying an ArrayLists data type.

Ex:

import java.util.ArrayList;

ArrayList<Integer> numbers = new ArrayList<Integer>(10);</Integer></Integer>

Some ArrayList methods:

  • add() (Adds new objects)
  • remove() (Removes objects)
  • contains() (Returns true if the list contains the specified element)
  • get(index) (Returns the element at the specified index)
  • set(index, value) (Changes the element at the specified index)
  • size() (Returns the number of elements)
  • clear() (Removes all elements from the list)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a LinkedList?

A

The same as an ArrayList, sharing all the same methods. The difference between an ArrayList and a LinkedList is that objects in a LinkedList are “linked” to neighbouring objects inside the list.

Ex:

import java.util.LinkedList;

LinkedList<Integer> numbers = new LinkedList<Integer>();</Integer></Integer>

You cannot specify an initial capacity in a LinkedList. LinkedList is part of the java.util package. You need to use a wrapper class when specifying a LinkedLists data type.

LinkedList shares the same methods as ArrayList. LinkedList vs ArrayList depends on what you need for your code, use an ArrayList when you need to rapidly access data and use a LinkedList when you need to manipulate/insert/delete data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is a HashMap?

A

A collection of objects stored in “key and value” pairs. HashMap is part of the java.util package. You need to use a wrapper class when specifying a HashMaps data types.

Ex:

import java.util.HashMap;

HashMap<String, Integer> points = new HashMap<String, Integer>();
points.put(“Amy”, 154); points.put(“Dave”, 42); points.put(“Rob”, 105); System.out.println(points.get(“Dave”));

HashMap stores values in pairs, where the first data type is the key and the second data type is the value. HashMaps cannot contain duplicated keys, if you do the new key will overwrite the existing one. To access the HashMap elements use the get method followed by the corresponding key.

Some HashMap methods:

  • get() (Access values)
  • put() (Add values)
  • remove() (Delete values)
  • clear() (Removes all elements)
  • size() (Returns how many elements are in the HashMap)
  • containsKey() (Checks to see if a key with a certain name exists)
  • containsValue() (Checks to see if a value exists)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is a HashSet?

A

A collection of objects that cannot contain duplications. HashSet is part of the java.util package. You need to use a wrapper class when specifying a HashSets data type.

Ex:

import java.util.HashSet;

HashSet<String> set = new HashSet<String>();</String></String>

By default, HashSets do not store items in the order they were added. If you want to remember the order of the elements added, use a LinkedHashSet. LinkedHashSet is part of the java.util package, and it shares the exact same properties as HashSet.

Ex:

import java.util.LinkedHashSet;

LinkedHashSet<String> set = new LinkedHashSet<String>();</String></String>

Some HashSet methods:

  • add() (Adds an item to the set)
  • remove() (Removes an item from the set)
  • clear() (Removes all items from the set)
  • size() (Shows the number of elements in the set)
  • contains() (Checks if an item exists in the set)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you sort items in a list?

A

With the Collections classes methods. Collections is part of the java.util package.

Ex:

import java.util.ArrayList;
import java.util.Collections;

ArrayList<String> animals = new ArrayList<String>(); animals.add(“Tiger”); animals.add(“Cat”); animals.add(“Dog”); Collections.sort(animals); System.out.println(animals);</String></String>

All the methods in Collections are static.

Some Collections methods:

  • reverse(List) (Reverses the sequence)
  • shuffle(List) (Randomizes the elements)
  • sort(List) (Sorts the elements in a list alphabetically)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is an iterator?

A

An object that can be used to loop through collections, obtain or remove elements. Iterator is part of the java.util package. To use an iterator, you need to get one using the iterator method.

Syntax:

Iterator<collection> (iterator name) = (collection name).iterator();</collection>

Ex:

import java.util.ArrayList;
import java.util.Iterator;

ArrayList<String> cars = new ArrayList<String>(); cars.add(“BMW”); cars.add(“Mazda”); cars.add(“Porsche”);
Iterator<String> it = cars.iterator();</String></String></String>

Iterator methods:

  • hasNext() (Returns true if there is at least one more element, either wise returns false)
  • next() (Returns the next element and advances the iterator)
  • remove() (Removes the last element that was returned by next from the collection)

Iterators are commonly used in loops:

Ex loop:

while(it.hasNext()) {System.out.println(it.next())

This checks to see if the iterator has additional elements, then prints the current element and moves on to the next one.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly