Lesson 2.2

The basic building blocks of programming - Lists and Loops

Lesson Outcomes

By The end of this lesson you should:

  • Have run your first program in Java
  • "Translated" some of your pseudocode into a runnable program
  • Have used some of Java's provided functionality
  • Be able to read and understand a Java program

In this lesson we'll be meeting more of Java, and its syntax that corresponds to our pseudocode

We'll be meeting a few more aspects of programming, alongside some old ones:

  • Collections and Loops
  • Rules and Conventions of Java
Collections

A Collection is a data type that holds a bunch of another data type

Their type can be defined as:


CollectionType<TypeItContains> collectionOfSomething = ...
          

we will continue to use:


var collectionOfSomething = ...
          

An example creating some collections:


import java.util.List;
import java.util.Set;
import java.util.Map;

public class UsingCollections {
  public static void main(String[] args) {
    var listOfStrings = List.of("first element", "second element");
    var setOfIntegers = Set.of(1, 2, 3);
    var mapFromStringToBoolean = Map.of(
        "this is true", true,
        "this is false", false
    );
  }
}
          

Notice that we have to import these types, this is because they are not part of the core language.

for-loops

For each

Much like pseudocode says "for each item in the list", we can do this:


import java.util.List;

public class UsingForEach {
  public static void main(String[] args) {
    var alphabet = List.of("a", "b", "c");
    for (var letter : alphabet) {
      System.out.println(letter);
    }
  }
}
          

where "letter" is a name we chose for the current element in the list

For with counter

Much like pseudocode says "for a counter from lower bound to upper bound", we can do this:


public class UsingForWithCounter {
  public static void main(String[] args) {
    for (var counter = 1; counter <= 10; counter = counter + 1) {
      System.out.println("Number " + counter);
    }
  }
}
          

The "for a counter from lower bound to upper bound" code is made of 3 parts


for (var counter = 1; counter <= 10; counter = counter + 1) {
  System.out.println("Number " + counter);
}
          
  1. var counter = 1; - Create an Integer variable called counter, set it to 1
  2. counter <= 10; - Continue looping until counter is greater than 10
  3. counter = counter + 1 - After each run of the loop, set the counter to its value plus 1
while-loop

This is very similar to our pseudocode:


public class UsingWhile {
  public static void main(String[] args) {
    var condition = true;
    while (condition) {
      System.out.println("I'm stuck here forever");
    }
  }
}
          

This particular while-loop will run forever, because it contains no logic to set condition to false.

Exercises

Lists and Loops

click here for the exercise sheet