java-lang-aez-notes

Home

Table of Contents

java-logo.png

Where you looking for JavaScript notes?

Object oriented programming

  • You can have an inner class which is a class within a class.
  • The Iterable interface abstracts the process of iterating over the contents of a container.
    • An iterable is something that provides a method to return an iterator.
    • An iterator is something that has hasNext and next methods to access the next value in a sequence.
    • There is sugar, the "foreach" statement, for working with iterables.
  • The Comparable interface requires a compareTo method to be implemented. This is similar to the Ord typeclass in Haskell.
    • It returns -1 for less, +1 for greater and 0 for equal.
    • The comparable interface defines a total order.
  • There is the getClass method to check what class an object belongs to.
  • The suffix "Impl" may be used in a class name to indicate that this is a concrete implementation of a class but that there is likely another class that is used to create instances of it.
    • This might crop up if you had a factory which produced instances of the class.
    • This might crop up if you have an interface and you want to hide the implementation details in something that implements that interface.

Abstract classes and Interfaces

  • A class that has the abstract modifier cannot be used to construct a new object, you can inherit from that class.
    • You might have the abstract class Animal and then you could extend that class with a Dog class.
  • An interface is similar to a typeclass in Haskell, it provides a set of methods that classes implementing the interface need to implement.
  • Both abstract classes and interfaces are used to hide annoying details. You can only inherit from one class, but you can implement multiple interfaces so these things provide slightly different functionality.

Modifiers

  • If an attribute or method is final, then it cannot be overwritten or modified. If an attribute of method is static, then they belong to the class rather than any particular instance of the class. The static modifier allows you to access the attribute or method from the class without needing to create in instance of the class.
  • Attributes and methods marked public can be accessed by all classes. If the protected modifier is used, then the attreibutes of method is only accessable by members of the package. If the private modifier is used, then the attributes or method is only accessable from within the class.

Equality testing

All Java classes have an equals method. The default is to check if the references are equal which regularly is not strong enough.

Here is an example of how to implement the equals method: 1.) check if they are literally the same object, 2.) check if the other thing is null, and finally 3.) check that each attribute is equal using == for primatives and equals again for objects.

public final class Date implements Comparable<Date>
{
   private final int month;
   private final int day;
   private final int year;

   public boolean equals(Object y)
   {
      if (y == this) return true;
      if (y == null) return false;
      if (y.getClass() != this.getClass())
	 return false;
      Date that = (Date) y;
      if (this.day   != that.day  ) return false;
      if (this.month != that.month) return false;
      if (this.year  != that.year ) return false;
      return true;
   }
}

Note that cast that is done after we have found that they are of the same class anyway.

Interfaces

An interface plays a similar role to a typeclass in Haskell. An interface X defines a set of methods that need to be implemented by a class Y if we are to say that Y implements X.

Iterable

Iterable interface

public interface Iterable<Item>
{
   Iterator<Item> iterator();
}

Iterator interface

public interface Iterator<Item>
{
   boolean hasNext();
   Item next();
   void remove(); // better to avoid this!
}

If you have have an iterable data type you can use foreach statements such as this

for (String s : stack)
   StdOut.println(s);

Example

This is taken from Sedgewick's lecture notes but the next example seems to fit better with some of the problems he set.

import java.util.Iterator;

public class Stack<Item> implements Iterable<Item>
{
    // the function to get the iterator
    public Iterator<Item> iterator() { return new ListIterator(); }

    // a private class to represent the iterator
    private class ListIterator implements Iterator<Item>
    {
	public boolean hasNext() { /* predicate */ }
	public void remove()     { throw new UnsupportedOperationException(); }
	public Item next()       { /* return next */ }
    }
}

Example

public Iterable<Item> range() {
    return new ItemIterable();
}

public class ItemIterable implements Iterable<Item> {
    public Iterator<Item> iterator() { return new ItemIterator(); }
}

public class ItemIterator implements Iterator<Item> {
    public boolean hasNext() {
    }

    public Item next() {
    }
}

Type system

Generics

Parametric polymorphism in java is provided by Generics (using the angle brackets: < and >). Constraints can be put on types to produce Bounded types, these play a similar role to typeclasses in Haskell. These features allow you to turn some run-time errors into compile time errors.

Unfortunately you cannot use generics in array creation, instead you need to create an array of objects and do the case explicitly.

Primitive types

  • boolean
  • char
  • byte
  • short
  • int
  • long
  • float
  • double

Syntax examples

Arrays

For arrays with values determined at runtime

double[] a;
a = new double[N];
for (int i = 0; i < N; i++) {
  a[i] = 0.0;
}

For arrays with values determined at compile time

String[] suit = {"Clubs", "Diamonds", "Hearts", "Spades"};

Documentation

The documentation system for Java is javadoc; the Wikipedia page for Javadoc has some useful examples, and this is supported by IntelliJ. There is a full list of available tags (e.g. @param) in the specification.

  • <p> and <a> tags are supported,
  • and to reference a method use {@link package.class#method}.

Example

 /**
 * Short one line description.                           (1)
 * <p>
 * Longer description. If there were any, it would be    (2)
 * here.
 * <p>
 * And even more explanations to follow in consecutive
 * paragraphs separated by HTML paragraph breaks.
 *
 * @param  variable Description text text text.          (3)
 * @return Description text text text.
 */
public int methodName (...) {
    // method body with a return statement
}

Enumerations and switch statements

WARNING the switch syntax has changed between Java versions so it may be best to stick to if-else unless you know the version you will be using and are comfortable with this.

public class Demo {

   private enum Day {

       SUNDAY("sunday"),
       MONDAY("monday"),
       TUESDAY("tuesday"),
       WEDNESDAY("wednesday"),
       THURSDAY("thursday"),
       FRIDAY("friday"),
       SATURDAY("saturday");

       Day(String name) { this.name = name; }

       @Override
       public String toString() { return name; }

       private final String name;

   }

   // put a main method here too!
}

The some examples of what that main method might look like are given below.

public static void main(String[] args) {

    int dayNum = 0;
    Day day;
    switch (dayNum) {
	case 0: day = Day.SUNDAY;
	    break;
	case 1: day = Day.MONDAY;
	    break;
	case 2: day = Day.TUESDAY;
	    break;
	default:
	    throw new IllegalStateException("Unexpected value: " + dayNum);
    }
    System.out.println(day.toString());
}
public static void main(String[] args) {

    int dayNum = -1;
    Day day = Day.MONDAY;
    switch (day.toString()) {
	case "sunday": dayNum = 0;
	    break;
	case "monday": dayNum = 1;
	    break;
	case "tuesday": dayNum = 2;
	    break;
	default:
	    throw new IllegalStateException("Unexpected value: " + dayNum);
    }
    System.out.println(dayNum);
}

There is also some sugar for writing switch statements

dayNum = switch (day.toString()) {
    case "sunday" -> 0;
    case "monday" -> 1;
    case "tuesday" -> 2;
    default -> throw new IllegalStateException("Unexpected value: " + dayNum);
};

For-each loop

There is some syntactic sugar to assist with writing loops.

int xs = {1,2,3};
for (int x : xs) {
    System.out.println(x);
}

Hello world

Here is a complete Hello World example.

// Hello.java
public class Hello {
    public static void main(String[] args) {
	System.out.println("hello, world!");
    }
}
$ javac Hello.java
$ java Hello
hello, world!

Ant build script

The following ant build script can be used with the hello world example above.

<project name="hello"
	 basedir=".">

    <target name="compile">
	<javac srcdir="."
	       includeantruntime="true"
	       includes="Hello.java"
	       destdir="." />
    </target>

    <target name="run"
	    depends="compile">
	<java classname="Hello"
	      fork="true" />
    </target>

</project>
$ ant compile
Buildfile: <path/to/build.xml>

compile:

BUILD SUCCESSFUL
Total time: 0 seconds
$ ant run
Buildfile: <path/to/build.xml>

compile:

run:
     [java] hello, world!

BUILD SUCCESSFUL
Total time: 0 seconds

Ternary operator

foo = (1 < 2) ? "hello" : "goodbye";

Varargs

The Oracle documentation for varargs gives the following example:

public static String format(String pattern,
			    Object... arguments);

with the explanation

The three periods after the final parameter's type indicate that the final argument may be passed as an array or as a sequence of arguments.

Command line arguments

See this example.

JUnit

There are differences between the major versions of JUnit that cannot be ignored.

JUnit4.X asserting it should throw an exceptions

@Test(expected = RuntimeException.class)
public void testItThrowsException() {
    Foo x = new Foo("this is not a good value");
}

Compilation and runtime

  • assert statements can be disabled or enabled at runtime. Rule of thumb is to only use them for internal invariants and to assume that they will be disabled in production.

Tools

IntelliJ

IntelliJ manages a lot of the mess of working in Java. There is the IdeaVim plugin to give sensible keybindings. The solarized theme is nice.

Code navigation and editing

  • zz to centre the current line (recenter-top-bottom).
  • Alt + Enter to apply suggested change.
  • F2 to jump to next error.
  • F4 or Crtl + Alt + B to jump to definition.
  • Ctrl + / to comment (and uncomment) code.
  • Ctrl + TAB to switch between files.

Code execution

  • Ctrl + F9 to build.
  • Shift + F9 to run in debug.

Code generation

To make the getters and setters for attributes use Code then Generate and select the attributes to generate the methods for.

VisualVM

This is a tool from Oracle that makes it very easy to profile a running program. It hooks into the JVM and generates a report on both the resource consumption and the CPU and memory usage through the code. There is an instructional video from 2013 which is sufficient to get started with.

Author: Alex Zarebski

Created: 2022-08-18 Thu 10:30

Validate