Passing code as a parameter: An example of Java 8’s lambda expressions

April 29, 2018 Leave a comment

In languages like Python and Javascript, functions are “first class objects”. This means that they can be assigned to variables and passed as parameters. In Java, if you want this functionality, you have to use an anonymous class or a lambda expression. Below are examples of the old-fashioned anonymous class technique, the new Lambda expression technique and, for comparison, the same code in Python and Javascript.

Note the in the Lambda expression example there is no body provided for the execute() method. The fact that the Executable interface has a single method, and that the code passed in is interpreted as an Executable object, is sufficient for the compiler to know that the code passed in should be run when the execute() method is invoked.

Java

package lambdaexample;

public class Main {

    public static void main(String[] args) {
        doAnonymousClassExample();
        doLambdaExample();
    }

    // This method not required by Lambda example
    static void doAnonymousClassExample() {
        CodeRunner c = new CodeRunner();
        c.run(new Executable() {
            public void execute() {
                System.out.println("The code is running.");
            }
        });
    }

    // This method not required by anonymous class example
    static void doLambdaExample() {
        CodeRunner runner = new CodeRunner();
        runner.run(() -> System.out.println("The code is running."));
    }
}

interface Executable {
    void execute();
}

class CodeRunner {
    void run(Executable code) {
        System.out.println("About to run the code...");
        code.execute();
    }
}

Javascript

var foo = function() {
  console.log("The code is running.");
}

function codeExecuter(code) {
  console.log("About to run code...");
  code();
}

codeExecuter(foo);

Python

def codeexecuter(code):
    print("About to run code...")
    code()

foo = lambda : print("The code is running.")
codeexecuter(foo)
Advertisements

Real-world use of preconditions and postconditions

April 28, 2018 Leave a comment

This is from Oracle’s documentation of Java 8’s lambda expressions. Look at the table that describes the new feature to be added to the social networking application.

Selection_027.png

SparkJava: Like Bottle.py, but Java

April 24, 2018 Leave a comment

Here is my tutorial on setting up Git, Gradle and SparkJava on Netbeans 8.2. It looks pretty good! I suggest looking into Grails and Groovy too.

SparkJava with Git, Grails and Netbeans 8.2

Java Multithreading Example

April 24, 2018 Leave a comment

This is not on the IB Computer Science syllabus, but it’s useful for IAs and Grade 10 projects. One of the key reasons you might decide to run some code in its own thread is so that your GUI can remain responsive to user-generated events like button clicks. Imagine you have a sudoku game that displays a timer. You would need to run the timer in its own thread so that the game remained responsive to the user entering answers in the sudoku grid.

public class MultiThreadingExample {

    public static void main(String[] args) {
        /* Create five new tasks and set them running in their
         * own threads.
         */
        for (int i = 0; i < 5; i++) {
            /* Notice that because we don't re-use the task 
             * or thread objects, there is no need to assign
             * them to variables. This code is equivalent to
             *
             * Task task = new Task();
             * Thread thread = new Thread(task);
             * thread.start()
             */
            (new Thread(new Task())).start();
        }
    }
}

class Task implements Runnable {
     
    private static int nextId;
    private int id;
    
    public Task() {
        init();
    }
    
    private synchronized void init() {
        /* The synchronized keyword ensures that any thread
         * that runs this method runs the whole method before
         * yielding to another thread. This is necessary here
         * to prevent two threads from executing id = nextId
         * consecutively (in which case they will both get the
         * same id).
         */
        id = nextId;
        nextId = nextId + 1;        
    }
    
    public void run() {
        /* Each thread just counts up to 10 and prints out its
         * id and the number it has reached.
         */
        for(int i = 0; i < 10; i++) {
            System.out.println(id + ": " + i);
        }
    }
}

Confusion with lists in the IB Computer Science syllabus

April 20, 2018 Leave a comment

There are three key mentions of the word list in the IB syllabus and they are all HL only:

  • Linked lists in Topic 5
  • ADT list in Option D
  • ArrayList and LinkedList in Option D

Topic 5 Linked Lists

This reference is all about how linked list objects work with references to the next node. You need to be able draw or construct simple code to show the changes that the list undergoes with insertion or deletion of a node. You should also certainly know the basic algorithm for traversing the list, e.g searching for an item within it.

Types of lists are singly-linked, doubly-linked, circular, etc, and a key point is that they only support serial access and, unlike arrays, don’t support direct access.

ADT list in Option D (D4.7)

ADT stands for Abstract Data Type. The “abstract” is there because we are not worrying at all about implementation, just what operations a list might support. What the IB wants you to understand here is that we can still talk about adding, removing, getting the next value, etc, without specifying exactly how the data is stored. In the past there have been questions that invent a list, along with the operations it supports, there and then on the questions paper, and students are expected to construct code using the list.

You can look at abstract lists in Java using the two links below. You are certainly not expected to know the details of these classes/interfaces, you just need the general concepts mentioned above.

java.util.AbstractList
java.util.List

ArrayList and LinkedList (D4.11)

The syllabus says you should have a “broad understanding of the operation of these lists and their interface (methods)”. Oddly you are not expected to know the implementation, but it seems to me a key fact that the underlying data structure in an ArrayList is an array, and the underlying data structure in a LinkedList is, well, a linked list. This has great implications for the decision as to which to select. Anyway, have a brief look at the Javadoc pages linked above, and also looked at the new slide put into the Option D presentation showing techniques for iteration through each of these list types.

Java Switch Statement Example

April 18, 2018 Leave a comment

I don’t see the switch statement used very much, but it’s on your syllabus so let’s take a look at it:

String grade = input(); // assume that input method exists
String msg;
switch (grade) {
	case "A":
		 msg += "Very ";
	case "B":
		 msg += "Good ";
	case "C": 
		 msg += "Pass";
		 break;
	case "D":
		 msg = "Borderline ";
	case "F":
		 msg = "Fail";
		 break;
	default: 
		 msg = "Invalid Grade";
}
System.out.println(msg);

The outputs are as follows:

grade = “A” -> “Very Good Pass”
grade = “B” -> “Good Pass”
grade = “C” -> “Pass”
grade = “D” -> “Borderline Fail”
grade = “F” -> “Fail”
Anything else -> “Invalid Grade”

Notes:

  • You have to have the break statement otherwise you “fall through” to the next case. It’s normal to have a break statement at the end of every case. The example I’ve provided is contrived to show you the functionality, but in 25 years of programming Java I can’t remember genuinely using a switch statement like this!
  • The default case is executed if none of the other cases are executed.
  • The ability to use a switch statement on String objects was introduced in Java 7.

Java Generics: A simple example

April 15, 2018 Leave a comment

Sometimes you will see funny angle brackets in Java code. Although Java’s generic types are not mentioned in the IB syllabus, this is a brief example of their use.

The output of this code is:

Hello
5
java.util.Random@7852e922
Anything object: Fred, 5
Anything object: Second, 2

package genericsdemo;
import java.util.List;
import java.util.ArrayList;
/**
 *
 * @author justin
 */
public class GenericsDemo {

    public static void main(String[] args) {
        /* Here we create four MyContainer objects and show that we can put
         * any type into them. Note that the generic type has to be a reference
         * type; we couldn't put a primitive in there.
         */
        MyContainer<String> container1 = new MyContainer("Hello");
        MyContainer<Integer> container2 = new MyContainer(5);
        MyContainer<java.util.Random> container3 = new MyContainer(new java.util.Random());
        MyContainer<Anything> container4 = new MyContainer(new Anything("Fred", 5));
        
        System.out.println(container1.get());
        System.out.println(container2.get());
        System.out.println(container3.get());
        System.out.println(container4.get());
        
        /* It is probably rare that you will use Java Generics to create
         * your own containers. Much more likely you will use it to specify  
         * the type of object to be held in a list object from the Java
         * library.
         */
        List<Anything> myList = new ArrayList();
        myList.add(new Anything("First", 1));
        myList.add(new Anything("Second", 2));
        myList.add(new Anything("Third", 3));
        System.out.println(myList.get(1));
    }
    
}

class MyContainer<T>{
    /* T is not a type, it is a type variable.
     * The variable t is an object of type T, even though we don't yet know 
     * what type T is. 
     */
    T t;
    public MyContainer(T t) {
        this.t = t;
    }
    
    T get(){
        return t;
    }
}

class Anything {
    String name;
    int number;
    
    public Anything(String name, int number) {
        this.name = name;
        this.number = number;
    }
    
    public String toString() {
        return "Anything object: " + name + ", " + number;
        
    }
}