[toc]
Control flow statements in Java--conditonals and loops--are very straightforward. They pretty much work the same as the do in JavaScript.
if (condition) {
//statement1
//statement2
//...
}if (condition) {
//statement1
//statement2
//...
} else {
//statement3
//statement4
//...
}import java.util.Scanner;
public class ElseIf {
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a grade: ");
int grade = in.nextInt();
if (grade < 60) {
System.out.println('F');
} else if (grade < 70) {
System.out.println('D');
} else if (grade < 80) {
System.out.println('C');
} else if (grade < 90) {
System.out.println('B');
} else {
System.out.println('A');
}
}
}Java also suports the switch statement. JavaScript has this too. Bash calls this the case statement.
A switch statement that acts something like an else if statement under certain conditions, called cases. The switch statement is not used very often, and we generally recommend you avoid using it. It is not as powerful as the else if model because the switch variable can only be compared for equality with a very small class of types. Also, if we've learned anything from using Objects in JavaScript, we know there's a better way to call functions up like key-values.
Still, they can be useful.
import java.util.Scanner;
public class DayPrinter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter an integer: ");
int dayNum = in.nextInt();
String day;
switch (dayNum) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
break;
default:
// in this example, this block runs if none of the above blocks match
day = "Int does not correspond to a day of the week";
}
System.out.println(day);
}
}Using the example above, if we input the number 4, the output will be Thursday.
Enter an integer: 4
Thursday
If we entered 10 the default case is used. This case is a catch-all for all other cases that aren't defined.
Enter an integer: 10
Int does not correspond to a day of the weekThe equlivalent version of the code sample above in else if form, looks like this.
import java.util.Scanner;
public class DayPrinter {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter an integer: ");
int dayNum = in.nextInt();
String day;
if (dayNum == 0) {
day = "Sunday";
} else if (dayNum == 1){
day = "Monday";
} else if (dayNum == 2){
day = "Tuesday";
} else if (dayNum == 3){
day = "Wednesday";
} else if (dayNum == 4){
day = "Thursday";
} else if (dayNum == 5){
day = "Friday";
} else if (dayNum == 6){
day = "Saturday";
} else {
day = "Int does not correspond to a day of the week";
}
System.out.println(day);
}
}🎗️ TODO: Show what this would look like if we used an Array or ArrayList.
Additionally, if break statements are omitted from the individual cases on accident, a behavior known as fallthrough is carried out. Fallthrough can be quite unintuitive, and is only desirable in very specific circumstances. We will discuss break statements in more detail in the loop section below. For now, just know that when used in a switch block, they terminate the switch statement they are in, so the flow of control in your program moves to the next statement after the switch block.
Here’s a quick example of how fallthrough works with our switch example but no breaks:
import java.util.Scanner;
public class DayPrinter {
public static void main(String[] args) {
System.out.println("Enter an integer: ");
Scanner in = new Scanner(System.in);
int dayNum = in.nextInt();
String day;
switch (dayNum) {
case 0:
day = "Sunday";
case 1:
day = "Monday";
case 2:
day = "Tuesday";
case 3:
day = "Wednesday";
case 4:
day = "Thursday";
case 5:
day = "Friday";
case 6:
day = "Saturday";
default:
// in this example, this block runs even if one of the above blocks match
day = "Int does not correspond to a day of the week";
}
System.out.println(day);
}
}This time, without the break statements in each case, if the user enters 4, they will see the default output:
Enter an integer: 4
Int does not correspond to a day of the week
This is because after the switch statement matches the case for 4 and assigns the value Thursday to the variable day, it proceeds to execute every statement in every case that follows, all the way through the default case. So the String that ends up being printed will reflect the last executed statement in the switch block.
Along similar lines, consider this variation on the code block above:
import java.util.Scanner;
public class DayPrinter {
public static void main(String[] args) {
System.out.println("Enter an integer: ");
Scanner in = new Scanner(System.in);
int dayNum = in.nextInt();
String day;
switch (dayNum) {
case 0:
day = "Sunday";
case 1:
day = "Monday";
case 2:
day = "Tuesday";
case 3:
day = "Wednesday";
case 4:
day = "Thursday";
case 5:
day = "Friday";
case 6:
day = "Saturday";
break;
default:
day = "Int does not correspond to a day of the week";
}
System.out.println(day);
}
}Here, we have a break statement in case 6 after day = "Saturday";. If the user enters 4, the execution will fallthrough until it reaches that break statement and Saturday is printed instead of Thursday. The output:
Enter an integer: 4
Saturday
[^ ifelse ]: The if-then and if-then-else Statements [^ switch]: The switch Statement
In Java we write a definite loop (a.k.a. for loop) as:
for (int i = 0; i < 10; i++ ) {
System.out.println(i);
}0
1
2
3
4
5
6
7
8
9
Note: You may not be familiar with the expression
i++since it is not found in all languages. The++is an increment operator that has the same effect asi += 1. In this example, since the++comes afteri, we call it a postfix increment operator. There is also a--decrement operator in Java. For more information, see Increment and Decrement Operators.
==The Java for loop gives you explicit control over the starting, stopping, and stepping of the loop variable inside the parentheses.== You can think of it this way:
for (start_clause; stop_clause; step_clause) {
//statement1
//statement2
//...
}If you want to start at 100, stop at 0 and count backward by 5, the loop is written as:
for (int i = 100; i >= 0; i -= 5) {
System.out.println(i);
}100
95
90
...
🎗️ TODO: Find out when this syntax was introduced.
Java also provides a syntax to iterate over any sequence or collection, such as an Array:
int nums[] = {1, 1, 2, 3, 5, 8, 13, 21};
for (int i : nums) {
System.out.println(i);
}Here, the loop variable moves through the items in the Array of integers, nums[]. The syntax here uses a colon symbol, :. This type of loop is known as a for-each loop.
Tip: When considering structure, it can be helpful to read the code sample above to yourself as "Forea each integer in
Array nums...".
This loop version also works with a String, where we can convert the String to an Array of characters:
String msg = "Hello World";
for(char c : msg. toCharArray()){
System.out.println(c);
}As you see, to iterate through a String in this way, Java requires an extra String method, .toCharArray(), to convert the String to an Array of characters.
Java also supports the while loop, or indefinite loop.
int i = 0;
while(i < 3){
i++
}Java adds an additional, if seldom used, variation of the while loop called the do-while loop. The do-while loop is very similar to while except that the condition is evaluated at the end of the loop rather than the beginning. This ensures that a loop will be executed at least one time. Some programmers prefer this loop in some situations because it avoids an additional assignment prior to the loop.
do {
System.out.println("Hello, World");
} while (false);Hello, World
Above, the message prints despite the condition never being met.
There are instances where you may want to terminate a loop if a given condition is met. In these instances, the break statement comes in handy. For example, say you want to loop through an Array of integers to search for a given value. Once that number is found, you want to quit the loop. You can do the following:
public class testBreak {
public static void main(String [] args) {
int[] someInts = {1, 10, 2, 3, 5, 8, 10};
int searchTerm = 10;
for (int oneInt : someInts) {
if (oneInt == searchTerm) {
System.out.println("Found it!");
break;
}
}
}
}In the code above, instead of the for loop iterating through all the integers in the array, it will stop after it finds the first matching instance. So once it finds the first 10 in the array, it prints “Found it!” and then terminates the loop. If the break statement weren’t there, the loop would continue and when it found the second 10, it would print “Found it!” a second time.
Note that the break statement terminates the innermost loop that it is contained within. So if you have nested loops and use a break statement within the innermost loop, then it will only terminate that loop and not the outer one. If a break is present in the outer loop, it — and any other block nested within it — is terminated when the break runs.
The continue statement is similar to, but importantly different from, the break statement. Like break, it interrupts the normal flow of control of the loop. But unlike break, the continue statement only terminates the current iteration of the loop. So the loop will continue to run from the top (as long as the boolean expression that controls the loop is still true) after a continue statement. Here is an example:
public class testContinue {
public static void main(String [] args) {
int[] someInts = {1, 10, 2, 3, 5, 8, 10};
int searchTerm = 10;
for (int oneInt : someInts) {
if (oneInt == searchTerm) {
System.out.println("Found it!");
continue;
}
System.out.println("Not here");
}
}
}The above program will print “Not here” on every iteration of the for loop except where the number has been found. So the output looks like this:
Not here
Found it!
Not here
Not here
Not here
Not here
Found it!
Because of the continue statement, the final print statement in the for loop is skipped. If the continue statement weren’t there, the output would look like this instead (notice the extra “Not here” printouts):
Not here
Found it!
Not here
Not here
Not here
Not here
Not here
Found it!
Not here
- The for statement (docs.oracle.com)
- The while and do-while Statements (docs.oracle.com)
- Break and Continue Statements (docs.oracle.com)
- Summary of Control Flow Statements (docs.oracle.com)
==A data structure lets us hold on to lots of data in a single place. It is a programming construct to aggregate lots of values into one value.== Many types of data structures exist in various languages. A few examples are lists, dictionaries, arrays, tuples, etc.
Java provides powerful and flexible structures to store data, known as collections. The Java collections framework refers to the various interfaces the language provides for implementing collection types.
Here, we’ll discuss a collection called ArrayList and compare it to the Array class. We’ll then introduce a third collection type called HashMap. These three collection types will be sufficient for our basic Java needs. For more, refer to the official Java documentation on collections.
We’ll explore collections in Java by looking at different versions of the same program. The program functions as a gradebook, allowing a user (a professor or teacher) to enter the class roster for a course, along with each student’s grade. It then prints the class roster along with the average grade. In each variation of this program, the grading system could be anything numeric, such as a 0.0-4.0 point scale, or a 0-100 percentage scale.
A test run of the program might yield the following:
Enter your students (or ENTER to finish):
Chris
Jesse
Sally
Grade for Chris: 3.0
Grade for Jesse: 4.0
Grade for Sally: 3.5
Class roster:
Chris (3.0)
Jesse (4.0)
Sally (3.5)
Average grade: 3.5
We’ll look at the gradebook using an Arraylist first.
To write an ArrayList version of the program, we will have to introduce several new Java concepts, including the class ArrayList. We will also review different kinds of for loops used in Java.
Before going any further, we suggest you run the ArrayListGradebook program in IntelliJ. You can view this program in java-web-dev-exercises. Once you’ve done that, let’s look at what is happening in the Java source code.
package org.launchcode.java.demos.collections;
import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListGradebook {
public static void main(String[] args) {
ArrayList<String> students = new ArrayList<>();
ArrayList<Double> grades = new ArrayList<>();
Scanner input = new Scanner(System.in);
String newStudent;
System.out.println("Enter your students (or ENTER to finish):");
// Get student names
do {
newStudent = input.nextLine();
if (!newStudent.equals("")) {
students.add(newStudent);
}
} while(!newStudent.equals(""));
// Get student grades
for (String student : students) {
System.out.print("Grade for " + student + ": ");
Double grade = input.nextDouble();
grades.add(grade);
}
// Print class roster
System.out.println("\nClass roster:");
double sum = 0.0;
for (int i = 0; i < students.size(); i++) {
System.out.println(students.get(i) + " (" + grades.get(i) + ")");
sum += grades.get(i);
}
double avg = sum / students.size();
System.out.println("Average grade: " + avg);
}
}Here we declare and initialize two objects, students and grades, which appear to be of type ArrayList and ArrayList, respectively. An ArrayList in Java is very similar to an Array. Like an Array, we must let the compiler know what kind of objects our ArrayList is going to contain. In the case of students, the ArrayList will contain values of type String (representing the names of the students), so we use the ArrayList syntax to inform the compiler that we intend to fill our list with Strings. Similarly, grades will hold exclusively values of type Double and is declared to be of type ArrayList.
⚠️ Warning! Notice that we declaredgradesto be of typeArrayList, using the wrapper classDoublerather than the primitive typedouble. All values stored in Java collections must be objects, so we’ll have to use object types in those situations.
In lines 10 and 11, we also initialize each list by creating a new, empty list. Note that when we call the ArrayList constructor, as in new ArrayList<>(), we don’t need to specify type (it’s implicit in the left-hand side of the assignment).
Note: You will sometimes see the
ArrayListclass written asArrayList<E>, whereErepresents a placeholder for the type that a programmer will declare a given list to hold. This is especially true in documentation. You can think ofEas representing an arbitrary type.Classes like
ArrayList<E>that take another type or class as a parameter are referred to as generic classes or generic types.
We then use a do-while loop to collect the names of each of the students in the class.
/* Lines 18 through 26 */
// Get student names
do {
newStudent = input.nextLine();
if (!newStudent.equals("")) {
students.add(newStudent);
}
} while(!newStudent.equals(""));Recall that a do-while loop is very similar to a while loop, but the execution condition is checked at the end of the loop block. This has the net effect that the code block will always run at least once. In this example, we prompt the user for a name, which Java processes via input.nextLine() when the user hits the enter key. To finish entering names, the user enters a blank line.
For each student that is entered (that is, each non-empty line), we add the new String to the end of our list with students.add(newStudent). The .add() method is provided by the ArrayList Class. There are lots of other ArrayList methods to get familiar with, some of which we will discuss in more detail below.
Note that our program imports java.util.ArrayList to take advantage of this Java provided class.
Below the do-while loop are two different loops that demonstrate two ways you can loop through a list in Java. Here’s the first, which collects the numeric grade for each student:
/* Lines 27 through 32 */
// Get student grades
for (String student : students) {
System.out.print("Grade for " + student + ": ");
Double grade = input.nextDouble();
grades.add(grade);
}This, you may recall, is Java’s for-each loop syntax. You may read this in your head, or even aloud, as: for each student in students. As you might expect at this point, we must declare the iterator variable student with its data type.
The next loop on display prints out each student’s name and grade:
/* Lines 34 through 41 */
// Print class roster
System.out.println("\nClass roster:");
double sum = 0.0;
for (int i = 0; i < students.size(); i++) {
System.out.println(students.get(i) + " (" + grades.get(i) + ")");
sum += grades.get(i);
}Here, we introduce the syntax students.size() which utilizes the size() method of ArrayList. This method returns the integer representing the number of items in the list. This is similar to String’s .length() method.
In this for loop, we use a loop index to define the starting point, ending point, and increment for iteration. It may be helpful for you to consider this kind of construction as something like, for integer i in the range of the number of items in students.... The first statement inside the parenthesis declares and initializes a loop index variable i. The second statement is a Boolean expression that is our exit condition. In other words, we will keep looping as long as this expression evaluates to true. The third statement is used to increment the value of the loop index variable at the end of iteration through the loop.
Again, the syntax i++ is Java shorthand for i = i + 1. Java also supports the shorthand i-- to decrement the value of i. We can also write i += 2 as shorthand for i = i + 2.
In the final lines of the program, we compute the average grade for all students:
/* Lines 43 through 44 */
double avg = sum / students.size();
System.out.println("Average grade: " + avg);🎗️ TODO: See if there is a
.reduce()function that creates the sum like one would use it for in JavaScript.
Let’s gather up a few of the ArrayList methods that we’ve encountered so far, along with a few new ones. While these will be the most common methods and properties that you use with this class, they by no means represent a complete list. Refer to the official documentation on the ArrayList class for such a list, and for more details.
To demonstrate the use of these methods, we’ll create a new ArrayList called planets.
ArrayList<String> planets = new ArrayList<>();Ok, we’ve got an empty ArrayList. We need to use the class’s .add() method to populate this collection with items.
NOTE: There are other means to declare and initialize an ArrayList in fewer lines. These require knowledge of other collections types, so we’ll stick with
.add()for the time being.
Using .add() to populate planets:
planets.add("Mercury");
planets.add("Venus");
planets.add("Earth");
planets.add("Mars");
planets.add("Jupiter");
planets.add("Saturn");
planets.add("Uranus");
planets.add("Neptune");Thus, the first item in this table:
| Java Syntax | Description | Example |
|---|---|---|
add() |
Adds an item to the ArrayList |
planets.add("Pluto") adds Pluto to planets |
size() |
Returns the number of items in an ArrayList, as an int |
planets.size() returns 9 |
contains() |
Checks to see if the ArrayList contains a given item, returning a Boolean |
planets.contains("Earth") returns true |
indexOf() |
Looks for an item in an ArrayList, returns the index of the first occurrence of the item if it exists, otherwise returns -1. |
planets.indexOf("Jupiter") returns 4 |
Here’s a couple more methods that require slightly longer descriptions:
| Java Syntax | Description | Example |
|---|---|---|
Collection.sort() |
Rearranges the elements of a Collection into ascending order. |
Collections.sort(planets) produces ["Earth", "Jupiter", "Mars", "Mercury", "Neptune", "Pluto", "Saturn", "Uranus", "Venus"] |
This method is technically used on Java’s Collections class and thus requires a different import statement:
import java.util.Collections;Collections is itself a member of the collections framework but not all members of the framework are instances of this class. We include this method here because, should you be in the market for a sorting method, this is a helpful one to know.
| Java Syntax | Description | Example |
|---|---|---|
toArray() |
Returns an Array containing hte elements of the ArrayList |
planets.toArray(planetsArray) returns {"Earth", "Jupiter", "Mars", "Mercury", "Neptune", "Pluto", "Saturn", "Uranus", "Venus"} |
Perhaps you recall that in Java, you must know the size of the Array when you create it. So we’ll need to first define the new Array before we can use toArray().
String[] planetsArray = new String[planets.size()];
planets.toArray(planetsArray);Speaking of Arrays, let’s see the Array version of Gradebook next.
We learned about arrays in Java in a previous lesson, so let’s spend a moment comparing them to ArrayLists. ArrayLists are generally easier to use than Java’s Array. Let’s see why this is.
Why does Java have both Arrays and ArrayLists? The answer is historical, at least in part. Java is a C-style language, and arrays are the most basic data structure in C. Using an Array over an ArrayList might be preferred in some circumstances, primarily for performance reasons (array operations are generally faster than ArrayList operations). Also note that Arrays are of fixed size. You cannot expand or contract an Array after it is created, so you must know exactly how many elements it will need to hold when you create it. This fact is reason enough to use ArrayLists in most scenarios.
To illustrate Array usage, here is a version of the Gradebook program using Arrays instead of ArrayLists:
package org.launchcode.java.demos.collections;
import java.util.Scanner;
public class ArrayGradebook {
public static void main(String[] args) {
// Allow for at most 30 students
int maxStudents = 30;
String[] students = new String[maxStudents];
double[] grades = new double[maxStudents];
Scanner input = new Scanner(System.in);
String newStudent;
int numStudents = 0;
System.out.println("Enter your students (or ENTER to finish):");
// Get student names
do {
newStudent = input.nextLine();
if (!newStudent.equals("")) {
students[numStudents] = newStudent;
numStudents++;
}
} while(!newStudent.equals(""));
// Get student grades
for (int i = 0; i < numStudents; i++) {
System.out.print("Grade for " + students[i] + ": ");
double grade = input.nextDouble();
grades[i] = grade;
}
// Print class roster
System.out.println("\nClass roster:");
double sum = 0.0;
for (int i = 0; i < numStudents; i++) {
System.out.println(students[i] + " (" + grades[i] + ")");
sum += grades[i];
}
double avg = sum / numStudents;
System.out.println("Average grade: " + avg);
}
}Note that we have to decide up front how large our Arrays students and grades are going to be. Thus, this program sets an arbitrary maximum amount of students, likely larger than any user will enter. It may seem obvious, then, that Array has no equivalent add() method. The only way to access and alter an element in an Array is with bracket notation, using an explicit index. For example, gradebook defines a counter variable, numStudents. When the first student is entered by the user, the value is stored in newStudent. If the value is not the empty string, then the item in students at position 0, the initial value of numStudents is assigned to the newStudent value. The next time the do-while loop executes, the value of students at position 1 will be assigned. And so on… Because we must always access and assign Array elements using an explicit index, our code can seem littered with Array counter variables (like our friends i and j) and is more difficult to read (not to mention more error-prone).
Like ArrayLists, however, we can loop through an Array using a for-each loop as long as we don’t need to use the index of the current item. If we only wanted to print each student’s name, and not their grade, at the end of our program, we could do the following:
for (String student : students) {
System.out.println(student);
}We’ll use Arrays in Java from time-to-time, but for the most part you should rely on ArrayLists to store collections of values, or ordered data.
Java also provides us a structure to store data as key/value pairs. Java calls these objects hashmaps (or maps, more generally), and they are provided by the HashMap class.
Considering the gradebook example, we can improve our program using a map. We’ll store the students’ grades along with their names in the same data structure. The names will be the keys, and the grades will be the values.
As with the other collection structures, in Java we must specify the types of the objects we’ll be storing when we declare a variable or parameter to be a map. This means specifying both key and value data types, which are allowed to be different types for a given map.
package org.launchcode.java.demos.collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class HashMapGradebook {
public static void main(String[] args) {
HashMap<String, Double> students = new HashMap<>();
Scanner input = new Scanner(System.in);
String newStudent;
System.out.println("Enter your students (or ENTER to finish):");
// Get student names and grades
do {
System.out.print("Student: ");
newStudent = input.nextLine();
if (!newStudent.equals("")) {
System.out.print("Grade: ");
Double newGrade = input.nextDouble();
students.put(newStudent, newGrade);
// Read in the newline before looping back
input.nextLine();
}
} while(!newStudent.equals(""));
// Print class roster
System.out.println("\nClass roster:");
double sum = 0.0;
for (Map.Entry<String, Double> student : students.entrySet()) {
System.out.println(student.getKey() + " (" + student.getValue() + ")");
sum += student.getValue();
}
double avg = sum / students.size();
System.out.println("Average grade: " + avg);
}
}Notice how a HashMap called students is declared on line 11:
/* Line 11 */
HashMap<String, Double> students = new HashMap<>();Here, defines the data types for this map’s pairs. Like the ArrayList, when we call the HashMap constructor on the right side of the assignment, we don’t need to specify type.
We can add a new item with a .put() method, specifying both key and value:
/* Line 26 */
students.put(newStudent, newGrade);And while we don’t do so in this example, we may also access HashMap elements using the get method. If we had a key/value pair of "jesse"/4.0 in the students map, we could access the grade with:
Double jesseGrade = students.get("jesse");Variables may be used to access elements:
String name = "jesse";
Double jesseGrade = students.get(name);Looping through a map is slightly more complex than it is for ordered lists. Let’s look at the for-each loop from this example:
/* Lines 38 through 41 */
for (Map.Entry<String, Double> student : students.entrySet()) {
System.out.println(student.getKey() + " (" + student.getValue() + ")");
sum += student.getValue();
}The iterator variable, student, is of type Map.Entry. The class Map.Entry is specifically constructed to be used in this fashion, to represent key/value pairs within HashMaps. Each Map.Entry object has a getKey method and a getValue method, which represent (surprisingly enough!), the key and value of the map item.
If you only need to access the key of each item in a map, you can construct a simpler loop:
for (String student : students.keySet()) {
System.out.println(student);
}A similar structure applies if you only need the values, using students.values():
for (double grade : students.values()) {
System.out.println(grade);
}Let’s collect some HashMap methods as we have for ArrayList. As we said about ArrayLists, this is by no means a comprehensive list. For full details on all properties and methods available, see the reference section below for official documentation on the HashMap class.
For the purposes of this table, we’ll create a map to hold our solar system’s planets and the number of moons associated with each.
HashMap<String, Integer> moons = new HashMap<>();
moons.put("Mercury", 0);
moons.put("Venus", 0);
moons.put("Earth", 1);
moons.put("Mars", 2);
moons.put("Jupiter", 79);
moons.put("Saturn", 82);
moons.put("Uranus", 27);
moons.put("Neptune", 14);| Java Syntax | Description | Example |
|---|---|---|
size() |
Returns the number of items in the map, as an int. |
moons.size() returns 8 |
keySet() |
Returns a collection containing all keys in the map. This collection may be used in a for-each loop just as lists are, but the map may not be modified within such a loop. |
moons.keySet() returns ["Earth", "Mars", "Neptune", "Jupiter", "Saturn", "Venus", "Uranus", "Mercury"] |
values() |
Returns a collection containing all values in the map. This collection may be used in a for-each loop just as lists are. |
moons.values() returns [1, 2, 14, 79, 82, 0, 27, 0] |
put() |
Add a key-value pair to a map. | moons.put("Pluto", 5) adds "Pluto": 5 to the moons |
containsKey() |
Returns a boolean indicating whether or not the map contains a given key. | moons.containsKey("Earth") returns true |
containsValue() |
Returns a boolean indicating whether or not the map contains a given value. | moons.containsValue(79) returns true |
We have only brushed the surface of how arrays, ArrayLists, and maps work. We leave it to you to refer to the official documentation linked below for more details. You’ll certainly be using ArrayLists and maps in more ways than those covered in this lesson, but with the knowledge you have now, you should be able to use Java collections and learn new uses as you go.
🎗️ TODO: Come back and do this part!
#Java