Learn Java Programming: How to Use Lists, Threads & Co.
In the last article in our Java series, we explain how to properly handle threads, lists, exceptions and files in Java.
Java: what are exceptions?
If you have not yet worked with Java, you can read our "Basics" here first. Various sample codes can be found in the picture gallery at the end of the article.
- An exception is a problem that occurs while the program is running.
- There is a special code to deal with such a command. To do this, first write "try {" and then the code to be executed. Then write "} catch (Exception e) {" and then various commands to be executed if the previous operation is not possible. Don't forget to add a brace at the end.
- A throw command is also very practical. An example of this is the code »int div (int a, int b) throws« ⮩ »ArithmeticException {« ⮩ »if (b == 0) {« ⮩ »throw new ArithmeticException (" Division by 0! ");« ⮩ »} Else {« ⮩ »return a / b;« ⮩ »}« ⮩ »}«. The throws statement in the method defines which exception type the method can get. The throw keyword determines what should happen with this exception.
- Practical: A single try block can contain several catch blocks.
Use threads in Java
Threads allow you to run different commands in Java at the same time. There are two different ways to create a thread.
- On the one hand, a certain class can inherit from the "Thread" class. For example, first write "class Loader extends Thread {". Then you have to define a method with "public void run () {" which describes the functions of the thread. In another class you can now use the "Loader obj = new Loader ();" command to use the "obj.start ();" method to start the thread.
- Alternatively, you can implement the "Runnable" interface in a class. You can do this with the command "class Loader implements Runnable {". Define a run method again. Now you can start the thread in another class with the code "Thread t = new Thread (new Loader ());" ⮩ "t.start ();"
- Tip: You can use the "Thread.sleep (1000);" command to let the thread rest for a second. However, note that this command generates an InterruptedException.
Create lists in Java
There are two different types of lists in Java: the "ArrayList" and the "LinkedList".
- Typically, arrays in Java can only store a certain number of objects. However, there is a function called "ArrayList" in the Java API. First write "import java.util.ArrayList;" to import the required package. Now you can use the ArrayList colors = new ArrayList (); command to create a new list. Optionally, you can use the ArrayList colors = new ArrayList (10); command to create a list that specifies the data type and size in advance.
- Now you can add something to the list with the command »colors.add (" ... ");«. With »colors.remove (" ... ");« this process can be reversed. You can also use »colors.contains (...);« to inquire whether the list contains a certain element or use the »colors.get (int x);« command to get a value with a certain index. Finally, you can use »colors.size ();« to query the number of elements in the list and use »colors.clear ();« to delete all elements of the list.
- Alternatively, there is also the "LinkedList", which you can import with the command »import java.util.LinkedList;«. The commands are the same here; however, you have to write "LinkedList" each time instead of "ArrayList". An ArrayList is more suitable for storing objects that can be accessed later. You should use a LinkedList if you want to change data.
Java: Use HashMap
In the above lists, each object has an (integer) index. The HashMap is used to store data with a pair of values consisting of "Key" and "Object".
- You import the HashMap with the command »import java.util.HashMap;«. Similar to the lists, you can now create a HashMap with the command »HashMap points = new HashMap ();«.
- Next, for example, you can add the command »points.put (" Amy ", 154);«. The command »System.out.println (" points.get ("Amy")); «now outputs the value 154. Again, you can use remove methods to remove it.
- A HashMap cannot contain objects with two identical keys. An object would simply be overwritten. The "containsKey" and "containsValue" methods are very practical and can be used to check whether an object or a key exists in the HashMap.
- There are also so-called "hash sets". A set is a collection of values, whereby two identical values can never exist. The import java.util.HashSet; command is used to import. For example, you can create a new set with the command »HashSet set = new HashSet ();«. Now you can add elements to this HashSet with the command »set.add (" ... ");«. The command »System.out.println (set);« finally outputs all commands of the set.
- Usually the order of the elements within a hash set is not maintained consistently. However, if you want to, you can use a "LinkedHashSet".
- By the way: A hash table stores information through a mechanism called "hashing", in which every value of a key is used to determine a unique value called "hash code". Simply put, this means that every element of a hash set is linked to a hash code.
Sort lists and use iterators
To work with lists even more efficiently, you can sort them and use iterators.
- The Java API also includes the collections class. One of the most practical methods here is the sort method. All methods of the collections class are static methods, so they do not have to be declared again. For example, if you created an ArrayList named "animal", you can order its values using the Collections.sort (animal); command. You can import the Collections class with the command »import java.util.Collections;«.
- An iterator is an object that circulates through a collection and receives and can delete values. You import the required package with the command »import java.util.iterator;«. In this case we have already created a LinkedList called "animals". You can now define the iterator with the command »Iterator it = animals.iterator ();«. If you now execute the command »System.out.println (it.next ());«, the first element of the LinkedList is output. If you execute the command again, the iterator moves one step further and outputs the second element. Here, too, you can remove elements with a remove method. There is also the hasNext method, which you can use to check whether another element exists.
Java: create and use files
You can easily create and use your own files in Java.
- To do this, you must first import the required package using the "import java.io.File;" command. Then define a file with a suitable path using the command »File file = new File (" C: \\ data \\ input-file.txt ");«. With »if (x.exists ()) {« you can check whether the file exists. You get the name of the file with "x.getName ()".
- In the next step you can create a new scanner with the command »Scanner sc = new Scanner (x);«. Again, you can use commands such as "sc.next ()" or "sc.hasNext ()" to read the data from a file. It works very well in a while loop. Don't forget to close the file with "sc.close ();" at the end.
- To be able to write to files, you must first add the "import java.util.Formatter;" command to your code. The command »Formatter f = new Formatter (" C: \\ CHIP \\ test.txt ");« now creates a file named "test.txt" at the specified path.
- To be able to write to the file, you can use the command »f.format ("% s% s% s, "1", "Max", "Mustermann \ r \ n"); «. % s "for a string that is replaced by the first parameter, the second"% s "by the second parameter, and so on. The program jumps to the next line by pressing" \ r \ n ".
This is where our tutorial series on the Java programming language ends. In the next practical tip, we will give you an introduction to programming with Python.