Java ArrayList
The ArrayList class is a resizable array, which can be found in
the [Link] package.
Create an ArrayList object called cars that will store strings:
import [Link]; // import the ArrayList class
ArrayList<String> cars = new ArrayList<String>(); // Create an ArrayList
object
The ArrayList class has many useful methods. For example, to add elements to
the ArrayList, use the add() method:
import [Link];
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
[Link]("Volvo");
[Link]("BMW");
[Link]("Ford");
[Link]("Mazda");
[Link](cars);
1
• To access an element in the ArrayList, use the get() method and refer
to the index number
• To modify an element, use the set() method and refer to the index
number
• To remove an element, use the remove() method and refer to the index
number
• To find out how many elements an ArrayList have, use the size method
Loop through the elements of an ArrayList with a for loop, and use
the size() method to specify how many times the loop should run:
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
[Link]("Volvo");
[Link]("BMW");
[Link]("Ford");
[Link]("Mazda");
for (int i = 0; i < [Link](); i++) {
[Link]([Link](i));
Create an ArrayList to store numbers (add elements of type Integer):
import [Link];
public class Main {
public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
2
[Link](10);
[Link](15);
[Link](20);
[Link](25);
for (int i : myNumbers) {
[Link](i);
Another useful class in the [Link] package is the Collections class,
which include the sort() method for sorting lists alphabetically or
numerically:
import [Link];
import [Link]; // Import the Collections class
public class Main {
public static void main(String[] args) {
ArrayList<String> cars = new ArrayList<String>();
[Link]("Volvo");
[Link]("BMW");
[Link]("Ford");
[Link]("Mazda");
[Link](cars); // Sort cars
for (String i : cars) {
[Link](i);
3
}
import [Link];
import [Link]; // Import the Collections class
public class Main {
public static void main(String[] args) {
ArrayList<Integer> myNumbers = new ArrayList<Integer>();
[Link](33);
[Link](15);
[Link](20);
[Link](34);
[Link](8);
[Link](12);
[Link](myNumbers); // Sort myNumbers
for (int i : myNumbers) {
[Link](i);
4
Java LinkedList
• The ArrayList class has a regular array inside it. When an element is added,
it is placed into the array. If the array is not big enough, a new, larger array
is created to replace the old one and the old one is removed.
• The LinkedList stores its items in "containers." The list has a link to the first
container and each container has a link to the next container in the list. To
add an element to the list, the element is placed into a new container and
that container is linked to one of the other containers in the list.
• Use an ArrayList for storing and accessing data, and LinkedList to
manipulate data.
LinkedList Methods
Java HashMap
In the ArrayList chapter, you learned that Arrays store items as an ordered
collection, and you have to access them with an index number (int type).
A HashMap however, store items in "key/value" pairs, and you can access them
by an index of another type (e.g. a String).
5
One object is used as a key (index) to another object (value). It can store
different types: String keys and Integer values, or the same type,
like: String keys and String values:
Create a HashMap object called capitalCities that will
store String keys and String values:
import [Link]; // import the HashMap class
HashMap<String, String> capitalCities = new HashMap<String, String>();
• The HashMap class has many useful methods. For example, to add items
to it, use the put() method
• To access a value in the HashMap, use the get() method and refer to its
key
• To remove an item, use the remove() method and refer to the key
• To remove all items, use the clear() method
• To find out how many items there are, use the size() method
Loop Through a HashMap
Loop through the items of a HashMap with a for-each loop.
Note: Use the keySet() method if you only want the keys, and use
the values() method if you only want the values:
Example
// Print keys
for (String i : [Link]()) {
[Link](i);
// Print keys and values
for (String i : [Link]()) {
6
[Link]("key: " + i + " value: " + [Link](i));
Create a HashMap object called people that will
store String keys and Integer values:
// Import the HashMap class
import [Link];
public class Main {
public static void main(String[] args) {
// Create a HashMap object called people
HashMap<String, Integer> people = new HashMap<String, Integer>();
// Add keys and values (Name, Age)
[Link]("John", 32);
[Link]("Steve", 30);
[Link]("Angie", 33);
for (String i : [Link]()) {
[Link]("key: " + i + " value: " + [Link](i));
7
Java HashSet
• A HashSet is a collection of items where every item is unique, and it is
found in the [Link] package
• The HashSet class has many useful methods. For example, to add items
to it, use the add() method
• To check whether an item exists in a HashSet, use
the contains() method
• To remove an item, use the remove() method
• To remove all items, use the clear() method
• To find out how many items there are, use the size method
•
// Import the HashSet class
import [Link];
public class Main {
public static void main(String[] args) {
HashSet<String> cars = new HashSet<String>();
[Link]("Volvo");
[Link]("BMW");
[Link]("Ford");
[Link]("BMW");
[Link]("Mazda");
[Link](cars);
8
Example
Use a HashSet that stores Integer objects:
import [Link];
public class Main {
public static void main(String[] args) {
// Create a HashSet object called numbers
HashSet<Integer> numbers = new HashSet<Integer>();
// Add values to the set
[Link](4);
[Link](7);
[Link](8);
// Show which numbers between 1 and 10 are in the set
for(int i = 1; i <= 10; i++) {
if([Link](i)) {
[Link](i + " was found in the set.");
} else {
[Link](i + " was not found in the set.");
9
Java Iterator
An Iterator is an object that can be used to loop through collections,
like ArrayList and HashSet. It is called an "iterator" because "iterating" is the
technical term for looping.
To use an Iterator, you must import it from the [Link] package.
• To loop through a collection, use the hasNext() and next() methods of
the Iterator
• Iterators are designed to easily change the collections that they loop
through. The remove() method can remove items from a collection while
looping.
// Import the ArrayList class and the Iterator class
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
// Make a collection
ArrayList<String> cars = new ArrayList<String>();
[Link]("Volvo");
[Link]("BMW");
[Link]("Ford");
[Link]("Mazda");
10
// Get the iterator
Iterator<String> it = [Link]();
// Print the first item
[Link]([Link]());
Example
Use an iterator to remove numbers less than 10 from a collection:
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
ArrayList<Integer> numbers = new ArrayList<Integer>();
[Link](12);
[Link](8);
[Link](2);
[Link](23);
Iterator<Integer> it = [Link]();
while([Link]()) {
Integer i = [Link]();
if(i < 10) {
[Link]();
11
}
[Link](numbers);
Another useful method is the toString() method, which is used to convert
wrapper objects to strings.
In the following example, we convert an Integer to a String, and use
the length() method of the String class to output the length of the "string":
Example
public class Main {
public static void main(String[] args) {
Integer myInt = 100;
String myString = [Link]();
[Link]([Link]());
Java Exceptions
When executing Java code, different errors can occur: coding errors made by
the programmer, errors due to wrong input, or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error message.
The technical term for this is: Java will throw an exception (throw an error).
Java try and catch
12
The try statement allows you to define a block of code to be tested for errors
while it is being executed.
The catch statement allows you to define a block of code to be executed, if an
error occurs in the try block.
The try and catch keywords come in pairs
The finally statement lets you execute code, after try...catch, regardless of
the result
The throw statement allows you to create a custom error.
The throw statement is used together with an exception type. There are many
exception types available in
Java: ArithmeticException, FileNotFoundException, ArrayIndexOutOfBoundsException , Secu
rityException, etc:
Syntax
try {
// Block of code to try
catch(Exception e) {
// Block of code to handle errors
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least
18 years old.");
13
}
else {
[Link]("Access granted - You are old enough!");
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
Java Regular Expressions
What is a Regular Expression?
A regular expression is a sequence of characters that forms a search pattern.
When you search for data in a text, you can use this search pattern to describe
what you are searching for.
A regular expression can be a single character, or a more complicated pattern.
Regular expressions can be used to perform all types of text search and text
replace operations.
Java does not have a built-in Regular Expression class, but we can import
the [Link] package to work with regular expressions. The package
includes the following classes:
• Pattern Class - Defines a pattern (to be used in a search)
• Matcher Class - Used to search for the pattern
• PatternSyntaxException Class - Indicates syntax error in a regular
expression pattern
14
Example
Find out if there are any occurrences of the word "w3schools" in a sentence:
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
Pattern pattern = [Link]("w3schools",
Pattern.CASE_INSENSITIVE);
Matcher matcher = [Link]("Visit W3Schools!");
boolean matchFound = [Link]();
if(matchFound) {
[Link]("Match found");
} else {
[Link]("Match not found");
// Outputs Match found
Example Explained
In this example, The word "w3schools" is being searched for in a sentence.
First, the pattern is created using the [Link]() method. The first
parameter indicates which pattern is being searched for and the second
parameter has a flag to indicates that the search should be case-insensitive.
The second parameter is optional.
15
The matcher() method is used to search for the pattern in a string. It returns a
Matcher object which contains information about the search that was
performed.
The find() method returns true if the pattern was found in the string and false if
it was not found.
Flags
Flags in the compile() method change how the search is performed. Here are a
few of them:
• Pattern.CASE_INSENSITIVE - The case of letters will be ignored when
performing a search.
• [Link] - Special characters in the pattern will not have any
special meaning and will be treated as ordinary characters when
performing a search.
• Pattern.UNICODE_CASE - Use it together with the CASE_INSENSITIVE flag
to also ignore the case of letters outside of the English alphabet
Java Threads
Threads allows a program to operate more efficiently by doing multiple things at
the same time.
Threads can be used to perform complicated tasks in the background without
interrupting the main program.
There are two ways to create a thread.
It can be created by extending the Thread class and overriding its run() method:
Extend Syntax
public class Main extends Thread {
public void run() {
[Link]("This code is running in a thread");
16
}
Another way to create a thread is to implement the Runnable interface:
Implement Syntax
public class Main implements Runnable {
public void run() {
[Link]("This code is running in a thread");
Running Threads
If the class extends the Thread class, the thread can be run by creating an
instance of the class and call its start() method:
Extend Example
public class Main extends Thread {
public static void main(String[] args) {
Main thread = new Main();
[Link]();
[Link]("This code is outside of the thread");
public void run() {
[Link]("This code is running in a thread");
17
Concurrency Problems
Because threads run at the same time as other parts of the program, there is
no way to know in which order the code will run. When the threads and main
program are reading and writing the same variables, the values are
unpredictable. The problems that result from this are called concurrency
problems.
o avoid concurrency problems, it is best to share as few attributes between
threads as possible. If attributes need to be shared, one possible solution is to
use the isAlive() method of the thread to check whether the thread has
finished running before using any attributes that the thread can change.
Use isAlive() to prevent concurrency problems:
public class Main extends Thread {
public static int amount = 0;
public static void main(String[] args) {
Main thread = new Main();
[Link]();
// Wait for the thread to finish
while([Link]()) {
[Link]("Waiting...");
// Update amount and print its value
[Link]("Main: " + amount);
amount++;
[Link]("Main: " + amount);
18
public void run() {
amount++;
Java Lambda Expressions
A lambda expression is a short block of code which takes in parameters and
returns a value. Lambda expressions are similar to methods, but they do not
need a name and they can be implemented right in the body of a method.
Syntax
The simplest lambda expression contains a single parameter and an expression:
parameter -> expression
Expressions are limited. They have to immediately return a value, and they
cannot contain variables, assignments or statements such as if or for. In order
to do more complex operations, a code block can be used with curly braces. If
the lambda expression needs to return a value, then the code block should have
a return statement.
(parameter1, parameter2) -> { code block }
Create a File
To create a file in Java, you can use the createNewFile() method. This method
returns a boolean value: true if the file was successfully created, and false if the
file already exists. Note that the method is enclosed in a try...catch block. This
is necessary because it throws an IOException if an error occurs (if the file cannot
be created for some reason):
19
Example
import [Link]; // Import the File class
import [Link]; // Import the IOException class to handle
errors
public class CreateFile {
public static void main(String[] args) {
try {
File myObj = new File("[Link]");
if ([Link]()) {
[Link]("File created: " + [Link]());
} else {
[Link]("File already exists.");
} catch (IOException e) {
[Link]("An error occurred.");
[Link]();
Write To a File
In the following example, we use the FileWriter class together with
its write() method to write some text to the file we created in the example
above. Note that when you are done writing to the file, you should close it with
the close() method:
20
Example
import [Link]; // Import the FileWriter class
import [Link]; // Import the IOException class to handle
errors
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("[Link]");
[Link]("Files in Java might be tricky, but it is fun
enough!");
[Link]();
[Link]("Successfully wrote to the file.");
} catch (IOException e) {
[Link]("An error occurred.");
[Link]();
In the following example, we use the Scanner class to read the contents of the
text file we created in the previous chapter:
Example
import [Link]; // Import the File class
21
import [Link]; // Import this class to handle
errors
import [Link]; // Import the Scanner class to read text files
public class ReadFile {
public static void main(String[] args) {
try {
File myObj = new File("[Link]");
Scanner myReader = new Scanner(myObj);
while ([Link]()) {
String data = [Link]();
[Link](data);
[Link]();
} catch (FileNotFoundException e) {
[Link]("An error occurred.");
[Link]();
Delete a File
To delete a file in Java, use the delete() method:
22
Example
import [Link]; // Import the File class
public class DeleteFile {
public static void main(String[] args) {
File myObj = new File("[Link]");
if ([Link]()) {
[Link]("Deleted the file: " + [Link]());
} else {
[Link]("Failed to delete the file.");
23