Java source code for X52.9238

Definitions:
computer, program, project, package, file, class, method

A computer is a machine that follows instructions. A program is a list of instructions for the computer to execute. The instructions in a Java program must be divided into sections called classes. The first and last line of our first Java program, HelloWorld.java, mark the start and end of a class named HelloWorld. You will create this class in step 4 of the HelloWorld Tutorial.

The instructions in a class must be further divided into subsections called methods. (In other languages, the methods are called “functions”, “subroutines”, or “procedures”.) The second and next-to-last lines of HelloWorld.java mark the start and end of a method named main, belonging to class HelloWorld. You will create this method in step 4 when you check the checkbox for public static void main.

The class HelloWorld will be written in a file named HelloWorld.java, also created in step 4. The set of files that make up a Java program is called a project. Our project will be named HelloWorld. The project resides in a folder of the same name, contained in the workspace folder which you created in step 7 of the instructions for downloading Eclipse. Our HelloWorld project will be very simple; the only .java file that it will contain will be HelloWorld.java. (The project may contain other files, but you don’t have to look at them.) You will create this project in step 3.

A more complicated project might contain hundreds of .java files. The files of a project are therefore divided into groups called packages. Our project will contain only one package, the “default package”, which will contain only one .java file, HelloWorld.java. You will create this package in step 4 when you leave the Package: box empty.

Download Java

On AWS:

sudo yum update
sudo yum install java

yum list installed 'java*'
Loaded plugins: extras_suggestions, langpacks, priorities, update-motd
Installed Packages
java-11-amazon-corretto.x86_64              1:11.0.6+10-1.amzn2      @amzn2-core
java-11-amazon-corretto-headless.x86_64     1:11.0.6+10-1.amzn2      @amzn2-core
javapackages-tools.noarch                   3.4.1-11.amzn2           @amzn2-core

which javac
/usr/bin/javac

which java
/usr/bin/java

javac --version
javac 11.0.6

java --version
openjdk 11.0.6 2020-01-14 LTS
OpenJDK Runtime Environment Corretto-11.0.6.10.1 (build 11.0.6+10-LTS)
OpenJDK 64-Bit Server VM Corretto-11.0.6.10.1 (build 11.0.6+10-LTS, mixed mode)

On AWS, create a bin subdirectory of your home directory and create the following bash shellscript.

echo $PATH | tr : '\n' | cat -n
     1  /usr/local/bin
     2	/usr/bin
     3	/usr/local/sbin
     4	/usr/sbin
     5	/home/user/.local/bin
     6	/home/user/bin

cd
pwd
ls -l

mkdir bin
ls -l
drwxrwxr-x 2 user group    6 Jan 28 11:12 bin

chmod 755 bin
ls -l
drwxr-xr-x 2 user group    6 Jan 28 11:12 bin

cd bin
pwd

vi jav
chmod 755 jav
ls -l jav

vi MyProg.java
jav MyProg
ls -l MyProg.java MyProg.class

file MyProg.java
MyProg.java:  C source, ASCII text

file MyProg.class
MyProg.class: compiled Java class data, version 55.0
#!/usr/bin/bash
#This bash shellscript is named jav.
#Put it in the bin subdirectory of your home directory.
#The first (or only) is the name of the .java file, without the .java extension.

if [[ $# -lt 1 ]]
then
	echo $0: requires at least one command line argument 1>&2
	exit 1
fi

if [[ ! -e $1.java ]]
then
	echo $0: $1.java does not exist 1>&2
	exit 1
fi

if [[ ! -f $1.java ]]
then
	echo $0: $1.java must be a file 1>&2
	exit 1
fi

if [[ ! -r $1.java ]]
then
	echo $0: must have read permission for $1.java 1>&2
	exit 1
fi

if ! javac $1.java
then
	#Arrive here if javac $1.java did not produce exit status 0.
        echo $0: $1.java did not compile 1>&2
        exit 1
fi

java $*   #$* is all the command line arguments passed to this shellscriprt.
#!/usr/bin/bash
#This shellscript is jget.  Sample use: jget HelloWorld

if [[ $# -lt 1 ]]
then
        echo $0: needs at least one argument 1>&2
        exit 1
fi

cd ~/bin   #The tilde stands for the name of the user's home directory.

if [[ -e $1.java ]]
then
	echo -n "~/bin/$1.java already exists.  Remove?  [y/n]: "
	read answer
	if [[ $answer == 'y' ]]   #string comparison, not numeric comparison
	then
		rm $1.java
	else                      #anything other than y counts as no
		exit 1
	fi
fi

if ! wget -q http://oit2.scps.nyu.edu/~meretzkm/x52.9238/src/$1.java
then
        echo $0: could not get http://oit2.scps.nyu.edu/~meretzkm/x52.9238/src/$1.java 1>&2
        exit 1
fi

#Compile and run:
jav $*

Install Java on PC before Eclipse.
Download page.
• Accept License Agreement
jdk_13.0.2-windows_x64_bin.exe
Allow changes? Yes
Installs in
/C/Program Files/java/jdk-13.0.2
C:\Users\myname\eclipse-workspace

Printing

  1. HelloWorld.java: System.out.println; System.out vs. System.err.
  2. Dime1.java: line separator: println vs. print.
  3. Dime2.java
  4. Flag.java: ASCII US flag. Many lines of output.

Variables, operators, expressions

  1. Variable.java: create, initialize, and print a variable.
  2. Expression.java: operator precedence and associativity. Math.abs.
  3. Remainder.java: the division and remainder operators.
  4. Assign.java: assign a new value to a variable; final variables; i = i + 1;
  5. JobTake.java: input, division and remainder. How long does the job take?
  6. Input1.java: input an integer by calling the method java.util.Scanner.nextInt and store the integer in a variable. Blocking i/o.
  7. Input2.java: check for input failure with java.util.Scanner.hasNextInt.
  8. Age.java, Wait.java, Cents.java, Turkey.java, Change.java

Control Structure

Loops: while, for, do-while

  1. NotToProgram.java
  2. While.java: while loop, {curly braces}, (parentheses), logical expression. Digression: System.out.printf
    1. 0 to 10 by 1’s
    2. 0 to 20 by 1’s
    3. 10 to 20 by 1’s
    4. 10 to 20 by 2’s: three vital statistics
    5. count down
    6. iterate zero times
  3. For1.java: for loop: three vital statistics on same line, code is more localized.
  4. For2.java: for loop with local variable
  5. Beer.java: 100 Bottles of beer on the Wall
  6. Pierogies.java (parochial)
  7. Thruway.java
  8. Sum1.java: sum the numbers from 1 to 10 (or to 100); +=
  9. Sum2.java: sum the numbers from 1 to n.
  10. Sum3.java: read n from the standard input.
  11. Sum4.java: concatenate Strings.
  12. Geometric.java: geometric progression
  13. CountForever.java: infinite for loop and sleep
  14. Infinite.java: infinite for loop with no induction variable at all
  15. DoWhile.java: do-while loop: test at the bottom, guessing game.

Nested Loops

  1. Nest.java: nested for loops (Lucy in the Sky with Diamonds)
  2. Rectangle1.java: rectangle hardwired for 4 rows and 5 columns. Modify to make a triangle with 4 rows.
  3. Rectangle2.java: rectangle with nrows rows and ncols columns
  4. Graph1.java: graph paper with one loop (hardwired for 10 rows and 10 columns)
  5. Graph2.java: graph paper with nested for loops (hardwired for 10 rows and 10 columns)
  6. Graph3.java: graph paper with nested for loops (nrows rows and ncols columns)

if and switch Statements

  1. If.java: if without else.
  2. Else1.java and Else2.java: a pair of consecutive, mutually exclusive if statements; the else keyword
  3. UpsideDown.java: put the smaller clause at the top.
  4. IsPrime.java: if inside of for loop; System.exit
  5. Primes.java: labelled continue. Skip this.
  6. IfInThen1.java and IfInThen2.java: if inside of then (profit vs. loss). Last test is sometimes unnecessary.
  7. IfInElse1.java and IfInElse2.java: if inside of else. Last test is sometimes unnecessary.
  8. ElseIf1.java and ElseIf2.java: an else occupied entirely by an if.
  9. TooLow.java: the DoWhile.java guessing game with hints. java.util.Random.nextInt
  10. ThreeWay.java: making, losing, breaking even.

    The Metro-North evacuation instructions:

    1. Remain inside the train if possible. If not …
    2. Go to next car through end doors. If Unable …
    3. Open side door and get out. If you can’t …
    4. Go out emergency windows.

  11. FourWayLeap.java: leap year
  12. FourWayOrdinal.java: the expression i % 100 is the two rightmost digits of i.
    	if (11 <= i % 100 && i % 100 <= 13) {
    		System.out.println("th");
    	} else if (i % 10 == 1) {
    		System.out.println("st");
    	} else if (i % 10 == 2) {
    		System.out.println("nd");
    	} else if (i % 10 == 3) {
    		System.out.println("rd");
    	} else {
    		System.out.println("th");
    	}
    
  13. Switch1.java and Switch2.java: presidential/congressional/local election year switch statement with breaks. NoBreaks.java: why the switch statement needs the breaks. See also Christmas1.java.
  14. Exercise (don’t peek). Christmas1.java and Christmas2.java (with array and the ternary operator) print The Twelve Days of Christmas.

Data types

  1. Int.java: division truncates; wrap around.
  2. Integers.java. The integral types (except char): byte, short, int, long. Farther in the negative direction.
    byte:                       –128 to                       127
    short:                   –32,768 to                    32,767
    int:              –2,147,483,648 to             2,147,483,647
    long: –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
    
  3. DemoBigInteger.java: class BigInteger; also BigDecimal.
  4. Floating.java: float, double
  5. Interest.java: how many years does it take for the principal to double? double variables, do-while loop, natural logarithm Math.log
  6. Organ.java: organ pipes spanning one octave. double variables, for loop, Math.pow
  7. Pi.java: compute π by the Monte Carlo method.
  8. Solve.java
  9. Char.java and cast to int. Unicode character code charts: Russian, Arabic, etc.
  10. DemoString.java: class String
  11. DemoBool.java: boolean

Arrays

  1. Array1.java and Array2.java: create an array of int’s (month lengths) and an array of String’s (month name)
  2. YearOfThe.java: array of String’s
  3. Plot.java: a movie plot generator with three arrays of String’s.
  4. Dependents1.java and Dependents2.java: number of dependents, without and with an array.BubbleSort.java and BubbleSortStrings.java an array of int’s and String’s. String.compareTo and String.compareToIgnoreCase
  5. Beethoven1.java and Beethoven2.java: play the Ode to Joy. Synthesizer, MidiChannel.
    start → Settings → Control Panel → Sound → volume up.
  6. Manhattan.java: find the street number along an avenue. Street1.java, Street2.java, Street3.java: the advantage of using an array. Compare YearOfThe.java, with and without an array.
  7. MyRandom.java: create an array with new.
  8. TwoD.java: two-dimensional array: tic-tac-toe board
  9. DetectWin.java: detect win at tic-tac-toe.
  10. MakeWin.java: make the winning move at tic-tac-toe. Three-dimensional array.
  11. SpreadSheet.java: spreadsheet of doubles
  12. Parallel.java: two-dimensional array holds parallel columns of integers: pitch and length

Static methods
(i.e., methods that do not belong to objects)

  In fact the manager said afterwards that Mr. Kurtz’s methods had ruined the district.  

—Joseph Conrad (1857–1924), Heart of Darkness (1899)

A static method is a method that does not belong to any object. We have already seen examples: Math.sqrt, System.exit. Math and System are not objects. A static method does belong to a class, however. Math and System are classes.

  1. Method1.java and Method2.java: Secret Agent Man. We already wrote a method (sleep) in Beer.java.
  2. MyPrint.java: pass a non-array argument to a method
  3. ArrayArg.java: pass an array argument to a method. Pass an array of Strings’s to main.
  4. ReturnValue.java: return a value from a method. Print an error message with System.err.println if the argument is illegal. (We already returned a value from the Input.getInt method in Input.java.)

Static fields
(i.e., fields that do not belong to objects)

Until now, every variable was declared inside the body of a method. A static field is a variable declared outside the body of a method. Although it belongs to no method, a static field does belong to a class. The last example is new.

  1. Integers.java: Class Integer has the static fields Integer.MIN_VALUE and Integer.MAX_VALUE.
  2. Pi.java: Class Math has the static field Math.PI.
  3. Input.java: Class Input has the static field Input.reader.
  4. Beethoven1.java: Class Beethoven1 has the static fields Beethoven1.synthesizer, Beethoven1.channel, Beethoven1.C, Beethoven1.D, Beethoven1.E, etc.
  5. Total.java: new example of a static field Total.total.

Objects with fields

  1. Field.java: object with two fields and a toString member function. Fields initialized to default values. Motivated by parallel arrays in Array2.java.
  2. Constructor.java: fields initialized by constructor.
  3. ArrayOfObjects1.java and ArrayOfObjects2.java array of objects.
  4. ArrayOfObjects3.java: mass produce an array of objects using a for loop.
  5. Retrofit a single array of objects into all of our parallel array examples: Array2.java. Beethoven2.java with parallel arrays of pitch, volume, duration.

Objects with methods

  1. DateDemo.java: fields are private, methods are public.
  2. CarDemo.java: has a siphon method that accesses two Car objects. Math.min.
  3. PointDemo.java: a point in a two-dimensional space.

Extend a base class

  1. CricketDemo.java: class MetricCricket (the subclass) extends class Cricket (the superclass). The constructor for the subclass calls the constructor for the superclass.
  2. AmnioteDemo.java add new fields instead of new methods.
  3. Car2Demo.java: class Car2 (the subclass) extends class Car (the superclass). The constructor for the subclass calls the constructor for the superclass.
  4. Date2Demo.java: a class with a missing piece is an abstract class.

Implement an interface that handles an event

  1. Inter.java
  2. Go to Android, scroll down to "Controls and Listeners", click on the first example, Click Listener. In the Android example, the interface View.OnClickListener plays the rôle of the interface Point, and the class MyOnClickListener plays the rôle of class CartesianPoint.
  3. Bug.java: classes Display and Shell, GC and Color. PaintListener is merely an interface: a class with a missing method. In this case, the missing method is paintControl, which we had to write ourselves. Similarly, KeyListener is also an interface: we have to write the missing methods keyPressed and keyReleased. (Class KeyAdapter has no missing pieces, but its keyPressed and keyReleased methods do nothing.) The argument of paintControl must be a PaintEvent object, which has a field of class GC, which has the method fillRectangle. The argument of keyPressed and keyReleased must be a KeyEvent object. https://download.eclipse.org/eclipse/downloads/drops4/R-4.14-201912100610/#SWT
  4. MouseBug.java: a MouseListener as well as a KeyListener.

Throw and catch an exception

  1. Throw1.java: int division by zero throws a java.lang.ArithmeticException. double division doesn’t.
  2. Throw2.java
  3. TryThrowCatchFinally1.java: throw an exception and catch it in the same method. The keywords try, throw, catch, and finally.
  4. TryThrowCatchFinally2.java: Throw the exception in one method, catch it in another method. The throws keyword.
  5. CountForever.java: Thread.sleep will throw the InterruptedException if it is interrupted by the Thread.interrupt method.
  6. Input.java: BufferedReader.readLine throws IOException if an I/O error occurs; Integer.parseInt throws NumberFormatException if the characters that were read in do not spell an integer value.
  7. Beethoven1.java: catch MidiUnavailableException.

Input and output

These four abstract classes have abstract read and write methods for bytes and chars.

read write
byte (8-bit) java.io.InputStream java.io.OutputStream
char (16-bit) java.io.Reader java.io.Writer

Classes PrintStream (8-bit) and PrintWriter (16-bit) have println methods as well as write methods. These classes are derived from OutputStream and Writer respectively. For example, System.out and System.err are PrintStream’s.

System.in is an InputStream. To read the values that were written by a PrintStream or Writer, put a Scanner object on top of an InputStream or Reader.

byte output

  1. HelloWorld.java. A PrintStream outputs bytes that represent characters, numbers, etc.
  2. FormatDemo.java. The first argument of PrintStream.format is a format string. The method throws IllegalFormatException and NullPointerException.

byte input

  1. InputStreamDemo1.java. System.in is an InputStream, which reads bytes, not characters. The read method of PrintStream reads one byte and returns an int giving the value of that byte (0–255 inclusive). Character.isISOControl.
  2. InputStreamDemo2.java. Read digits that spell out an integer value. Character.isDigit and Character.getNumericValue.
  3. ScannerDemo1.java: Scanner.nextInt, Scanner.nextDouble, Scanner.next. Detect failure by catching exceptions.
  4. ScannerDemo2.java: Scanner.hasNextInt, hasNextDouble, hasNext. Detect failure with if statements.

A digression on 16-bit char input

  1. InputStreamReaderDemo.java. With an InputStream, you can read bytes 0–255 inclusive). If you also have an an InputStreamReader, you can read bytes and get chars (0–65535 inclusive).
  2. BufferedReaderDemo.java. The above classes InputStream and InputStreamReader let you read one byte or char at a time. They will also let you read an array of bytes or chars, but you have to know in advance exactly how many bytes or chars you want to read. A BufferedReader will let you read up to and including the next '\n', '\r', or '\r\n'.
  3. Input.java. Call the static method Integer.ParseInt instead of constructing a Scanner object.

byte file output and byte file input

  1. FileOutputStreamDemo.java. A FileOutputStream writes bytes to a file. Easier to use if you put a PrintStream on top of it. (System.out is an example of a PrintStream. This class has the println method.)
  2. FileInputStreamDemo.java. A FileInputStream reads bytes from a file. Easier to use if you put a Scanner on top of it.
  3. RandomAccessFileDemo.java. A RandomAccessFile has a seek method.
  4. FileDemo.java: A File object tells you information about a file on the disk, starting with whether the file exists. Class Date.

TCP/IP socket i/o

A conversation between a server and a client is always initiated by the client. In other words, the client talks first. On the other hand, the server is usually launched first. It is usually running long before the client talks to it, and continues running after the conversation is finished. In fact, a server usually converses with many clients simultaneously.

  1. Client.java: Use class java.net.Socket for TCP/IP, class java.net.DatagramSocket for UDP/IP. The 16-bit port number (13) identifies which server program the client wants to talk to on the remote host. Port 80 is the web server. See /etc/services for a list of other port numbers. The awk wildcard in square brackets contains one space and one tab.
    sed 's/#.*//' /etc/services | awk '$2 ~ /^80[^0-9]/'
    http            80/tcp          www www-http    # WorldWideWeb HTTP
    http            80/udp          www www-http    # HyperText Transfer Protocol
    http            80/sctp                         # HyperText Transfer Protocol
    
    netstat -at
    Active Internet connections (servers and established)
    Proto Recv-Q Send-Q Local Address           Foreign Address         State      
    tcp        0      0 localhost:smtp          0.0.0.0:*               LISTEN     
    tcp        0      0 0.0.0.0:sunrpc          0.0.0.0:*               LISTEN     
    tcp        0      0 0.0.0.0:ssh             0.0.0.0:*               LISTEN     
    tcp        0   1281 ip-172-31-85-59.ec2:ssh 222.186.52.139:45546    FIN_WAIT1  
    tcp        0    264 ip-172-31-85-59.ec2:ssh oit2.scps.nyu.edu:51828 ESTABLISHED
    tcp6       0      0 [::]:sunrpc             [::]:*                  LISTEN     
    tcp6       0      0 [::]:54321              [::]:*                  LISTEN     
    tcp6       0      0 [::]:ssh                [::]:*                  LISTEN     
    tcp6       0      0 localhost:54321         localhost:51762         TIME_WAIT  
    tcp6       0      0 localhost:54321         localhost:51760         TIME_WAIT
    
    netstat -at | awk 'NR <= 2 || $4 ~ /:54321$/'
    Active Internet connections (servers and established)
    Proto Recv-Q Send-Q Local Address           Foreign Address         State      
    tcp6       0      0 [::]:54321              [::]:*                  LISTEN     
    
  2. Server1.java. This server serves exactly one client and then dies. The service it renders is to send the word "Hello". Class ServerSocket. Change client to
    			Socket socket = new Socket("localhost", 54321);
    
  3. ThreadDemo.java: do two or more things a the same time. Class Thread.
  4. Server2.java. A multi-threaded server that serves many clients simultaneously.

SWT Programs

  1. HelloWorldSWT.java: open and close an SWT window. Classes Display and Shell.
  2. FillRectangle.java: fill a rectangle in a window. PaintListener is merely an interface: a class with a missing method. In this case, the missing method is paintControl; we had to write it ourselves. Similarly, KeyListener is also an interface: we have to write the missing methods keyPressed and keyReleased. The argument of paintControl must be a PaintEvent object, which has a field of class GC, which has the method fillRectangle.
  3. For1SWT.java: fill a column of squares with a for loop.
  4. For2SWT.java: fill rows and columns of squares with nested for loops.
  5. FlagSWT.java and DominicanSWT.java: nested for loops, else-if.
  6. Rose.java
  7. Sudoku.java

Sound Programs

start → Settings → Control Panel → Sound → volume up.

  1. Beethoven1.java and
  2. Beethoven2.java: play the Ode to Joy

Windowing packages: AWT, SWT, Swing

  1. Window1AWT.java: packages java.awt and java.awt.event.
  2. Window2AWT.java with an anonymous inner class
  3. WindowSWT.java: package org.eclispe.swt.widgets. As in HelloWorldSWT.java, remember to say
    Properties → Java Build Path → Projects → Add… → org.eclipse.swt
  4. WindowSwing.java: package javax.swing

CSV format: comma-separated values

  1. CSV1.java inputs the CSV file yob2018.txt. Class java.util.Scanner, method split. The interface java.util.List is implemented by the class java.util.ArrayList. This example is inspired by my pandas course.
    #!/usr/bin/bash
    #This shellscript is named tester (not test).
    #Compile and run CSV1.java.
    
    cd ~/bin
    
    if ! javac CSV1.java
    then
    	exit 1
    fi
    
    wget -q -O - http://oit2.scps.nyu.edu/~meretzkm/pandas/teaser/yob2018.txt |
    java CSV1 |
    head -10
    
    exit 0
    
    Count the number of male births in America in 2019. Don’t make the fields of class Name private. To make the code clearer, add two static fields to class CSV1.
    	private static final boolean M = true;
            private static final boolean F = false;
    
    Change the last for loop to
    		int boys = 0;
    
                    for (Name name: list) {
    			if (name.sex == M) {
    				boys += name.births;
    			}
                    }
    
                    System.out.println(boys);
    

Recursion

  1. RecursivePrint1.java.
  2. RecursivePrint2.java.
  3. Factorial.java.
  4. Factorial.java.
  5. TreePrint1.java.
  6. TreePrint2.java.
  7. KthLargest.java. Given a sorted binary tree, find the node with the kth largest value.
  8. QuickSort1.java. Sort an ArrayList<Integer>. Easier to read in Python.
  9. QuickSort2.java: create the three shorter Lists using lambdas.
    		//Could have created smallValues in five separate statements:
    		//See package java.util.stream
    
    		Stream<Integer> streamOfIntegers = list.stream();
    		Predicate<Integer> predicate = i -> i < pivot;
    		Stream<Integer> shorterStream = streamOfIntegers.filter(predicate);
    		Collector<Integer, ?, List<Integer>> collector = Collectors.toList();
    		var smallValues = shorterStream.collect(collector);
    
  10. Maze.java and a Python version. Make it non-static.
    XXXXXXXXXXXXXXXXXXXXXXXX
    XXXXXX.XXXXXXXX+++++++BX
    XA+XXX........X+XXXXXXXX
    XX+XXX.XXXXXXXX+XXX.XXXX
    XX+++++++XX+++++....XXXX
    XXXXXXXX+XX+XXX.XXX.XXXX
    XXXX.XXX+XX+XXX.XXX.XXXX
    XXXX....++++...XXXX.XXXX
    XXXXXXXXXXXXXXXXXX..XXXX
    XXXXXXXXXXXXXXXXXXXXXXXX
    
  11. Dijkstra.java: Dijkstra’s Algorithm.
    XX XX XX XX XX XX XX 
    
    XX 00 01 02 03 04 XX 
    
    XX 01 XX 03 XX XX XX 
    
    XX 02 03 04 XX 99 XX 
    
    XX XX XX XX XX XX XX
    
    XX XX XX XX XX XX XX 
    
    XX 00 01 02 03 04 XX
    
    XX 01 XX 03 XX XX XX
    
    XX 02 03 04 XX 99 XX
    
    XX XX XX XX XX XX XX 
    
    #!/usr/bin/bash
    #This shellscript is colorize.
    #NF is the number of fields on each line.
    
    awk '{
            for (i = 1; i <= NF; ++i) {
                    if ($i != "XX") {
                            n = int($i)
                            if (n == 99) {
                                    bg = "black"   #inaccessible
                            } else {
                                    n = 255 - 20 * n
                                    bg = sprintf("#%02X%02X%02X", n, n, n)
                            }
                            $i = "<SPAN STYLE = \"background-color: " bg ";\">" $i "</SPAN>"
                    }
            }
            print
    }'
    
    exit 0
    
    $ jav Dijkstra | colorize
    

Lambdas

  1. Lambda.java: the simplest example I could find.

Things to do differently next time

Use the simpler getInt method in Input.java. Do exceptions earlier, as part of control structure. Do SWT drawing and sound after exceptions. Add 16-bit char file i/o. AWT, SWT, Swing: trio of simpler example, without objects and redrawing. Keep the focus on loops, if statements, arrays.

Outstanding programming projects

  1. Write The Twelve Days of Christmas.
  2. Research project: create an array of objects where the constructor for each object takes two arguments of different types (e.g., String and int as in ArrayOfObjects1.java, ArrayOfObjects2.java, ArrayOfObjects3.java.
  3. In DateDemo.java, add non-static methods prev and compareTo to class MyDate. Add static method numberOfDays to class MyDate. Should compareTo be static?
  4. In CarDemo.java, make siphon static. siphon should still receive references to two objects of class Car.
  5. In PointDemo.java, change x and y from double to int. A Point object now represents the coördinates of a pixel on a screen. Add two static int fields named width and height to class Point, giving the dimensions of the screen. The constructor for class Point should use these static fields to make sure the numbers are within the legal ranges. Maybe you could also give class Point a nonstatic method named move that would change the Point’s x and y. This method should also do error checking.
  6. In Date2Demo.java, remove class Date. Write classes FastDate and SmallDate without using inheritance.