\input texinfo



@tex
\global\def\linkcolor{0 0 1}  % blue
\global\def\urlcolor{0 0 1}   % blue
@end tex

@set EDITION 1.1
@set VERSION 1.1
@set UPDATED 29 May 2016
@set UPDATE-MONTH May 2016

@comment $Id@w{$}
@comment %**start of header
@comment @include version.texi
@settitle GNU Java Training Wheels @value{VERSION}
@syncodeindex pg cp
@comment %**end of header

@copying

This manual is for GNU Java Training Wheels (version @value{VERSION},
@value{UPDATED}), which is a system for making it easier for novices
to learn to program in the Java language.

Copyright @copyright{} 2016 Davin Pearson.

@quotation
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with no
Invariant Sections, with no Front-Cover Texts, and with no Back-Cover
Texts.  A copy of the license is included in the section entitled
``GNU Free Documentation License''.
@end quotation
@end copying

@titlepage
@title GNU Java Training Wheels
@subtitle for version @value{VERSION}, @value{UPDATED}
@author Davin Pearson (@email{davin.pearson@@gmail.com})
@page
@vskip 0pt plus 1filll
@insertcopying
@end titlepage

@contents

@ifnottex
@node Top
@top GNU Java Training Wheels

This manual is for GNU Java Training Wheels (version @value{VERSION},
@value{UPDATED}).

@end ifnottex

@menu
* About GNU Java Training Wheels::
* J.T.W. Proof of concept #1 A superfor macro::
* J.T.W. Proof of concept #2 file inclusion::
* J.T.W. Tutorials::
* Packages in J.T.W. and Java::
* GNU Free Documentation License::
* Passwords for the answers to the tutorials::
* Index::
@end menu

@node    About GNU Java Training Wheels
@chapter About GNU Java Training Wheels

@cindex About GNU Java Training Wheels

This document documents a new programming language written by me,
Davin Pearson (email: @code{davin @emph{dot} pearson @emph{at} gmail @emph{dot}
com}) called @emph{J.T.W.}, short for @emph{Java Training Wheels} for the
sole purpose of making it easier to learn to program in Java.  The
J.T.W. language has a similar syntax to Delphi, Pascal, BASIC and
JavaScript and therefore learning J.T.W. before or while learning Java
provides a less steep learning curve than learning Java from scratch.
For many reasons you might even prefer to program in J.T.W. rather
than Java.  Here is why you should learn J.T.W. before or while
learning Java:

@itemize

  @item The J.T.W. language is supported by a parser that
  troubleshoots problematic J.T.W. code with clear error messages.

  @cindex Trouble-shooting problematic J.T.W. constructs
  @cindex Problematic J.T.W. constructs, trouble-shooting

  @item The J.T.W. language compiles to Java in a natural and
  straightforward way so it is easy to learn Java once you know
  J.T.W..  See the following diagram for a comparison of the
  J.T.W. and Java build processes.

  @cindex Mapping from J.T.W. -> Java
  @cindex J.T.W. -> Java mapping

@example
    +-----+
    |*.jtw|
    +--+--+
       |
       v Emacs' batch mode
    +------+                   +------+
    |*.java|                   |*.java|
    +--+---+                   +--+---+
       |                          |
       v javac compiler           v javac compiler
    +-------+                  +-------+
    |*.class|                  |*.class|
    +--+----+                  +--+----+
       |                          |
       | java                     | java
       V                          V
runs the class             runs the class


@end example

  

  @item Pascal-style @strong{@code{begin}} ... @strong{@code{end}} constructs are supported
  instead of C-style @code{@{ ... @}} constructs which is more
  sensible especially for novices.

  @cindex Pascal-style @strong{@code{begin}} ... @strong{@code{end}} construct versus the C-style @{ ... @} construct

  @item A simple syntax for the @strong{@code{main}} @strong{@code{function}}: @strong{@code{beginMain}} ... @strong{@code{endMain}}
  rather than the rather cumbersome: @code{@strong{@code{public}} @strong{@code{static}} @code{void}
  @strong{@code{main}}(String[] args) @{ ... @}}.

  @cindex A simple syntax for the @strong{@code{main}} @strong{@code{function}}.
  @cindex @strong{@code{main}} @strong{@code{function}}, a simple syntax for.

  @item Class variables, properties, functions, methods and
  constructors are declared as such much like Delphi which makes your
  code look clearer.  Specifically there are new keywords @strong{@code{classVar}},
  @strong{@code{constructor}}, @strong{@code{function}}, @strong{@code{method}} and @strong{@code{property}}.

  @cindex @strong{@code{classVar}} construct
  @cindex @strong{@code{constructor}} construct
  @cindex @strong{@code{function}} construct
  @cindex @strong{@code{method}} construct
  @cindex @strong{@code{property}} construct

  @item The Delphi/Pascal/JavaScript keyword @strong{@code{var}} for clearer local
  variables.

  @cindex The Delphi/Pascal/JavaScript keyword @strong{@code{var}} for clearer local variables
  @cindex @strong{@code{var}} for clearer local variables

  @cindex The Pascal/BASIC keyword @strong{@code{then}} for clearer @strong{@code{if}} statements
  @cindex @strong{@code{then}} for clearer @strong{@code{if}} statements

  @item The Pascal/BASIC keyword @strong{@code{then}} for clearer @strong{@code{if}} statements.

  @cindex BASIC style @strong{@code{and}} and @strong{@code{or}} constructs rather than Java's cumbersome @strong{@code{&&}} @strong{@code{||}} constructs.

  @cindex C++ style @strong{@code{and}} and @strong{@code{or}} constructs rather than Java's cumbersome @strong{@code{&&}} @strong{@code{||}} constructs.

  @cindex @strong{@code{and}} construct from BASIC and C++ in J.T.W.

  @cindex @strong{@code{or}} construct from BASIC and C++ in J.T.W.

  @item The BASIC and C++ style keywords @strong{@code{and}} and @strong{@code{or}} rather than Java's
  rather cumbersome: @strong{@code{&&}} and @strong{@code{||}}.

  @cindex @strong{@code{elseif}} construct rather than @strong{@code{else}} @strong{@code{if}}

  @item The P.H.P. keyword @strong{@code{elseif}} is supported instead of Java's
  cumbersome @strong{@code{else}} @strong{@code{if}}.

  @cindex @strong{@code{superfor}} macro

  @item As proof of concept, a @strong{@code{superfor}} macro is presented for
  enhanced BASIC-style @strong{@code{for}} loops.
  See @ref{J.T.W. Proof of concept #1 A superfor macro}.

  @cindex File inclusion in J.T.W.

  @item As proof of concept, file inclusion is supported so that you
  can spread a class across several files.  Natural divisions are
  methods.  Different methods can be placed in different source files
  for those situations where methods become large and unwieldy.  See

  @ref{J.T.W. Proof of concept #2 file inclusion}.

  
  

  @item @strong{NEW!} As of J.T.W version 1.1, packages are now supported. See
  @ref{Packages in J.T.W. and Java}.

  

@end itemize

@node    J.T.W. Proof of concept #1 A superfor macro
@chapter J.T.W. Proof of concept #1 A superfor macro

@cindex @strong{@code{superfor}} looping construct


A proof of concept for the J.T.W. preprocessor is the @strong{@code{superfor}} macro,
which is an enhanced BASIC-style @strong{@code{for}} loop.  Here is how to invoke the
@strong{@code{superfor}} macro in your @code{*.jtw} file:

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i = 0 @strong{@code{to}} 10)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("i=" + i);
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{endMain}}
@end example

The above code results in the following printout:

@example
i=0
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i=10
@end example

The @strong{@code{step}} size argument is optional, here is an example with an
explicit @strong{@code{step}} size announced:

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i = 0 @strong{@code{to}} 10 @strong{@code{step}} 2)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("i=" + i);
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{endMain}}
@end example

The above code results in the following printout:

@example
i=0
i=2
i=4
i=6
i=8
i=10
@end example

@noindent If the @strong{@code{downto}} keyword is given instead of the @strong{@code{to}} keyword then the
loop will count downwards from the first given number to the second,
even if a postive @strong{@code{step}} size is given.  Here is an example with a
negative @strong{@code{step}} size:

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i = 10 @strong{@code{downto}} 0 @strong{@code{step}} 2)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("i=" + i);
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{endMain}}
@end example

The above code results in the following printout:

@example
i=10
i=8
i=6
i=4
i=2
i=0
@end example

Note that the specification of the @strong{@code{superfor}} macro doesn't need
constants for the values of @code{start}, @code{stop} and @code{step-size}.
They can be any variable or more generally any Java expression, and
those expressions will be evaluated only once, should your code have
side effects, i.e. changes the value of a variable in your code.  See
the following example.  The expression @code{++y} has the side effect of
incrementing the value of @code{y} before returning the value of @code{y}:

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{var}} int x = 20;
@tie{}@tie{}@tie{} @strong{@code{var}} int y = 15;
@tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i = x @strong{@code{to}} (2 * ++y))
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("i=" + i);
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{endMain}}
@end example

The above code results in the following printout:

@example
i=20
i=21
i=22
i=23
i=24
i=25
i=26
i=27
i=28
i=29
i=30
i=31
i=32
@end example

@section Elisp source code for the superfor macro

The following code belongs in the file
@code{~/jtw/jtw-build-jtw.el} which in itself is too
large for inclusion in this manual.  You can find this code by
visiting @ref{J.T.W. tarball}.  Alternatively, you can study this
fragment of the file @code{~/jtw/jtw-build-jtw.el} which deals
with the @strong{@code{superfor}} macro.  In the listing that follows,
@code{*pp-namespace*} stores a string containing a long arbitrary name to
prevent accidental aliasing of the @strong{@code{include}} directives with rest of the
comments code.


@example
(let (p1 p2 str form type variable T var start stop step-size step-size-2
         this_start this_stop this_step this_step_size file line p-prior
         beg0 end0)
  @emph{;;(checkpoint "2")}
  (save-excursion
    @emph{;;(setq parse-sexp-ignore-comments t)}
    (goto-char (point-min))
    (setq *superfor* 0)
    (while (re-search-forward "\\<superfor\\>" nil t)
      (setq beg0 (match-beginning 0))
      (setq end0 (match-end 0))
      @emph{;;(checkpoint "sitting for 1 seconds...")}
      (font-lock-fontify-buffer)
      @emph{;;(sit-for 1)}
      (when (save-excursion
              (save-match-data
                (re-search-forward "(" (point-at-eol) t)
                (forward-char -1)
                (re-search-forward "\\<var\\>" nil t)
                (not (warn--inside-comment-or-string))))
        @emph{;;(error "Smelly cat")}
        (setq *current-buffer* (current-buffer))
        @emph{;;(switch-to-buffer *current-buffer*)}
        (setq p1 beg0)
        (assert (save-match-data
                  (looking-at " \t\r\n*(")))
        (setq p2 (save-excursion
                   (forward-sexp 1)
                   (point)))
        (setq str (buffer-substring-no-properties end0 p2))
        @emph{;;(checkpoint "str=%s" str)}
        (setq form (read-str str))
        @emph{;;(checkpoint "form=%s" form)}
        @emph{;;(debug "form")}
        (assert (consp form))
        @emph{;;(error "Rolling Stones plays Cuba")}
        (delete-region p1 p2)
        (incf *superfor*)
        (setq this (format "superfor_%d_" *superfor*))
        (when (not (eq (nth 0 form) 'var))
          (warn--log-message "Error 35: Keyword var missing")
          (when (and (not (eq (nth 0 form) 'char))
                     (not (eq (nth 0 form) 'short))
                     (not (eq (nth 0 form) 'int))
                     (not (eq (nth 0 form) 'long))
                     (not (eq (nth 0 form) 'float))
                     (not (eq (nth 0 form) 'double)))
            (warn--log-message (concat
                                "Error 37:#1 argument type to superfor macro must be"
                                " one of char/short/int/long/float/double"))))
        (when (eq (nth 0 form) 'var)
          (if (and (not (eq (nth 1 form) 'char))
                   (not (eq (nth 1 form) 'short))
                   (not (eq (nth 1 form) 'int))
                   (not (eq (nth 1 form) 'long))
                   (not (eq (nth 1 form) 'float))
                   (not (eq (nth 1 form) 'double)))
              (warn--log-message (concat
                                  "Error 37:#2 argument type to superfor macro must be"
                                  " one of char/short/int/long/float/double")))
          (progn
            (setq type (nth 1 form))
            (setq T (prin1-to-string type))
            (setq variable (nth 2 form))
            (setq variable-equals (prin1-to-string (nth 2 form)))
            (if (string-match "=" variable-equals)
                (progn
                  (setq variable (read-str (substring variable-equals 0 (match-beginning 0))))
                  (setq start    (read-str (substring variable-equals (match-end 0))))
                  (if (eq (nth 3 form) 'to)
                      (setq to 'to)
                    (if (eq (nth 3 form) 'downto)
                        (setq to 'downto)
                      (assert "The Bug")))
                  (setq stop     (nth 4 form))
                  (if (eq (nth 5 form) 'step)
                      (setq step-size (nth 6 form))
                    @emph{;;(setq step-size 1)}
                    ))
              (assert (or (eq (nth 3 form) '=)))
              @emph{;;(debug "Joaquin Rodrigo")}
              (setq start (nth 4 form))
              (if (eq (nth 5 form) 'to)
                  (setq to 'to)
                (if (eq (nth 5 form) 'downto)
                    (setq to 'downto)
                  (assert "Planet of New Orleans")))
              (setq stop (nth 6 form))
              (if (eq (nth 7 form) 'step)
                  (progn
                    (setq step-size (nth 8 form))
                    @emph{;;(assert (numberp (nth 8 form)))}
                    )
                @emph{;;(setq step-size 1)}
                )
              ))
          (d-quote
           (debug "Rocket Queen")
           (setq type "")
           (setq T "double")
           (setq variable (nth 0 form))
           (assert (eq (nth 1 form) '=))
           (setq start (nth 2 form))
           (if (eq (nth 3 form) 'to)
               (setq to 'to)
             (if (eq (nth 3 form) 'downto)
                 (setq to 'downto)
               (debug "My Michelle")))
           (setq stop (nth 4 form))
           (if (eq (nth 5 form) 'step)
               (setq step-size (nth 6 form))))
          (setq var         (prin1-to-string variable))
          (setq start       (prin1-to-string start))
          (setq stop        (prin1-to-string stop))
          (setq step-size-2 (prin1-to-string step-size))
          (setq start       (warn--splat-quest start))
          (setq stop        (warn--splat-quest stop))
          (setq step-size-2 (warn--splat-quest step-size-2))
           -----------------------------------------------------
          (setq this_start     (concat this "start"))
          (setq this_stop      (concat this "stop"))
          (setq this_step      (concat this "step"))
          (setq this_step_size (concat this "step_size"))
          @emph{;;(debug "My Parties")}
          (insert (concat (concat "var " T " " this_start " = " start ";")
                          (concat "var " T " " this_stop  " = " stop  ";")
                          (if step-size
                              (concat "var " T " " this_step " = " step-size-2 ";"
                                      "var " T " " this_step_size " = "
                                      (if (eq to 'to) (concat "Math.abs(" this_step ")") (if (eq to 'downto) (concat "-Math.abs(" this_step ")") (debug "Heavy Fuel"))) ";\n")
                            (concat "var " T " " this_step_size " = " (if (eq to 'to) "1" (if (eq to 'downto) "-1" (debug "Ticket to Heaven"))))) ";\n"))
          (setq line 0)
          (setq p-prior
                (save-excursion
                  (beginning-of-line)
                  (setq str (concat "^ \t*//+ " *pp-namespace* " #location0-9"
                                    " (\\(" *drive-spec* "-a-zA-Z0-9_./+\\):\\(0-9+\\))"))
                  (if (or (looking-at str) (re-search-backward str nil t))
                      (progn
                        @emph{;;(debug "Antonio Vivaldi")}
                        (setq file (buffer-substring-no-properties           (match-beginning 1)
                                                                             (match-end 1)))
                        (assert (stringp file))
                        (setq line (read-str (buffer-substring-no-properties (match-beginning 3)
                                                                             (match-end 3))))
                        (assert (integerp line))
                        (point)
                        )
                    (setq file (concat default-directory *stump* ".jtw"))
                    (setq line 1)
                    (goto-char (point-min))
                    (forward-line 2)
                    (point)
                    )))
          (setq line (+ line (count-lines p-prior (point))))
          (decf line)
          (decf line)
          (insert (format "// %s (setq file-stack '%s)\n" *list-namespace* (prin1-to-string file-stack)))
          (insert (format "// %s #location3 (%s:%d)\n" *pp-namespace* file line))
          (insert (concat "for (var " T " " var " = " this_start ";"
                          " ((" this_step_size " > 0) ? " var " <= "
                          this_stop " : " var " >= " this_stop "); "
                          var " += " this_step_size ")"))
          @emph{;;(debug "Yehudi Menuhin")}
          )))))
)
@end example


@section A bug in J.T.W. superfor

The question mark operator @code{a ? b : c} which expands to

@example
Type result;
@strong{@code{if}} (a) @strong{@code{then}}
@strong{@code{begin}}
@tie{}@tie{}@tie{} result = b;
@strong{@code{end}}
@strong{@code{else}}
@strong{@code{begin}}
@tie{}@tie{}@tie{} result = c;
@strong{@code{end}}
@end example

where type can be any Java type is not directly supported by the
arguments to the @strong{@code{superfor}} macro in J.T.W.  Elsewhere the question mark
is supported.  Instead in the @strong{@code{superfor}} macro you have to write the
following code to get a question mark operator online:

@example
@strong{@code{class}} SuperFor
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} foo(1,2);
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@tie{}@tie{}@tie{} @strong{@code{function}} void foo(int x, int y)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i=0 to (x < y @strong{@code{QUEST}} 10 : 20))
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.print(" " + i);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}
@end example


where the symbol @strong{@code{QUEST}} compiles into a question mark: @code{?}.  When
built, the program prints out the following:

@example
i=0
i=1
i=2
i=3
i=4
i=5
i=6
i=7
i=8
i=9
i=10
@end example



@node    J.T.W. Proof of concept #2 file inclusion
@chapter J.T.W. Proof of concept #2 file inclusion


When your classes become large and unwieldy, it becomes useful to
split a source file into several compilation units.  the most natural
division into compilation units is at the level of methods.  with each
method in a separate file you can manage methods that are excessively
large.  here is how to use file inclusion in the J.T.W. language.
first comes the @code{Foo.jtw} file with all bodies of methods harvested
from them:


@example
@strong{@code{class}} Foo
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{include}} "Foo-apple.method";
@tie{}@tie{}@tie{} @strong{@code{include}} "Foo-banana.method";
@tie{}@tie{}@tie{} @strong{@code{include}} "Foo-carrot.method";
@strong{@code{end}}
@end example

Here are the files that get included.  the first file is
@code{Foo-apple.method}:

@example
@strong{@code{property}} int prop1; @emph{/* declares a property for use with the apple method. */}

@strong{@code{method}} void apple(@emph{/* parameters */})
@strong{@code{begin}}
@tie{}@tie{}@tie{} prop1 = prop1 + 1;
@tie{}@tie{}@tie{} @emph{/* rest of body of apple method */}
@strong{@code{end}}
@end example

the second file is @code{Foo-banana.method}:

@example
@strong{@code{method}} void banana(@emph{/* parameters */})
@strong{@code{begin}}
@tie{}@tie{}@tie{} @emph{/* body of banana method */}
@strong{@code{end}}
@end example

the third file is @code{Foo-carrot.method}:

@example
@strong{@code{method}} void carrot(@emph{/* parameters */})
@strong{@code{begin}}
@tie{}@tie{}@tie{} @emph{/* body of carrot method */}
@strong{@code{end}}
@end example

when all of the file inclusions have been carried out by the J.T.W.
to @strong{@code{java}} compiler, the code that @strong{@code{javac}} sees will be something like
this:

@example
@emph{/* Automatically generated file. Do not edit! */}
@emph{// #foomatic #location (Foo.jtw:1)}
@strong{@code{class}} Foo
@{
@tie{}@tie{}@tie{} @emph{// #foomatic #location (apple.method:1)}
@tie{}@tie{}@tie{} int prop1; @emph{/* declares a property for use with the apple method. */}
@tie{}@tie{}@tie{}
@tie{}@tie{}@tie{} void apple(@emph{/* parameters */})
@tie{}@tie{}@tie{} @{
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} prop1 = prop1 + 1;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* rest of body of apple method */}
@tie{}@tie{}@tie{} @}
@tie{}@tie{}@tie{} @emph{// #foomatic #location (banana.method:1)}
@tie{}@tie{}@tie{} void banana(@emph{/* parameters */})
@tie{}@tie{}@tie{} @{
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* body of banana method */}
@tie{}@tie{}@tie{} @}
@tie{}@tie{}@tie{} @emph{// #foomatic #location (carrot.method:1)}
@tie{}@tie{}@tie{} void carrot(@emph{/* parameters */})
@tie{}@tie{}@tie{} @{
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* body of carrot method */}
@tie{}@tie{}@tie{} @}
@tie{}@tie{}@tie{} @emph{// #foomatic #location (Foo.jtw:6)}
@}
@end example

Note the use of the value @code{#foomatic} of the string
@code{*pp-namespace*} (where @emph{pp} stands for pre-processor) that is a
long arbitrarily defined string to prevent accidental aliasing with
the rest of the commented code that the user of the system might
write.    The @code{#location} directives are
used to keep track of the original line number in the source file.
Using Emacs batch mode executing the Elisp code: @code{jtw-build-jtw.el},
error messages in @code{Foo.java} now point back to the original
@code{Foo.jtw} file, or one of the files that get @code{#include}d like so:
@code{apple.method}, @code{banana.method} or @code{carrot.method}.  If you are
particularly clever, you can reuse the same @strong{@code{method}} in different
classes.

Version 1.0 of J.T.W. used the @emph{C Pre-Processor} (@strong{@code{cpp}}) to manage the
@code{#location} directives but unfortunately @strong{@code{cpp}} destroys comments in
the target file, and Java uses @emph{/** ... */} comments to document
the program's behaviour so @strong{@code{cpp}} cannot be used.



@node    J.T.W. Tutorials
@chapter J.T.W. Tutorials

@cindex Davin Pearson's Personal Website @url{http://davin.50webs.com}

The following tutorials including full model answers can be found on
my Website at the following location:

@center @url{http://davin.50webs.com/J.T.W}

The advantage of using my online tutorials is that the tutorials have
superior @strong{syntax} @emph{highlighting} of the code examples.  See the
following link @ref{Passwords for the answers to the tutorials} for
the passwords on my Website.

@menu

* Tutorial 1 Your first program:: Your first program and introducing
functions, parameters, arguments, strings, @code{System.out.println} and
comments to give you enough basic J.T.W. to get you started.

* Tutorial 2 Introduction to programming in Java:: Introducing chars,
the difference between == and =, booleans, the @strong{@code{if}} (...) @strong{@code{then}} ...
@strong{@code{elseif}} (...) ... @strong{@code{elseif}} (...) ... @strong{@code{else}} ... construct, local
variables, ints, the for construct and teaching you how to call
existing methods of the @code{String} @strong{@code{class}} but not teaching you how to
write your own methods until Tutorial 9.

* Tutorial 3 superfor loops and for loops:: Introducing
@code{System.out.print} for printing without a trailing carriage return,
introducing the @strong{@code{superfor}} construct, revising loops that use the @strong{@code{for}}
construct, introducing doubles and revising ints and chars.

* Tutorial 4 Four looping constructs:: Other types of loops such as
@strong{@code{superfor}}, @strong{@code{while}} and @strong{@code{do}} ... @strong{@code{while}}, and revising @strong{@code{if}} statements and @strong{@code{for}}
loops. Learning what is the best of these four looping constructs.

* Tutorial 5 A beer drinking song:: Using all of the J.T.W. constructs
that you have learned so far to rewrite a song to be more
general-purpose.

* Tutorial 6 Class variables:: Introducing class variables which are
different from variables that are local to functions.

* Tutorial 7 Non-Object arrays:: Introducing non-object arrays that
are either single dimensional or multi dimensional using two different
initialization syntaxes and introducing function name overloading.

* Tutorial 8 Accessing functions and class variables from another class:: Learning how to
access functions from another class and introducing boolean arrays.

* Tutorial 9 Mapping class variables to instance variables (also known as properties) and functions to methods::

   This gives you the full power of O.O.P. (Object Oriented
   Programming) classes.  Introducing getter methods and references
   for accessing objects. Introducing the @strong{@code{null}} keyword for
   representing no object and introducing the @code{toString} method,
   while explaining why this @strong{@code{method}} is better than any other @strong{@code{method}} or
   @strong{@code{property}} for debugging your code.

* Tutorial 10 Object arrays:: Introducing object arrays that are
either single-dimensional or multi-dimensional. Revising two different
initialization syntaxes from Tutorial 7 on non-object arrays.

* Tutorial 11 References to another class:: When classes have
references to objects of other classes in their properties then you
can set up relationships between different classes.

* Tutorial 12 Overloading methods:: Swapping the properties of
two objects, and converting methods to functions and vice-versa.

* Tutorial 13 More about references:: More questions about references.

@cindex Linked lists

* Tutorial 14 Linked lists:: When a class has a reference to itself as a
property then you can build linked lists out of objects of this
class. @strong{WARNING:} Linked lists are tricky for novice programmers to
grasp.

* Tutorial 15 Introducing inheritance:: Introducing inheritance,
polymorphism, getter and setter methods, the @strong{@code{instanceof}} keyword for
run-time type inquiry and introducing the Object class.  Introducing
the @strong{@code{null}} keyword for representing no object and introducing the
@code{toString} method, while explaining why this @strong{@code{method}} is better than
any other @strong{@code{method}} or @strong{@code{property}} for debugging your code.

* Tutorial 16 More inheritance:: Showing you how inheritance can be used to reduce
the amount of duplication of code.

* Tutorial 17 Arrays inheritance and polymorphism:: Teaches why in
most cases it is better to use polymorphism rather than run-time type
inquiry.

* Tutorial 18 Advanced J.T.W.:: Mapping J.T.W. to Java and the
internal details of the J.T.W. system, including a @emph{GNU Makefile}.

@end menu

@node    Tutorial 1 Your first program
@section Tutorial 1 Your first program


@anchor{J.T.W. tarball}
@cindex A tarball to get you started
@cindex @code{~/jtw-tutorials}

@strong{Question 4.1.1: Some code to get you started.}  First, please visit
the following Website
@url{http://davin.50webs.com/J.T.W/download-links.html} for the
programs that you need to have installed before you can do any coding
in J.T.W.  You should then download a tarball (also known as a
@emph{compressed archive file}):
@url{http://davinpearson.com/binaries/java-training-wheels-1.1.tar.gz}
containing the code you need to get started. Then unzip the tarball
and change directory to @code{java-training-wheels} and issue the
following command on GNU/Linux systems: @code{./configure} or on MS
Windows systems: @code{bash configure}.  If you are using
@emph{M.S. Windows} and your @code{HOME} variable is unset, then you will
need to set it to a sensible value.  Examples of sensible values for
your @code{HOME} variable include, @code{c:\} or @code{c:\home} or @code{d:\home}
if your @code{d} drive is a hard drive.  To set the @code{HOME} variable in
windows, press @strong{Windows E} and right click on @emph{My Computer}
(Windows XP) or @emph{This Computer} (Windows 10) and click on
@emph{Properties}, then click on @emph{Advanced system settings}, then click
on @emph{Advanced}, then click on @emph{New} environment variable to set the
@code{HOME} variable.

@cindex Installing Davin's version of Emacs @code{dlisp.tar.gz}
@cindex Davin's version of Emacs @code{dlisp.tar.gz}
@cindex @code{dlisp.tar.gz}, Davin's version of GNU Emacs
@cindex Installing Davin's @code{jtw-mode}
@cindex Davin's @code{jtw-mode.el}, a major mode for editing *.jtw files
@cindex @code{jtw-mode.el} Davin's major mode for editing *.jtw files

When you run the @code{configure} script you will be prompted for the
location of prefix directory and the location of the place to keep
your @code{*.jtw} files.  You will also be asked if you want to install
just Davin's @code{jtw-mode} or Davin's full version of Emacs.

@strong{NOTE:} If are reading this file on your local filesystem then
you would have already completed this question.

@cindex My first program
@cindex Your first program
@cindex Your first J.T.W. program
@cindex ``Hello, World!''
@cindex Hello, World!

@strong{Question 4.1.2: Your first J.T.W. program.} Traditionally in
computer science the first program that you write in any programming
language is a program that does nothing else but prints out "Hello,
World". The following code does just that. In the following code, note
the use of the @strong{@code{class}} construct. In Java and J.T.W., every piece of
program code that does some real computational work resides in a @strong{@code{class}}
of some description.



@example
@strong{@code{class}} MyFirstProgram
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Hello, World!");
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@cindex @code{make build X.run} to build and run a @strong{@code{class}} file.
@cindex Building code that uses a @strong{@code{class}}

The code for any @strong{@code{class}} @code{X} in these tutorials should reside in a
file called @code{X.jtw}. Therefore the above code should be put into a
file called @code{MyFirstProgram.jtw}. If two classes @code{X} and @code{Y} use
each other and @code{X} contains the @strong{@code{main}} @strong{@code{function}} then it is convenient
to place them both in a file called @code{X.jtw}. To build and run some
code, you first need to be in the @code{~/jtw-tutorials} folder and
secondly you need to issue the following shell command: @code{make X.run}
where @code{X} is the name of the @strong{@code{class}} that you want to run, so it is

@center @code{make @code{MyFirstProgram.run}}

in this case.  For all the questions that follow this one, it will be
assumed that you know how to do this. See @ref{How to build a
collection of class files or an entire package} for more information
about building classes that use other classes in different files or
building entire packages.

@strong{Question 4.1.3: Multiple calls to @code{System.out.println()}}. Change
the above code from printing the string "Hello, World!" to printing
out the following messages. Please note that it will be easiest to use
multiple calls to @code{System.out.println()} which sends text to the
screen for the purpose of viewing.

@cindex @code{System.out.println(/* args */);}

@example
Hello, Anne! How are you doing?
Hello, Brian! How are you doing?
Hello, Clare! How are you doing?
@end example

@strong{Question 4.1.4: Functions,parameters and arguments.}  A @strong{@code{function}} is
a piece of code that does some computational work and optionally
returns a value. Notice how the @code{hello} @strong{@code{function}} below takes a value
of whose name to say hello to. This value who is called a
parameter. The values passed to the parameter by the call to the
@strong{@code{function}} is called an argument. For the purposes of this question, add
two more calls to the hello @strong{@code{function}} in the @strong{@code{main}} @strong{@code{function}} to get the
same result as the code for the previous question. The keyword
@code{void} indicates that this @strong{@code{function}} does not return a value. See the
next question for a @strong{@code{function}} that does return a value.

@cindex Functions, parameters and arguments

@example
@strong{@code{class}} MySecondProgram
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{function}} @code{void} hello(String who)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Hello " + who + ", how are you doing?");
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} hello("Anne");
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.1.5: Return values.}  Notice how the following @code{hello}
@strong{@code{function}} returns a string rather than printing out the string. Add two
more calls to the @code{hello} @strong{@code{function}} below to get the same result as
for Question 4.1.4.

@cindex Return values

@example
@strong{@code{class}} MyThirdProgram
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{function}} String hello(String who)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} return "Hello " + who + ", how are you doing?";
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println(hello("Anne"));
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.1.6: Ignoring return values.}  In J.T.W. and Java, it is
not necessary to use a value that is returned by a @strong{@code{function}}. Sometimes
this wastes computational resources since the value that is computed
by the @strong{@code{function}} is not used but other times when the @strong{@code{function}} whose
value is to be ignored does some additional work by setting the
value(s) of some variable(s) to different values then the @strong{@code{function}}
call is not a waste of resources. To ignore the value returned by the
hello @strong{@code{function}}, simply call the @strong{@code{function}} without using the value like
so: @code{hello("Ignored");} For the purposes of this question, try
calling the hello @strong{@code{function}} without using the return value by adding a
line of code to the @strong{@code{main}} @strong{@code{function}}.

@cindex Ignoring the return values of functions and methods.

@strong{Question 4.1.7: Comments.}  Study the following code. Note the use
of comments. Comments are used to disable code for debugging purposes
and also to help explain how a program works. The most useful comment
in J.T.W. and Java is @emph{/** until the first */}. This type of
comment is harvested by Javadoc to produce documentation on how a
@strong{@code{class}} works. The second and third most useful comments are
(respectively) @emph{// until the end of the line} and @emph{/* until
the first */}. The third type of comment is not very useful because in
Java you are not allowed to have one comment inside another, so if you
use this type of comment you will constantly need to search for and
remove @emph{*/} closing comments. In the tutorials that follow you will see
many comments, although mainly the first and second types of comments.

@cindex Comments harvested by Javadoc
@cindex Javadoc, harvesting of comments

@example
@emph{/** This comment is harvested by Javadoc
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} to document the MyFourthProgram class */}
@strong{@code{class}} MyFourthProgram
@strong{@code{begin}} @emph{// I am a single line comment}
@tie{}@tie{}@tie{} @emph{/* I am}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{a multi-line}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{comment */}
@tie{}@tie{}@tie{} @emph{/** This comment is harvested by Javadoc}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{to document the hello function */}
@tie{}@tie{}@tie{} @strong{@code{function}} String hello(String who)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} return "Hello " + who + ", how are you doing?";
@tie{}@tie{}@tie{} @strong{@code{end}} )
@tie{}@tie{}@tie{} @emph{/** This comment is harvested by Javadoc}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{to document the main function */}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println(hello("Anne"));
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example



@node    Tutorial 2 Introduction to programming in Java
@section Tutorial 2 Introduction to programming in Java

@strong{Question 4.2.1:} The following code returns whether or not the current
parameter ch is a vowel. The parameter ch is of type char which is
used to hold the components of a string. That is to say, strings are
built out of sequences of chars. Also note the use of the
@code{Character.toUpperCase} @strong{@code{function}} to convert chars into uppercase chars
so that the code works equally well for @code{isVowel('a')} and
@code{isVowel('A')}. Study, compile and run the following code. Does it print
what you expected it to? If not, then fix the bug.

@cindex @code{Character.toUpperCase}
@cindex Introducing chars
@cindex chars, introducing

@example
@strong{@code{class}} Scrabble
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{function}} boolean isVowel(char ch)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} ch = Character.toUpperCase(ch);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{if}} ((ch == 'A') @strong{@code{or}} (ch == 'E') @strong{@code{or}} (ch == 'I') @strong{@code{or}} (ch == 'O') @strong{@code{or}} (ch == 'U'))
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{then}} @strong{@code{return}} @strong{@code{true}};
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{else}} @strong{@code{return}} @strong{@code{false}};
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println(isVowel('a'));
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@cindex The difference between @code{==} and @code{=}

In the above code, note the difference between @code{a = b} example:
@code{ch = Character.toUpperCase(ch)} and @code{a == b} example: @code{ch ==
'A'}. The first is an assignment that sets a to be whatever the value
of b is, while the second is a question that says whether or not the
two arguments a and b are equal.

Note that later on in this tutorial you will learn that this is not
the way to compare two strings. Also note the use of the @emph{boolean}
return type. This means that the return value is either @strong{@code{true}} or @strong{@code{false}}.

@strong{Question 4.2.2:} By copying the pattern established by the above code,
write a @strong{@code{function}} @code{isConsonant} which returns whether or not the given
argument is not a vowel. The easiest way to do this is to write
isVowel(ch) == @strong{@code{false}} which means: ``ch is not a vowel''. You will also
need to ensure that the parameter ch is greater than or equal to 'A'
and less than or equal to 'Z'. Then test your code by calling
@code{isConsonant} from the @strong{@code{main}} @strong{@code{function}}.

@strong{Question 4.2.3:} By copying the pattern established in the following code:

@example
@strong{@code{function}} @code{int} countVowels(String word)
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{var}} int result = 0;
@tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i=0 @strong{@code{to}} i<word.length()-1)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} char ch = word.charAt(i);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{if}} (isVowel(ch)) @strong{@code{then}} result = result + 1;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{return}} result;
@strong{@code{end}}
@end example

write a @strong{@code{function}} that counts the number of consonants in a word. Note
the use of the @strong{@code{var}} keyword for defining variables that are local to
functions. Local variables are very much like parameters that were
introduced in the previous tutorial. In the above code, note the use
of @code{word.charAt(i)} and @code{word.length()}. The first of these
results the character at location in the string word given by the
value of i and the second of these returns the length of the string
word. In Tutorial 11 you will learn that these are called methods
which are different from functions that currently know how to
write. Until we get to this tutorial and we are ready to teach you how
to write your own methods, you will only call existing methods such as
the above methods of the String class. Then test your code by calling
it from the @strong{@code{main}} @strong{@code{function}}.

@cindex Calling existing methods of the @code{String} class

@strong{Question 4.2.4:} Write a @strong{@code{function}} @code{simpleScoreWord} that calls
@code{countVowels} and @code{countConsonants} to give a Simple Score of a
word. The Simple Score of a word is the number of vowels in the word
plus the number of consonants in the word times ten. Then test your
code by calling it from the @strong{@code{main}} @strong{@code{function}}.

@strong{Question 4.2.5:} Write a @strong{@code{function}} @code{advancedScoreLetter} that
returns the Advanced Score of a letter. Here is a breakdown of the
distribution of letters for the purpose of the calculation of the
Advanced Scores.

@example
2 blank tiles (scoring 0 points)
1 point: E 12 tiles, A 9 tiles, I 9 tiles, O 8 tiles, N 6 tiles, R 6 tiles, T 6 tiles, L 4 tiles, S 4 tiles, U 4 tiles
2 points: D 4 tiles, G 3 tiles
3 points: B 2 tiles, C 2 tiles, M 2 tiles, P 2 tiles
4 points: F 2 tiles, H 2 tiles, V 2 tiles, W 2 tiles, Y 2 tiles
5 points: K 1 tiles
8 points: J 1 tiles, X 1 tiles
10 points: Q 1 tiles, Z 1 tiles
@end example

Then test your code by calling it from the @strong{@code{main}} @strong{@code{function}}.

@strong{Question 4.2.6:} Write a @strong{@code{function}} @code{advancedScoreWord} that
returns the Advanced Score of a word. The Advanced Score of a word is
the sum of the Advanced Scores of each letter in the word. If the word
is eight letters long then you should add an extra, say, 50 points to
the score. Then test your code by calling it from the @strong{@code{main}} @strong{@code{function}}.

@strong{Question 4.2.7:} Comparing strings. Amend the @code{advancedScoreWord}
@strong{@code{function}} so that swear words get a score of zero. For the purposes of
this question you only need to think of three swear-words to add to
the code. In the interests of not offending anyone, please keep your
choice of swear words very tame. When comparing strings it is a
mistake to use == which you already know is how you compare the
following types that you know of so far: booleans, chars and
ints. Using == on strings compiles and runs but gives you the
incorrect result. The correct method to compare strings is to use the
equals method of the string class like so: @code{word.equals("bugger")}
which returns @strong{@code{true}} or @strong{@code{false}}, depending on whether or not the string
word currently holds the value "bugger".

@strong{Question 4.2.8:} Change the @code{advancedScoreWord} @strong{@code{function}} so it works
equally well with uppercase words and lowercase words. You will need
write to call either @code{word.toUpperCase()} or @code{word.toLowerCase()}
and store the result in word.

@cindex @code{toUpperCase()} of the @code{String} class
@cindex @code{toLowerCase()} of the @code{String} class



@node    Tutorial 3 superfor loops and for loops
@section Tutorial 3 superfor loops and for loops


@strong{Question 4.3.1a:} For loops that count up in steps of one. Study the
following code and verify that it prints out "2 3 4 5 6 7 8 9 10" by
compiling and running it. Notice that the @code{System.out.print()}
@strong{@code{function}} call doesn't print a carriage return after printing the
argument value. That is why the @code{System.out.println()} @strong{@code{function}} call
is needed at the end of the for loops @strong{@code{superfor}} and @strong{@code{for}}, to print a
carriage return at the end of the line. Also note the use of the plus
sign to concatenate a string and the number to produce string result.

@cindex Introducing the @code{System.out.print} construct
@cindex Introducing the @code{System.out.println} construct
@cindex @code{System.out.print} construct, introducing
@cindex @code{System.out.println} construct, introducing
@cindex Introducing the @strong{@code{superfor}} construct
@cindex @strong{@code{superfor}} construct, Introducing

@example
@strong{@code{class}} ForTest
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}} )
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* Here is the superfor loop: */}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i=2 @strong{@code{to}} 10) System.out.print(" " + i);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* Here is the ordinary for loop: */}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{for}} (@strong{@code{var}} int i=2; i<=10; i=i+1) System.out.print(" " + i);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example



@strong{Question 4.3.1b:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "5 6 7 8 9 10".

@strong{Question 4.3.1c:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "234 235 236 237 238".

@strong{Question 4.3.1d:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "48 49 50 ... 75 76".

@strong{Question 4.3.1e:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "-5 -4 -3 -2 -1 0 1 2 3".

@strong{Question 4.3.2a:} For loops that count up in steps greater than
one. Study the following code and verify that it prints out "10 15 20
25 30 35 40" by compiling and running it.

@example
@strong{@code{class}} ForTest
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}} )
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* Here is the superfor loop: */}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i=10 @strong{@code{to}} 40 step 5) System.out.print(" " + i);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* Here is the ordinary for loop: */}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{for}} (@strong{@code{var}} int i=10; i<=40; i=i+5) System.out.print(" " + i);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.3.2b:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "20 25 30 35 40".

@strong{Question 4.3.2c:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "100 105 110 115 120 125".

@strong{Question 4.3.2d:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "2 4 6 8 10 12 14".

@strong{Question 4.3.2e:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "10 13 16 19 22 25".

@strong{Question 4.3.3a:} For loops that count down in steps of one. Study the
following code and verify that it prints out "10 9 8 7 6 5 4 3 2 1" by
compiling and running it.

@example
@strong{@code{class}} ForTest
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* Here is the superfor loop: */}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} @code{int} i=10 @strong{@code{downto}} 1) System.out.print(" " + i);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* Here is the ordinary for loop: */}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{for}} (@strong{@code{var}} int i=10; i>=1; i=i-1) System.out.print(" " + i);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.3.3b:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "10 9 8 7 6 5 4".

@strong{Question 4.3.3c:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "20 19 18 17 16 15 14 13 12".

@strong{Question 4.3.3d:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "66 65 64 ... 47".

@strong{Question 4.3.3e:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "3 2 1 -1 -2 -3 -4 -5 -6 -7".

@strong{Question 4.3.4a:} For loops that count down in steps greater than
one. Study the following code and verify that it prints out "100 90 80
70 60 50 40 30 20" by compiling and running it.

@example
@strong{@code{class}} ForTest
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* Here is the superfor loop: */}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i=100 @strong{@code{downto}} 20 step -10) System.out.print(" " + i);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* Here is the ordinary for loop: */}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{for}} (@strong{@code{var}} int=100; i>=20; i=i-10) System.out.print(" " + i);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.3.4b:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "80 70 60 50 40 30 20".

@strong{Question 4.3.4c:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "500 490 480 470 460".

@strong{Question 4.3.4d:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "10 8 6 4 2 0".

@strong{Question 4.3.4e:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "33 28 23 18 13 8 3".

@strong{Question 4.3.5a:} For loops that use floating point numbers to
count. Study the following code and verify that it prints out "1.1 2.2
3.3 4.4" by compiling and running it. The type name double is short
@strong{@code{superfor}} double precision floating point. It is natural to ask: why not use
single precision floating point? The answer to this question is that
double precision floating point gives fewer compilation errors than
single precision floating point does.

@example
@strong{@code{class}} ForTest
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}} )
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* Here is the superfor loop: */}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} double i=1.1 @strong{@code{to}} 4.4 step 1.1) System.out.print(" " + i);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* Here is the ordinary for loop: */}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{for}} (@strong{@code{var}} double i=1.1; i<=4.4; i=i+1.1) System.out.print(" " + i);
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.3.5b:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "0 2.2 4.4 6.6". Note that rounding errors
may prevent you from getting this exact answer. Also note that the
answer to this question is not what your would naively expect without
running the code.

@strong{Question 4.3.5c:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "-30 -19.9 -9.8 0.3
10.4 20.5".

@strong{Question 4.3.5d:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "100.0 96.7 93.4 90.1
86.8 83.5 80.2 76.9".

@strong{Question 4.3.5e:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "-100.0 -105.5 -111.0
-116.5".

@strong{Question 4.3.6a:} For loops that use chars to count. Study the following
code and verify that it prints out "a b c d e f g h i j k l m n o p q
r s t u v w x y z" by and running it.

@example
@strong{@code{class}} ForTest
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* Here is the superfor loop: */}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} char i='a' @strong{@code{to}} 'z') System.out.print(" " + i);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* Here is the ordinary for loop: */}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{for}} (@strong{@code{var}} char i='a'; i<='z'; i=i+1) System.out.print(" " + i);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.3.6b:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "a b c d e f".

@strong{Question 4.3.6c:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "z y x w v u t s r q p o n m l k j i h g f e d c b a".

@strong{Question 4.3.6d:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "p o n m l k j i h".

@strong{Question 4.3.6e:} Change the @strong{@code{superfor}} loop and the ordinary @strong{@code{for}}
loop to print out the following numbers: "A B C D E F G H I J K L M N O P Q R S T U V W X Y Z".




@node    Tutorial 4 Four looping constructs
@section Tutorial 4 Four looping constructs

@strong{Question 4.4.1:} Study, compile and run the following code:

@example
@strong{@code{class}} LoopTest
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{function}} @code{int} powerOf2A(@code{int} n)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} @code{int} counter = n;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} @code{int} result  = 1;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{while}} (counter > 0)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} result = 2 * result;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} counter = counter - 1;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{return}} result;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{function}} @code{int} powerOf2B(@code{int} n)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} @code{int} counter = n;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} @code{int} result  = 1;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{do}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} result = 2 * result;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} counter = counter - 1;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}} @strong{@code{while}} (counter > 0);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{return}} result;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{function}} @code{int} powerOf2C(int n)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} @code{int} result = 1;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{for}} (@strong{@code{var}} @code{int} counter = n; counter > 0; counter = counter - 1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} result = 2 * result;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{return}} result;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{function}} @code{int} powerOf2D(int n)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} @code{int} result = 1;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} @code{int} counter=n @strong{@code{downto}} 1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} result = 2 * result;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{return}} result;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{}  /**
@tie{}@tie{}@tie{}   * Prints a row of stars of a given length.
@tie{}@tie{}@tie{}   */
@tie{}@tie{}@tie{} @strong{@code{function}} void printLineC(int length)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{for}} (@strong{@code{var}} int i = 0; i<length; i=i+1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.print("#");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{// For Question 4.4.1 add some code here...}
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@cindex Introducing @strong{@code{while}} loops @strong{@code{do}} ... @strong{@code{while}} loops
@cindex @strong{@code{while}} loop
@cindex @strong{@code{do}} ... @strong{@code{while}} loop
@cindex @strong{@code{for}} loop

@strong{Question 4.4.2:} To the @strong{@code{main}} @strong{@code{function}} add some code to call the
functions @code{powerOf2A}, @code{powerOf2B}, @code{powerOf2C} and
@code{powerOf2D} to verify that they all return the same result. To
inspect the result you will need to apply the @code{System.out.println()}
statement to the values returned by those functions.

@strong{Question 4.4.3:} There is a bug in the @code{powerOf2B} @strong{@code{function}}
because it does not behave correctly in the case when @code{n} is zero or
less. Put an @strong{@code{if}} (...) @strong{@code{then}} ... statement at the top of this @strong{@code{function}}
to make it handle the case of zero properly.  Also make it return 1 in
the case that @code{n} is less than zero.

@strong{Question 4.4.4:} There is a bug in the @code{powerOf2D} @strong{@code{function}}
because it does not behave correctly in the case when n is zero or
negative.  Make it return 1 if @code{n <= 0}.  Put an @strong{@code{if}} (...) @strong{@code{then}} ...
statement at the top of this @strong{@code{function}} to make it handle these cases
properly.  Since this @strong{@code{function}} returns an @code{int}, make it return 1 in
these cases.

@strong{Question 4.4.5:} By copying the pattern of @code{powerOf2A},
@code{powerOf2B}, @code{powerOf2C} and @code{powerOf2D}, write functions
@code{printLineA}, @code{printLineB} and @code{printLineD} that work
identically to the @strong{@code{function}} @code{printLineC}, except that they use @strong{@code{while}}
loops, @strong{@code{do}} loops and @strong{@code{superfor}} loops, respectively. Add some code to the
@strong{@code{main}} @strong{@code{function}} to test them out.

@strong{Question 4.4.6:} Based on the previous three questions, is there a best
looping construct? Or does it depend on what the looping construct is
going to be used for?

@cindex The best of the four looping constructs @strong{@code{superfor}}, @strong{@code{for}}, @strong{@code{while}} and @strong{@code{do}} ... @strong{@code{while}}



@node    Tutorial 5 A beer drinking song
@section Tutorial 5 A beer drinking song

@strong{Question 4.5.1:} Study the following code and then compile and run it to
verify that it prints out the lyrics to a popular song:

@cindex Beer drinking song

@example
@strong{@code{class}} BeerSong
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Five bottles of beer on the wall.");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Five bottles of beer on the wall.");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("If one bottle of beer should accidentally fall,");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("there'd be four bottles of beer on the wall.");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Four bottles of beer on the wall.");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Four bottles of beer on the wall.");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("If one bottle of beer should accidentally fall,");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("there'd be three bottles of beer on the wall.");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Three bottles of beer on the wall.");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Three bottles of beer on the wall.");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("If one bottle of beer should accidentally fall,");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("there'd be two bottles of beer on the wall.");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Two bottles of beer on the wall.");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Two bottles of beer on the wall.");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("If one bottle of beer should accidentally fall,");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("There'd be one bottle of beer on the wall.");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("One bottle of beer on the wall.");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("One bottle of beer on the wall.");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("If one bottle of beer should accidentally fall,");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("there'd be no bottles of beer on the wall.");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.5.2:} The following is the first attempt to make the code
smaller but to keep the same output: If you compile and run the
following code you will notice that it counts up from one rather than
down from n. Change the for loop so that it runs down rather than
up. For information about how to write the for loop, please consult
Tutorial 4.2.

@example
@strong{@code{class}} BeerSong
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{function}} song(int n)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i=1 @strong{@code{to}} n)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println(i + " bottles of beer on the wall");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println(i + " bottles of beer on the wall");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("If one bottle of beer should accidentally fall,");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("there'd be " + (i-1) + " bottles of beer on the wall");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} song(5);
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.5.3:} Finish the @code{number2string} @strong{@code{function}} below and add a
new @strong{@code{function}} call to this @strong{@code{function}} in the song @strong{@code{function}} so that it
print textual numbers rather than digits.

@example
@strong{@code{function}} String number2string(int n)
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{assert}} n>=0 : n;
@tie{}@tie{}@tie{} @strong{@code{assert}} n<=10: n;
@tie{}@tie{}@tie{} if (n == 0) then return "no";
@tie{}@tie{}@tie{} if (n == 1) then return "one";
@tie{}@tie{}@tie{} if (n == 2) then return "two";
@tie{}@tie{}@tie{} /* rest of code goes here */
@tie{}@tie{}@tie{} if (n == 9) then return "nine";
@tie{}@tie{}@tie{} if (n == 10) then return "ten";
@tie{}@tie{}@tie{} @strong{@code{assert}} @strong{@code{false}};
@strong{@code{end}}
@end example

@strong{Question 4.5.4:} Add a new @strong{@code{function}} @code{String capitalize(String s)}
that capitalizes the first word in a @code{String} and call this @strong{@code{function}}
from the song @strong{@code{function}} so that the first words in each sentence are
capitalized. You should find the @strong{@code{function}} @code{Character.toUpperCase}
and the methods @code{charAt} and @code{substring} in the package
@code{java.lang} helpful for writing this @strong{@code{function}}. See the @strong{@code{class}} @code{String}
in the @strong{@code{package}} @code{java.lang} at
@url{http://docs.oracle.com/javase/1.5.0/docs/api} for more details.

@strong{Question 4.5.5:} Add new @strong{@code{function}} call @code{String plural(int n)} that
returns the string "s" if n is not equal to 1 and the empty string ""
otherwise. Then call this @strong{@code{function}} from the song @strong{@code{function}} so that the
phrase "bottle" is pluralized when it should be.

@strong{Question 4.5.6:} Write a @strong{@code{function}} called @code{number2string2} that can
handle values up to but not including 100. Note that you will need
multiple @strong{@code{if}} ... @strong{@code{then}} statements to achieve this. Note that if @code{n}
is a number then the following expressions are useful:

@example
@tie{}@tie{}@tie{}  @strong{@code{var}} int temp1 = n / 10 % 10 results in temp1 holding the tens digit of n and is zero in the case that n<10.
@tie{}@tie{}@tie{}  @strong{@code{var}} int temp2 = n % 10 results in temp2 holding the ones digit of n.
@end example

Also make it print out "one hundred or more" in the case that n>=100

@strong{Question 4.5.7:} Change the song @strong{@code{function}} so that the following @strong{@code{function}}
call: @code{song(5,"rum");} in the @strong{@code{main}} @strong{@code{function}} results in the following
printout:

@example
Five bottles of rum on the wall.

...

there'd be no bottles of rum on the wall.
@end example

@strong{Question 4.5.8:} Once all the code is working, add the following line to
the @strong{@code{main}} @strong{@code{function}}: @code{song(100,"gin");} so that it prints out the
following:

@example
One hundred bottles of gin on the wall.

...

there'd be zero bottles of gin on the wall.
@end example

@strong{Question 4.5.9:} Write a new @strong{@code{function}} @code{number2string3} that works like
@code{number2string2} and @code{number2string} except that it handles
numbers up to 999. Internally @code{number2string3} should call
@code{number2string2}. You might find the following @strong{@code{function}} useful:

@example
@strong{@code{function}} String textand(String a, String b)
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{if}} (a.equals("") or b.equals("")) @strong{@code{then}} @strong{@code{return}} a + b;
@tie{}@tie{}@tie{} @strong{@code{else}} @strong{@code{return}} a + " and " + b;
@strong{@code{end}}
@end example

@strong{Question 4.5.10:} @strong{Tricky!} Write a new @strong{@code{function}} @code{number2string4} that works
like number2string3 execpt that it handles numbers up to nine hundred
and ninety-nine million nine hundred and ninety-nine thousand nine
hundred and ninety-nine, i.e. 999,999,999. The @strong{@code{function}} number2string4
should internally call number2string3 like so:

@example
@strong{@code{var}} String ones = number2string3(n % 1000);
@strong{@code{var}} String thousands = number2string3(n / 1000 % 1000);
@strong{@code{var}} String millions = number2string3(n / 1000 / 1000 % 1000);
@end example

@noindent Note that the variables above will have values from 0 to 999
inclusive.



@node    Tutorial 6 Class variables
@section Tutorial 6 Class variables

@strong{Question 4.6.1:} Study, compile and run the following code. Note the use
of the class variable @code{myMoney}. A class variable is different from a
variable that is local to a @strong{@code{function}} because the lifetime of the class
variable is for the duration that the program is run, whereas the
lifetime of a local variable is for the duration of the @strong{@code{function}}
call. In the code that follows, the variable @code{myMoney} is used to
store a numerical value, for how much money you have.

@cindex Introducing class variables

@example
@strong{@code{class}} Money
@strong{@code{begin}}
@tie{}@tie{}@tie{} @emph{/** Property myMoney stores money value in dollars */}
@tie{}@tie{}@tie{} @strong{@code{classVar}} int myMoney;

@tie{}@tie{}@tie{} @strong{@code{function}} void spend(String item, int value)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} myMoney = myMoney - value;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("*** spent $" +
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{}  value +
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{}  " on " + item +
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{}  ", leaving you with $" + myMoney);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} myMoney = 100;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} spend("aquarium",50);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} spend("shoes",100);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} spend("lipstick",20);
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.6.2:} Change the myMoney class variable so that it is a double
(short for double-precision floating point) rather than an int. You
will need to add a new @strong{@code{function}} money2string that converts double
values into strings. For example the floating point number 1.2345
should be printed out as $1.23. If x is a double then the following
expression converts x from a double into a number of dollars (int)x
and the following expression converts x into a number of cents
(int)(money * 100) - 100 * dollars. Note that you will need to make it
so that $1.03 prints out as this value.

@strong{Question 4.6.3:} Add an if statement to the spend @strong{@code{function}} so that it
uses @code{System.out.println()} to print out an error message if the
person does not have enough funds in their bank account to pay for the
item parameter.

@strong{Question 4.6.4:} Add a new @strong{@code{class}} variable @code{double}
@code{governmentsMoney} and make it so that 12.5% of the cost of each
item goes to the government in the form of G.S.T., which stands for
Goods and Services Tax, a value-added tax.

@strong{Question 4.6.5:} Add a new class variable @code{numBattleships} that records
how many batteships are owned by the government. Write a @strong{@code{function}}
@code{buyBattleShips} that causes the government to buy as many battleships
as it can afford. Make it so that the @code{buyBattleShips} @strong{@code{function}} prints
out how many battleships were purchased. Let the cost of each
battleship be one million dollars and store this value in a variable
called @code{costOfShip}. Please note that if the government's money is less
the one million dollars then no battleships will be purchased.

@strong{Question 4.6.6:} Set the initial value for @code{governmentsMoney} to be two
millions dollars, then call the @code{buyBattleShips} @strong{@code{function}} and verify
that two battleships were purchased.


@node    Tutorial 7 Non-Object arrays
@section Tutorial 7 Non-Object arrays




This tutorial teaches you how to create single-dimensional and
multi-dimensional arrays of non-@code{Object}s. The non-@code{Object} types
in Java are those which aren't declared inside a class, so it includes
the following types: @code{boolean}, @code{char}, @code{int}, @code{float} and @code{double}. A helpful
convention in Java is that the non-object types start with a lowercase
letter, while object types start with an uppercase letter, such as for
example the @code{String} @strong{@code{class}} as an example of an @code{Object} type. In
addition to this, two different array initialization syntaxes are
presented.

@cindex Arrays
@cindex Introducing non-@code{Object} arrays
@cindex Introducing single-dimensional non-@code{Object} arrays
@cindex Arrays of non-@code{Object} type, single-dimensional
@cindex Non-@code{Object} arrays, single-dimensional

@subsection Single-dimensional non-Object arrays

@anchor{Single-dimensional non-Object arrays}

@cindex Arrays of non-@code{Object} type, first initialization syntax
@cindex First initialization syntax for arrays of non-@code{Object} type



@strong{Question 4.7.1:} Here is an example of a convenient one dimensional
array initialization syntax. Study, compile and run the following
code. The code @code{int[]} should be read out loud as int array indicating
the variable a is an int array, also known as an array of ints. Note
that the first value of the for loop below is zero. This is because in
J.T.W. and Java, the first index of an array is zero not one. This
convention harks back to the old days of the C Programming Language
and is used because it is more efficient in the low level of machine
language than counting arrays from one.

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{var}} int[] a = @{ 1,2,3 @};
@tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i=0 to a.length-1)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("a[" + i + "]=" + a[i]);
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{endMain}}
@end example

Due to a design oversight by the creators of Java you cannot use this
syntax to re-initialize an array like so:

@example
a = @{ 4,5,6 @}; @emph{// Compilation error}
@end example

Luckily there is a way array around this oversight and that is to use
a design pattern where you introduce a temporary variable like so:

@example
var int[] temp = @{ 4,5,6 @};
a = temp; @emph{// Array "a" now holds 4 5 6}
@end example

Later you will learn why this design pattern is useful for
re-initializing multi-dimensional arrays.

@strong{Question 4.7.2:} Write a @strong{@code{function}} @code{print} that takes an int array
argument and prints out the array. You will need to use the @code{length}
property of the array parameter so your @strong{@code{function}} works with arbitrary
sized arrays. Change the @strong{@code{main}} @strong{@code{function}} to what follows so that it
contains a call to the @code{print} @strong{@code{function}}.

@example
@strong{@code{var}} int[] a = @{ 1,2,3 @};
print(a);
@end example

@strong{Question 4.7.3:} Write a @strong{@code{function}} with same name as the previous print
@strong{@code{function}}, except that this one should take an argument that is a
double[], also known as a double array. Two functions with the same
name in the same class is allowed in Java and the practice of using
has a special name that is: @emph{@strong{@code{function}} name overloading}. Overloading
is only allowed when the two functions with the same name have
different parameters. When you call an overloaded @strong{@code{function}} J.T.W. and
Java looks at the number and types of the arguments a determines from
this which of the overloaded functions to call. Change the @strong{@code{main}}
@strong{@code{function}} to what follows so that it initializes an array of
double-precision floating point variables and then calls the second
print @strong{@code{function}}.

@example
@strong{@code{var}} double[] b = @{ 1.1,2.2,3.3 @};
print(b);
@end example

@cindex Arrays of non-@code{Object} type, second initialization syntax
@cindex Second initialization syntax for arrays of non-@code{Object}s

Here is an example of a second initialization syntax. For this
particular example it is better to use the simpler, earlier
initialization syntax, but when the size of the array to be created is
to be determined at run-time, then the second syntax should used. The
next question will show you an example of this.

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{var}} int[] a = @code{@strong{new}} int[3]; )
@tie{}@tie{}@tie{} @emph{// at this point the array is all zeroes}
@tie{}@tie{}@tie{} @strong{@code{for}} (var int i=0; i<3; i=i+1)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a[i] = i;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} print(a);
@strong{@code{endMain}}
@end example

@strong{Question 4.7.4:} Write a @strong{@code{function}} create takes one @code{int} argument,
the size of the array to create and returns an @code{int} array of that
size. Make it so the ith element of the array is initialized to
i. Call this @strong{@code{function}} from the @strong{@code{main}} @strong{@code{function}} like so:

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{var}} int[] a = create(3);
@tie{}@tie{}@tie{} print(a);
@strong{@code{endMain}}
@end example

@strong{Question 4.7.5:} Write a @strong{@code{function}} create2 takes one int argument, the
size of the array to create and returns a double array of that
size. Make it so the ith element of the array is initialized to
i.i. Why is it not possible to overload that create @strong{@code{function}}? Try it
and see what the compiler says. Call create2 from the @strong{@code{main}} @strong{@code{function}}
like so:

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{var}} double[] a = create2(3);
@tie{}@tie{}@tie{} print(a);
@strong{@code{endMain}}
@end example

@strong{Question 4.7.6:} Write a @strong{@code{function}} doubler that takes an int array x and
returns a new int array result that is twice as big as x. Copy x into
result before you return it. The extra elements in the result should
all be zero.

@strong{Question 4.7.7:} Change the doubler @strong{@code{function}} so that every zero in the
array result is set to the value 13.

@subsection Two dimensional non-Object arrays

@cindex Two-dimensional non-@code{Object} arrays
@cindex Non-@code{Object} arrays, two-dimensional
@cindex Arrays of non-@code{Object} type, two-dimensional

@strong{Question 4.7.8:} Here is an example of a convenient two dimensional
array initialization syntax. Study, compile and run the following
code. The code int[][] should be read out loud as @emph{int array array}
indicating that the variable @code{a} is an @emph{int array array}, also
known as a @emph{two-dimensional array of ints}.

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{var}} int[][] a = @{ @{ 1,2,3 @} @{ 4,5 @} @{ 6 @} @}

@tie{}@tie{}@tie{} @strong{@code{for}} (var int y=0; y<a.length; y=y+1)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{for}} (var int x=0; x<a[y].length; x=x+1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.print(" " + a[y][x]);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{endMain}}
@end example

@strong{Question 4.7.9:} By copying the pattern of the code above, do some more
overloading of the print @strong{@code{function}} by writing two new print functions,
one taking a two dimensional array of ints, the other taken a two
dimensional array of doubles. The call both of these functions from
the @strong{@code{main}} @strong{@code{function}}.

@cindex Function name overloading

Note that if x is a two dimensional array of ints, then x[i] is a one
dimensional array of ints for each in the range 0 ... x.length-1. Note
that in the above code, a[0] is an array of three ints, a[1] is an
array of two ints and a[2] is an array of one int. The reason these
sub-arrays are all of different sizes is to save your computer's
precious memory. For example you can have one sub-array much longer
than all of the others without needing to allocate a whole bunch of
memory that will go unused. Since a[0] is an int array, you would
naively expect it to be able to be re-initialized like so:

@example
a[0] = @{ 4,5,6,7@};)
@end example

so that after this code @code{a[0]} holds the four element long array
4,5,6 and 7. But as mentioned above in @ref{Single-dimensional
non-Object arrays}, this doesn't work because of a design oversight by
the creators of Java. Luckily as mentioned above there is a way around
this oversight and that is to use a temporary variable like so:

@example
var int[] temp = @{ 4,5,6,7@};
a[0] = temp;) @emph{// Array "a[0]" now holds 4 5 6 7}
@end example

Like with one dimensional arrays, there is a second initialization
syntax for two dimensional arrays and here it is. Unlike the above
code the sub-arrays a[0], a[1] and a[2] are all of equal size, namely
three.

@example
@strong{@code{var}} int[][] a = new int[3][3];
a[0][0] = 1; a[1][0] = 2; a[2][0] = 3;
a[0][1] = 4; a[1][1] = 5;
a[0][2] = 6;
@end example

@strong{Question 4.7.10:} Write a @strong{@code{function}} create3 and create4 that takes on int
argument size and returns a two dimensional array of ints or doubles,
respectively. Make is so that if a is the name of the returned array,
then a[y][x] is set to the value of x+y.

@subsection Three-dimensional non-Object arrays

@cindex Three-dimensional non-@code{Object} arrays
@cindex Arrays of non-@code{Object} type, three-dimensional

@strong{Question 4.7.11:} Using the knowledge you have gained so far about
arrays, create, initialize and print a three-dimensional array of
ints.




@node    Tutorial 8 Accessing functions and class variables from another class
@section Tutorial 8 Accessing functions and class variables from another class




@strong{Question 4.8.1:} Study, compile and run the following code which resides
in a file called @code{Box.jtw}. Notice the use of @code{System.out.print()}
to print without a trailing newline and @code{System.out.println()} to
print with a trailing newline. The @emph{ln} part tells you this.

@example
@strong{@code{class}} Box
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{function}} void square(int n)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (var int y=0 @strong{@code{to}} n-1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (var int x=0 @strong{@code{to}} n-1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{if}} ((x == 0) @strong{@code{or}} (x == n-1) @strong{@code{or}} (y == 0) @strong{@code{or}} (y == n-1))
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{then}} System.out.print("#");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{else}} System.out.print(" ");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} square(5);
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

Notice that here is the output of the above code for different values
of the n parameter:

@multitable @columnfractions .25 .25
@item n=1 @*
@tab @code{#} @*
@item n=2 @*
@tab @code{##} @*
     @code{##} @*
@*
@item n=3 @*
@tab @code{###} @*
     @code{#@tie{}#} @*
     @code{###} @*
@*
@item n=4 @*
@tab @code{####} @*
     @code{#@tie{} #} @*
     @code{#@tie{} #} @*
     @code{####} @*
@*
@item n=5 @*
@tab @code{#####} @*
     @code{#@tie{} @tie{}#} @*
     @code{#@tie{} @tie{}#} @*
     @code{#@tie{} @tie{}#} @*
     @code{#####} @*
@end multitable

@strong{Question 4.8.2:} By copying the pattern established in the above code,
write a now @strong{@code{function}} square2 that generates the following output. Note
that you will need to remove some of the or clauses in the square
method above to get the following output:

@multitable @columnfractions .25 .25
@item n=1 @*
@tab @code{#} @*
@*
@item n=2 @*
@tab @code{##} @*
     @code{##} @*
@*
@item n=3 @*
@tab @code{###} @*
     @code{} @*
     @code{###} @*
@*
@item n=4 @*
@tab @code{####} @*
     @code{} @*
     @code{} @*
     @code{####} @*
@*
@item n=5 @*
@tab @code{#####} @*
     @code{} @*
     @code{} @*
     @code{} @*
     @code{#####} @*
@*
@end multitable

@strong{Question 4.8.3:} By copying the pattern established in the above code,
write a now @strong{@code{function}} square3 that generates the following output: n=1

@multitable @columnfractions .25 .25
@item n=1 @*
@tab @code{#} @*
@*
@item n=2 @*
@tab @code{##} @*
     @code{##} @*
@*
@item n=3 @*
@tab @code{#@tie{}#} @*
     @code{#@tie{}#} @*
     @code{#@tie{}#} @*
@*
@item n=4 @*
@tab @code{#@tie{} #} @*
     @code{#@tie{} #} @*
     @code{#@tie{} #} @*
     @code{#@tie{} #} @*
@*
@item n=5 @*
@tab @code{#@tie{} @tie{}#} @*
     @code{#@tie{} @tie{}#} @*
     @code{#@tie{} @tie{}#} @*
     @code{#@tie{} @tie{}#} @*
     @code{#@tie{} @tie{}#} @*
@*
@end multitable

@strong{Question 4.8.4:} Study, compile and run the following code which resides
in a file called Box.java:

@example
@strong{@code{class}} Box
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{function}} void x(int n)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (var int y=0 t0 n-1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (var int x=0 @strong{@code{to}} n-1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{if}} ((x == y) @strong{@code{or}} (x == n-1-y)) then System.out.print("#");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{else}} System.out.print(" ");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} x(5);
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

Notice that here is the output of the above code for different values
of the n parameter:

@multitable @columnfractions .25 .25
@item n=1 @*
@tab @code{#} @*
@*
@item n=2 @*
@tab @code{##} @*
     @code{##} @*
@*
@item n=3 @*
@tab @code{# #} @*
     @code{@tie{}#@tie{}} @*
     @code{# #} @*
@*
@item n=4 @*
@tab @code{#@tie{} #} @*
     @code{@tie{}## } @*
     @code{@tie{}## } @*
     @code{#@tie{} #} @*
@*
@item n=5 @*
@tab @code{# @tie{} #} @*
     @code{@tie{}# # } @*
     @code{@tie{} #  } @*
     @code{@tie{}# # } @*
     @code{# @tie{} #} @*
@*
@end multitable

@strong{Question 4.8.5:} By copying the pattern established in the above code,
write a now @strong{@code{function}} x2 that generates the following output. Note that
you will need to remove one of the or clauses in the @code{x} @strong{@code{function}}
above to get the following output:

@multitable @columnfractions .25 .25
@item n=1 @*
@tab @code{#} @*
@*
@item n=2 @*
@tab @code{# } @*
     @code{@tie{}#} @*
@*
@item n=3 @*
@tab @code{#  } @*
     @code{@tie{}# } @*
     @code{@tie{} #} @*
@*
@item n=4 @*
@tab @code{#   } @*
     @code{@tie{}#  } @*
     @code{@tie{} # } @*
     @code{@tie{} @tie{}#} @*
@*
@item n=5 @*
@tab @code{#    } @*
     @code{@tie{}#   } @*
     @code{@tie{} #  } @*
     @code{@tie{} @tie{}# } @*
     @code{@tie{} @tie{} #} @*
@*
@end multitable

@strong{Question 4.8.6:} By copying the pattern established in the above code,
write a now @strong{@code{function}} @code{x3} that generates the following output. Note that
you will need to remove one of the or clauses in the x method above to
get the following output:

@multitable @columnfractions .25 .25
@item n=1 @*
@tab @code{#} @*
@*
@item n=2 @*
@tab @code{@tie{}#} @*
     @code{# } @*
@*
@item n=3 @*
@tab @code{@tie{} #} @*
     @code{@tie{}# } @*
     @code{#  } @*
@*
@item n=4 @*
@tab @code{@tie{} @tie{}#} @*
     @code{@tie{} # } @*
     @code{@tie{}#  } @*
     @code{#   } @*
@*
@item n=5 @*
@tab @code{@tie{} @tie{} #} @*
     @code{@tie{} @tie{}# } @*
     @code{@tie{} #  } @*
     @code{@tie{}#   } @*
     @code{#    } @*
@*
@end multitable

@strong{Question 4.8.7:} Study, compile and run the following code which resides
in a file called Box.java:

@example
@strong{@code{class}} Box
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{function}} void triangle(int n)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int y=0 @strong{@code{to}} n-1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int x=0 @strong{@code{to}} n-1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{if}} (x < y)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{then}} System.out.print("#");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{else}} System.out.print(" ");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} triangle(5);
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

Notice that here is the output of the above code for different values
of the n parameter: n=1

@multitable @columnfractions .25 .25
@item n=1 @*
@tab @code{#} @*
@*
@item n=2 @*
@tab @code{# } @*
     @code{##} @*
@*
@item n=3 @*
@tab @code{#  } @*
     @code{## } @*
     @code{###} @*
@*
@item n=4 @*
@tab @code{#   } @*
     @code{##  } @*
     @code{### } @*
     @code{####} @*
@*
@item n=5 @*
@tab @code{#    } @*
     @code{##   } @*
     @code{###  } @*
     @code{#### } @*
     @code{#####} @*
@*
@end multitable

@strong{Question 4.8.8:} By copying the pattern established in the above code,
write a new @strong{@code{function}} triangle2 that generates the following
output. Note that you will need to change the @strong{@code{if}} clause in the
triangle method above to get the following output: n=1

@multitable @columnfractions .25 .25
@item n=1 @*
@tab @code{#} @*
@*
@item n=2 @*
@tab @code{##} @*
     @code{# } @*
@*
@item n=3 @*
@tab @code{###} @*
     @code{## } @*
     @code{#  } @*
@*
@item n=4 @*
@tab @code{####} @*
     @code{### } @*
     @code{##  } @*
     @code{#   } @*
@*
@item n=5 @*
@tab @code{#####} @*
     @code{#### } @*
     @code{###  } @*
     @code{##   } @*
     @code{#    } @*
@*
@end multitable

@strong{Question 4.8.9:} Write a new @strong{@code{function}} called box that generates the
following output. Note that you will need to modify the triangle
method above to get the following output:

@multitable @columnfractions .25 .25
@item n=1 @*
@tab @code{#} @*
@*
@item n=2 @*
@tab @code{##} @*
     @code{##} @*
@*
@item n=3 @*
@tab @code{###} @*
     @code{###} @*
     @code{###} @*
@*
@item n=4 @*
@tab @code{####} @*
     @code{####} @*
     @code{####} @*
     @code{####} @*
@*
@item n=5 @*
@tab @code{#####} @*
     @code{#####} @*
     @code{#####} @*
     @code{#####} @*
     @code{#####} @*
@*
@end multitable

@strong{Question 4.8.10:} Add the following code to Box.java:

@cindex Introducing boolean arrays

@example
@strong{@code{class}} Grid
@strong{@code{begin}}
@tie{}@tie{}@tie{} @emph{/* NOTE: the use of "final" below to denote a value whose value cannot be changed. */}
@tie{}@tie{}@tie{} @strong{@code{final}} @strong{@code{classVar}} int SIZE = 20;

@tie{}@tie{}@tie{} @emph{/* NOTE: the array below is a two-dimensional array */}
@tie{}@tie{}@tie{} @strong{@code{classVar}} boolean[][] array = new boolean[SIZE][SIZE];

@tie{}@tie{}@tie{} @strong{@code{function}} void set(int x, int y, boolean v)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{if}} ((x>=0) @strong{@code{and}} (x<SIZE) @strong{@code{and}} (y>=0) @strong{@code{and}} (y<SIZE)) @strong{@code{then}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} array[x][y] = v;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{function}} void print(int size)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (var int y=0 @strong{@code{to}} size-1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (var int x=0 @strong{@code{to}} size-1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{if}} (array[x][y])
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{then}} System.out.print("#");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{else}} System.out.print(" ");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();) @emph{// prints an empty line between shapes}
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}
@end example

@cindex How to access class variables and functions from another class
@cindex Accessing class variables and functions from another class
@cindex Class variables from another class, accessing

@strong{Question 4.8.11:} The following question will guide you through the
process of making the drawing algorithm more powerful. Instead of
printing the shapes directly to the screen, they will be stored in an
array to be printed out only when the array has been completely
set. You don't need to know a great deal about arrays to answer the
remaining questions of this section as the array code has been written
for you in the @code{Grid} @strong{@code{class}} above. For every call to
@code{System.out.println()} in @code{Box.java}, replace it with a call to
the @code{set} @strong{@code{method}} of the @code{Grid} @strong{@code{class}}. Note that the third
parameter in the @code{set} @strong{@code{method}} is of type @code{boolean}, that is to say it
must be either @strong{@code{true}} or @strong{@code{false}}. To call a @strong{@code{function}} of another @strong{@code{class}} you
need to prefix the name of the @strong{@code{class}} like so: @code{Grid.set(/* argument
values */)}. Finally at the end of all of the functions in the @code{Box}
@strong{@code{class}} except for the @strong{@code{main}} @strong{@code{function}} you will need to call the
@code{Grid.print} method of the @code{Grid} @strong{@code{class}} to actually print out the
array.

@strong{Question 4.8.12:} Re-initialize the boolean array array named
@code{array} from the @strong{@code{main}} @strong{@code{function}} of the @code{Box} @strong{@code{class}}.  @strong{HINT:} to
access a @strong{@code{class}} variable from another @strong{@code{class}}, you need to prefix it with
the name of its @strong{@code{class}} name, in this case it is @code{Grid}.
Re-initialize the @code{array} variable to a two-dimensional array of
dimensions 100 x 100.  Also set the @code{size} variable to 100 so that
the functions of the @code{Grid} class still work.







@node    Tutorial 9 Mapping class variables to instance variables (also known as properties) and functions to methods
@section Tutorial 9 Mapping class variables to instance variables (also known as properties) and functions to methods


@subsection Elementary classes: using a single class for everything

For the purpose of the text that follows, O.O.P. stands for @emph{Object
Oriented Programming}.

@strong{Question 4.9.1:} Study, compile and run the following code:

@example
@strong{@code{class}} PersonDriver1
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{classVar}} String homersName = "Homer Simpson";
@tie{}@tie{}@tie{} @strong{@code{classVar}} int    homersAge  = 40; @emph{// Homer's age in years}

@tie{}@tie{}@tie{} @strong{@code{classVar}} String fredsName  = "Fred Flintstone";
@tie{}@tie{}@tie{} @strong{@code{classVar}} int    fredsAge   = 45; @emph{// Fred's age in years}

@tie{}@tie{}@tie{} @strong{@code{classVar}} String darthsName = "Darth Vader";
@tie{}@tie{}@tie{} @strong{@code{classVar}} int    darthsAge  = 55; @emph{// Darth's age in years}

@tie{}@tie{}@tie{} @strong{@code{function}} void growHomer()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} homersAge = homersAge + 1;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{function}} void growFred()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} fredsAge = fredsAge + 1;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{function}} void growDarth()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} darthsAge = darthsAge + 1;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{function}} void knightHomer()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} homersName = "Sir " + homersName;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{function}} void knightFred()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} fredsName = "Sir " + fredsName;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{function}} void knightDarth()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} darthsName = "Sir " + darthsName;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{function}} void printHomer()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("I am " + homersName + ", my age is " + homersAge);
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{function}} void printFred()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("I am " + fredsName + ", my age is " + fredsAge);
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{function}} void printDarth()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("I am " + darthsName + ", my age is " + darthsAge);
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} growHomer();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} knightHomer();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} printHomer();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} printFred();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} printDarth();
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.9.2:} By copying the pattern established in the existing
code write a some new class variables to represent a new person called
Barak Obama.  Note that he was born August 4, 1961 so at the time of
writing this manual he is 54 years old.


@strong{Question 4.9.3:} Then write some functions to work with this new person.

@strong{Question 4.9.4:} Finally call those functions from the @strong{@code{main}} @strong{@code{function}}.

@subsection Improved classes: one object per class

As your program gets large (say over 1000 lines) then it becomes no
longer practical to put all of your code in the same class. So it is
natural to put each piece of related code in its own class.  The J.T.W.
programming language supports splitting a class into its constituent
methods and having one file for each method.  Simply use the @strong{@code{include}}
directive and J.T.W. will include the file for you like so:

@code{include "a.method";}

will include a method named @code{a}.

@strong{Question 4.9.5:} Study, compile and run the following code: Each of
these classes can be put in their own file. For each class @code{X}, this
class can be put into a file called @code{X.jtw}. However for the
purposes of this tutorial you will probably find it easier to merge
all of the classes into the same file into a file called
@code{PersonDriver2.jtw}

@example
@strong{@code{class}} Homer
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{classVar}} String name = "Homer Simpson";
@tie{}@tie{}@tie{} @strong{@code{classVar}} int    age  = 40;) @emph{// Homer's age in years}

@tie{}@tie{}@tie{} @strong{@code{function}} void grow()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} age = age + 1;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{function}} void knight()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} name = "Sir " + name;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{function}} void print()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("I am " + name + ", my age is " + age);
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} Fred
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{classVar}} String name = "Fred Flintstone";
@tie{}@tie{}@tie{} @strong{@code{classVar}} int    age  = 45;) @emph{// Fred's age in years}

@tie{}@tie{}@tie{} @strong{@code{function}} void grow()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} age = age + 1;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{function}} void knight()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} name = "Sir " + name;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{function}} void print()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("I am " + name + ", my age is " + age);
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} Darth
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{classVar}} String name = "Darth Vader";
@tie{}@tie{}@tie{} @strong{@code{classVar}} int    age  = 55;) @emph{// Darth's age in years}

@tie{}@tie{}@tie{} @strong{@code{function}} void grow()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} age = age + 1;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{function}} void knight()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} name = "Sir " + name;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{function}} void print()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("I am " + name + ", my age is " + age);
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} PersonDriver2
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} Homer.grow();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} Fred.knight();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} Homer.print();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} Fred.print();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} Darth.print();
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.9.6:} By copying the pattern established in the existing
code write a new class to represent Barak Obama.

@strong{Question 4.9.7:} Call the functions from the @strong{@code{main}} @strong{@code{function}} of the driver
class.

@subsection True O.O.P.: more than one object per class

To allow for more than one object per class, most if not all class
variables needs to be made into what are called instance variables (or
more simply and more commonly known as properties) and most if not all
functions need to be made into what are called methods.

@cindex Mapping from class variables -> instance variables (also known as properties)
@cindex Mapping from functions -> methods

@strong{Question 4.9.8:} Study, compile and run the following code:

@example
@strong{@code{class}} Person
@strong{@code{begin}} )
@tie{}@tie{}@tie{} @emph{/*
@tie{}@tie{}@tie{} * NOTE: the use of the "property" keyword here instead of the
@tie{}@tie{}@tie{} * "classVar" keyword.
@tie{}@tie{}@tie{} */}
@tie{}@tie{}@tie{} @strong{@code{property}} String name; @emph{// Person's full name}
@tie{}@tie{}@tie{} @strong{@code{property}} int    age;  @emph{// Person's age in years}

@tie{}@tie{}@tie{} @emph{/*
@tie{}@tie{}@tie{} * NOTE: the use of the "method" keyword here instead of the
@tie{}@tie{}@tie{} * "@strong{@code{function}}" keyword.
@tie{}@tie{}@tie{} */}
@tie{}@tie{}@tie{} @strong{@code{method}} void grow()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} age = age + 1;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{method}} void knight()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} name = "Sir " + name;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{method}} void print()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("I am " + name + ", my age is " + age);
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{beginMain}}

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Person h = new Person();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} h.name = "Homer Simpson";
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} h.age  = 40;

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Person f = new Person();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} f.name = "Fred Flintstone";
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} f.age  = 45;

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Person d = new Person();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} d.name = "Darth Vader";
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} d.age  = 55;

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} h.grow();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} h.knight();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} h.print();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} f.print();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} d.print();
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

In the above code, note the use of three references h, f and d.

@strong{Question 4.9.9:} By copying the pattern established in the existing
code add some code to the @strong{@code{main}} @strong{@code{function}} add some code to create a new
person for Barak Obama.

@cindex A common design pattern: @strong{@code{private}} properties, @strong{@code{public}} constructor and @strong{@code{public}} getters
@cindex Design pattern: @strong{@code{private}} properties, @strong{@code{public}} constructor and @strong{@code{public}} getters
@cindex @strong{@code{private}} properties, @strong{@code{public}} constructor and @strong{@code{public}} getters, a common design pattern

@subsection A common design pattern: @strong{@code{private}} properties,@strong{@code{public}} @strong{@code{constructor}} and @strong{@code{public}} getters

@cindex Encapsulation

A common design pattern in Java and one that I present for you in the
following code is to make all of the properties of a class effectively
read-only to all client classes by making all of the properties
private and providing non-private getter methods for getting the
values of the properties. It is possible for the original class to
change the values of the properties but other classes (such as
PersonTest below) are not capable of doing this, without calling a
method of the original class such the grow and knight methods of the
Person class. Finally an additional thing known as a @strong{@code{constructor}} is
used to ensure that objects are initialized with meaningful values for
their properties.

@strong{Question 4.9.10:} Study, compile and run the following code:

@example
@strong{@code{class}} Person
@strong{@code{begin}}

@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{property}} String name;
@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{property}} int    age; @emph{// Age in years}
)
@tie{}@tie{}@tie{} @emph{//}
@tie{}@tie{}@tie{} @emph{// NOTE: Getter methods}
@tie{}@tie{}@tie{} @emph{//}
@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} String getName()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} return name;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} int getAge()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} return age;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{constructor}} Person(String aName, int anAge)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} this.name = aName;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} this.age  = anAge;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} void grow()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} age = age + 1;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} void knight()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} name = "Sir " + name;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} void print()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("I am " + name + ", my age is " + age);
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} PersonDriver3
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{//}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{// NOTE: In the following constructor calls the age and name are set by the constructor}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{//}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Person h = new Person("Homer Simpson",40);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Person f = new Person("Fred Flintstone",45);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Person d = new Person("Darth Vader",55);

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} h.grow();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} h.knight();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} h.print();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} f.print();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} d.print();

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} h.name = "Luke Skywalker";)                 @emph{// ERROR: name is private}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} h.age = h.age + 1;                          @emph{// ERROR: age is private}

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("name=" + h.name);       @emph{// ERROR: name is private}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("age="  + h.age);        @emph{// ERROR: age is private}

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("name=" + h.getName());  @emph{// OK: getter is non-private}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("age="  + h.getAge());   @emph{// OK: getter is non-private}
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

Note that you will have to remove the error lines from the above file
for the code to compile.

@strong{Question 4.9.11:} By copying the pattern established in the existing
code add some code to the @strong{@code{main}} @strong{@code{function}} to create a new person called
Hillary Clinton.  Hillary Clinton was born on October 26, 1947 so at
the time of writing this manual she was 68 years old 
@subsection Comparing strings

@strong{Question 4.9.12:} Add a method unknight() which removes the "Sir " title
if he has one. One trap for young players in J.T.W. or Java is to use
the operator == to compare strings like so:

@example
@strong{@code{function}} boolean myCompare(String a, String b)
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{return}} a == b;) @emph{// Works but not as expected!}
@strong{@code{end}}
@end example

It compiles without error, but doesn't give you the result you were
expecting. Instead you need to use the equals method of the String
class like so:

@example
@strong{@code{function}} boolean myCompare(String a, String b)
@strong{@code{begin}}
@tie{}@tie{}@tie{} return a.equals(b);
@strong{@code{end}}
@end example

More generally, if x and y are a references to objects, then x == y
returns whether or not x and y are pointing to the same object,
whereas x.equals(y) returns whether or not the contents of the objects
referred to by x and y are equal. The meaning of the word contents
varies from class to class, but in the case of strings it means that
the strings contain the same data.

You will also find the @code{String} class' substring and
(@code{toUpperCase} or @code{toLowerCase}) methods useful here too. See the
class @code{String} in the package @code{java.lang} at
@url{http://docs.oracle.com/javase/1.5.0/docs/api} for more details of
these two methods.

@subsection The @strong{@code{null}} value for references

@cindex @strong{@code{null}} value for references

As soon as you learn how to use references you need to know that all
reference variables could conceivably hold the value @strong{@code{null}}, meaning no
value. In particular when properties are themselves references as you
will discover in Tutorial 11, then those properties are initialized to
@strong{@code{null}} by default. Object arrays that you will learn about in Tutorial
10 using the second of two initialization syntaxes are also
initialized to @strong{@code{null}} by default.

@cindex The @code{toString} @strong{@code{method}}.
@cindex @code{toString} @strong{@code{method}}.

@subsection Why the toString method is better than any other method or
property for debugging

@cindex @code{NullPointerException}

If x is a reference to a class @code{X} (including this for the current
class) and if @code{m} is a @strong{@code{method}} of @code{X} and @code{p} is a @strong{@code{property}} of
@code{X}, and if @code{x} is currently @strong{@code{null}}, then the following lines result in
a @code{NullPointerException} being thrown when executed:

@example
x.p;
x.m();
@end example

@noindent whereas if @code{x} is @strong{@code{null}} then

@example
@code{System.out.println(x);} and
@code{System.out.println("x=" + x);}
@end example

@noindent prints out, respectively:

@example
@strong{@code{null}}, and
x=@strong{@code{null}}.
@end example

@noindent If @code{x} is not @strong{@code{null}}, it calls

@example
@code{System.out.println(x.toString());}
@code{System.out.println("x=" + x.toString());}
@end example

so these expressions are safer to use than any other method or
property in situations where @code{x} might be null. The syntax of the
@code{toString} @strong{@code{method}} is as follows:

@example
@strong{@code{public}} @strong{@code{method}} String toString()
@strong{@code{begin}}
@tie{}@tie{}@tie{} @emph{// Code goes here...}
@strong{@code{end}}
@end example

Importantly for reasons which will be explained later the toString
method must be declared with @strong{@code{public}} visibility. For other properties
and methods to be used safely with @strong{@code{null}} references you need to wrap a
conditional if construct around the calling of the @strong{@code{method}} or @strong{@code{property}}
like so for properties:

@example
@strong{@code{if}} (x != @strong{@code{null}})
@strong{@code{then}} @strong{@code{begin}}
@tie{}@tie{}@tie{} System.out.println(x.p);
@strong{@code{end}}
@end example

or like so for methods:

@example
@strong{@code{if}} (x != @strong{@code{null}})
@strong{@code{then}} @strong{@code{begin}}
@tie{}@tie{}@tie{} System.out.println(x.m());
@strong{@code{end}}
@end example

Therefore the @code{toString} @strong{@code{method}} is more convenient than any other @strong{@code{method}}
or @strong{@code{property}}.

@cindex Why the @code{toString} method is better than any other @strong{@code{method}} or @strong{@code{property}} for debugging your code

@strong{Question 4.9.13:} Change the @code{print} @strong{@code{method}} above from a @strong{@code{method}} that prints
out to the screen to a @strong{@code{method}} called @code{toString} that returns a
@code{String}.

@cindex Writing your own methods

@strong{Question 4.9.14:} Call the @code{toString} @strong{@code{method}} instead of the @code{print}
methods in the @strong{@code{main}} @strong{@code{function}}.


@node    Tutorial 10 Object arrays
@section Tutorial 10 Object arrays




This tutorial teaches you how to create single-dimensional and
multi-dimensional arrays of @code{Object}s. The @code{Object} types are all
types execept for boolean, char, int, float and double. A helpful
convention in Java is that the @code{Object} types start with an uppercase
letter, while non-@code{Object} types start with a lowercase letter, such as
for example the @code{String} @strong{@code{class}} as an example of an @code{Object} type. In
addition to this, two different array initialization syntaxes are
presented.

@cindex Arrays
@cindex @code{Object} arrays
@cindex Arrays of @code{Object} type, single-dimensional
@cindex Single-dimensional arrays of @code{Object}s

@subsection Single-dimensional arrays of @code{Object}s

@strong{Question 4.10.1:} Here is an example of a convenient one-dimensional
array initialization syntax.  Study, compile and run the following
code.  The code @code{Person}[] should be read out loud as ``person
array'' indicating the variable @code{a} is a @emph{person array}, also known as
an ``array of persons''.

@example
@strong{@code{class}} Person
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{property}} String name;

@tie{}@tie{}@tie{} @strong{@code{constructor}} Person(String aName)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} name = aName;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} String toString()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{return}} name;
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} PersonTest
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Person[] a = @{ new Person("Person # 1"), new Person("Person # 2"), new Person("Person # 3") @};
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i=0 @strong{@code{to}} a.length-1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("a[" + i + "]=" + a[i]);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@cindex Arrays of @code{Object} type, initialization
@cindex Arrays of @code{Object} type, first initialization syntax
@cindex First initialization syntax for arrays of @code{Object}s

Due to a design oversight by the creators of Java you cannot use this
syntax to re-initialize an array like so:

@example
@emph{// Compilation error}
a = @{ new Person("Person # 4"), new Person("Person # 5"), new Person("Person # 6"), new Person("Person # 7") @};
@end example

Luckily there is a way array around this oversight and that is to use
a design pattern where you introduce a temporary variable like so:

@example
@emph{// No error}
@strong{@code{var}} Person[] temp = @{ new Person("Person # 4"), new Person("Person # 5"), new Person("Person # 6"), new Person("Person # 7") @};
a = temp; @emph{// Array "a" now holds Person # 4,Person # 5,Person # 6,Person # 7}
@end example

Later you will learn why this design pattern is useful for
re-initializing multi-dimensional arrays.

@strong{Question 4.10.2:} Write a @strong{@code{function}} in the @strong{@code{class}} PersonTest called
@code{print} that takes a Person array argument and prints out the
array. You will need to use the length property of the array parameter
so your @strong{@code{function}} works with arbitrary sized arrays. Change the @strong{@code{main}}
@strong{@code{function}} to what follows so that it contains a call to the @code{print}x
@strong{@code{function}}.

@example
@strong{@code{var}} Person[] a = @{ new Person("Person # 1"), new Person("Person # 2"), new Person("Person # 3")@};
print(a);
@end example

@strong{Question 4.10.3:} Write your own class called Mine similar to the Person
class with a one int parameter constructor, a private int property p
and a toString method that converts p to a string. Then write a
@strong{@code{function}} in the PersonTest class with same name as the previous print
@strong{@code{function}}, except that this one takes a Mine[], also known as a Mine
array. You might recall from Tutorial 7 that this practice of having
two functions with the same name is called @strong{@code{function}} name
overloading. Change the @strong{@code{main}} @strong{@code{function}} to what follows so that it
initializes an array of Mine point variables and then calls the second
print @strong{@code{function}}.

@example
@strong{@code{var}} Mine[] b = @{ new Mine(1), new Mine(2), new Mine(3) @};
print(b);
@end example

@cindex Arrays of @code{Object} type, second initialization syntax
@cindex Second initialization syntax for arrays of @code{Object}s

Here is an example of a second initialisation syntax. For this
particular example it is better to use the simpler, earlier
initialisation syntax, but when the size of the array to be created is
to be determined at run-time, then the second syntax should used. The
next question will show you an example of this.

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{var}} Person[] a = new Person[3];
@tie{}@tie{}@tie{} @emph{// at this point the array is all nulls}
@tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i=0 @strong{@code{to}} a.length-1)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a[i] = new Person("Person # " + (i+1));
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} print(a);
@strong{@code{endMain}}
@end example

@strong{Question 4.10.4:} Write a @strong{@code{function}} create takes one @code{int} argument, the
size of the array to create and returns a Person array of that
size. Make it so the ith element of the array is initialised to
"Person # " + i. Call this @strong{@code{function}} from the @strong{@code{main}} @strong{@code{function}} like so:

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{var}} Person[] a = create(3);
@tie{}@tie{}@tie{} print(a);
@strong{@code{endMain}}
@end example

@strong{Question 4.10.5:} Write a @strong{@code{function}} create2 takes one int argument, the
size of the array to create and returns a Mine array of that
size. Make it so the ith element of the array's toString method prints
out "Mine # " + i. Why is it not possible to overload that create
@strong{@code{function}}? Try it and see what the compiler says. Call create2 from the
@strong{@code{main}} @strong{@code{function}} like so:

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{var}} Mine[] a = create2(3);
@tie{}@tie{}@tie{} print(a);
@strong{@code{endMain}}
@end example

@strong{Question 4.10.6:} Write a @strong{@code{function}} doubler that takes a Person array x
and returns a new Person array called result twice as big as x. Copy x
into the result before you return it. The extra elements in result
should all be @strong{@code{null}}.

@strong{Question 4.10.7:} Change the doubler @strong{@code{function}} so that every @strong{@code{null}} in the
array result is set to a @code{@strong{new}} @code{Person} make it so that every new Person
@code{Object} has a different name property.

@subsection Two-dimensional arrays of @code{Object}s

@cindex Two-dimensional arrays of @code{Object}s
@cindex Arrays of @code{Object} type, two-dimensional
@cindex @code{Object} arrays, two-dimensional

@strong{Question 4.10.8:} Here is an example of a convenient two dimensional
array initialization syntax. Study, compile and run the following
code. The code Person[][] should be read out loud as person array
array indicating the variable @code{a} is a @emph{person array array}, also
known as a @emph{two-dimensional array of persons}.

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{var}} Person[][] a = @{ @{ new Person("Person # 1"), new Person("Person # 2"), new Person("Person # 3") @},
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @{ new Person("Person # 4"), new Person("Person # 5") @},
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @{ new Person("Person # 6") @} @};

@tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int y=0 @strong{@code{to}} a.length-1)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int x=0; @strong{@code{to}} a[y].length-1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.print(" " + a[y][x]);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{endMain}}
@end example

@strong{Question 4.10.9:} By copying the pattern of the code above, do some more
overloading of the print @strong{@code{function}} by writing two new print functions,
one taking a two dimensional array of Person, the other taken a two
dimensional array of Mine. The call both of these functions from the
@strong{@code{main}} @strong{@code{function}}.

Since a[0] is a Person array,you would naively expect it to be able to
be re-initialised like so:

@example
a[0] = @{ new Person("Person # 4"),
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} new Person("Person # 5"),
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} new Person("Person # 6") @};
@end example

so that after this code a0 holds the four element long array @code{Person
#4},@code{Person #5} and @code{Person #6}, but it does't work owing to a
design oversight by the creators of Java. Luckily as mentioned above
there is a way around this oversight and that is to use a temporary
variable like so:

@example
@strong{@code{var}} Person[] temp = @{ new Person("Person # 4"),
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} new Person("Person # 5"),
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} new Person("Person # 6") @};
a[0] = temp; @emph{// Array "a[0]" now holds Person # 4,Person # 5,Person # 6}
@end example

Like with one-dimensional arrays, there is a second initialization
syntax for two-dimensional arrays and here it is. Unlike the above
code the sub-arrays @code{a[0]},@code{a[1]} and @code{a[2]} are all of equal
size, namely three.

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{var}} Person[][] a = new Person[3][3];
@tie{}@tie{}@tie{} a[0][0] = new Person("Person # 1");
@tie{}@tie{}@tie{} a[0][1] = new Person("Person # 2");
@tie{}@tie{}@tie{} a[0][2] = new Person("Person # 3");
@tie{}@tie{}@tie{} a[1][0] = new Person("Person # 4");
@tie{}@tie{}@tie{} a[1][1] = new Person("Person # 5");
@tie{}@tie{}@tie{} a[1][2] = new Person("Person # 6");
@tie{}@tie{}@tie{} a[2][0] = new Person("Person # 7");
@tie{}@tie{}@tie{} a[2][1] = new Person("Person # 8");
@tie{}@tie{}@tie{} a[2][2] = new Person("Person # 9");
@strong{@code{endMain}}
@end example

@strong{Question 4.10.10:} Write a @strong{@code{function}} create3 and create4
that takes an @code{int} argument size and returns a two-dimensional array of
@code{Person} or @code{Mine}, respectively. Make is so that each @code{Person} or
@code{Mine} @code{Object} has its own number, using a separate counter
variable @code{@strong{@code{var}} @code{int} count}.

@subsection Three-dimensional arrays of @code{Object}s

@cindex Three-dimensional arrays of @code{Object}s
@cindex Arrays of @code{Object} type, three-dimensional

@strong{Question 4.10.11:} Using the knowledge you have gained so far about
arrays, create, initialize and print a three-dimensional array of
@code{Person}s. Make it so that each @code{Person} @code{Object} is given its
own number using a separate counter variable @code{@strong{@code{var}} @code{int} count}.




@node    Tutorial 11 References to another class
@section Tutorial 11 References to another class


The following code presents example involving three classes @code{Flea}, @code{Dog}
and @code{DogOwner} to represent the idea that a dog has a flea and a
dog-owner has a dog. The @strong{@code{class}} @code{DogTest} is the driver @strong{@code{class}}. The key
concept of this tutorial is that classes can have references of
objects of another class in order to set up a relationship between the
two classes.

@cindex Setting up relationships between different classes.
@cindex Relationships between different classes.

@strong{Question 4.11.1:} Study the following code and find the two bugs in
it. Fix the bugs and then compile and run it to verify that it prints
out "p=I am a flea called Pop".

@example
@strong{@code{class}} Flea
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{property}} String name;

@tie{}@tie{}@tie{} @strong{@code{constructor}} Flea(String aName)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} aName = name;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} String toString()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} return "I am a flea called " + name;
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} Dog
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{property}} String name;
@tie{}@tie{}@tie{} @strong{@code{property}} int age; @emph{// Age in years}
@tie{}@tie{}@tie{} @strong{@code{property}} Flea dogsFlea;

@tie{}@tie{}@tie{} @strong{@code{constructor}} Turtle(String aName, int anAge, Flea aFlea)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} name     = aName;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} age      = anAge;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} dogsFlea = aFlea;
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} DogTest
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} Flea p = new Flea("Pop");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} Flea s = new Flea("Squeak");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} Flea z = new Flea("Zip");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("p=" + p);
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.11.2:} In the @strong{@code{main}} @strong{@code{function}} of the DogTest class, write code
to call the @code{toString} @strong{@code{method}} for the fleas referenced by s and z.

@strong{Question 4.11.3:} In the @strong{@code{main}} @strong{@code{function}} of the DogTest class, write code
to construct three dogs called "Fido", "Jimbo" and "Rex". For the
purposes of the rest of these questions, let the name of the
references for Fido, Jimbo and Rex be @code{f}, @code{j} and @code{r}. Note
that the third parameter to the Dog class is of type Flea. Therefore
you will need to supply a Flea reference for each dog. Make it so that
Fido has a flea called Pop, Jimbo has a flea called Squeak, and Rex
has a flea called Zip.

@strong{HINT:} If the flea called Pop is referenced by the variable name
@code{p}, then this reference should appear as the third argument in one
of the calls to the Dog constructor.

@strong{Question 4.11.4:} Write a @code{toString} method in the @code{Dog} @strong{@code{class}} that
works like the @code{toString} method in the @code{Flea} @strong{@code{class}}. Then call
this @strong{@code{method}} from the @strong{@code{main}} @strong{@code{function}} to print out the full statistics of
the three dogs that you have just created in Question 11.3.

@strong{Question 4.11.5:} By copying the pattern of the @code{Flea} and @code{Dog}
classes, write a class @code{DogOwner} that has three non-private
properties: name, salary and ownersDog. Also write a three-parameter
constructor for the @code{DogOwner} @strong{@code{class}} that sets these properties.

@strong{Question 4.11.6:} Add some code into the @strong{@code{main}} @strong{@code{function}} to construct three
dog owners called Angus, Brian and Charles. Make it so that Angus has
a dog called Rex, Brian has a dog called Jimbo, and Charles has a dog
called Fido. For the purposes of the rest of these questions, let the
name of the references for Angus, Brian and Charles be (respectively)
@code{a}, @code{b} and @code{c}. Use the @code{Dog} references that you created in
Question 11.3 to achieve this. Make it so that Angus, Brian and
Charles have initial salaries of 10,000, 20,000 and 30,000.

@strong{Question 4.11.7:} Without changing the call to the @code{DogOwner}
constructor, change the value of the salary property of object
referenced by @code{a} to 1,000,000. Note that since the salary property
of the @code{DogOwner} class is non-private you should be able to set the
value of the salary property from the @strong{@code{main}} @strong{@code{function}} of DogTest.

@strong{Question 4.11.8:} Write a @code{toString} @strong{@code{method}} for the @strong{@code{class}}
@code{DogOwner} and add some code to the @strong{@code{main}} @strong{@code{function}} to call it for
Angus, Brian and Charles.

@strong{Question 4.11.9:} What is the value of:
@code{a.ownersDog.dogsFlea.toString()}?  Add some code to the @strong{@code{main}}
@strong{@code{function}} to find out if it does what you think it should do.


@node    Tutorial 12 Overloading methods
@section Tutorial 12 Overloading methods


@strong{Question 4.12.1:} Write constructors for the classes SportsShoe and
Runner below, by looking at the @strong{@code{main}} @strong{@code{function}} to see how many
arguments each constructor has.

@example
@strong{@code{class}} SportsShoe
@strong{@code{begin}}

@tie{}@tie{}@tie{} @strong{@code{property}} String model;      @emph{// what kind of shoe it is}
@tie{}@tie{}@tie{} @strong{@code{property}} double speedBoost; @emph{// the boosting factor of the shoe}

@tie{}@tie{}@tie{} @emph{// constructor goes here:}

@tie{}@tie{}@tie{} @emph{// Useful method for debugging}
@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} String toString()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} return "I am a shoe called " + model + " and my boosting factor is " + speedBoost;
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} Runner
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{property}} String     name;  @emph{// Runner's name.}
@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{property}} int        speed; @emph{// speed of runner in km/hr.}
@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{property}} SportsShoe shoes; @emph{// which shoe they are wearing.}

@tie{}@tie{}@tie{} @emph{// constructor goes here:}

@tie{}@tie{}@tie{} @emph{// Useful method for debugging}
@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} String toString()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{return}} "I am a runner and my name is " + name + " and my shoes are " + shoes;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @emph{/**}
@tie{}@tie{}@tie{} @emph{*** This private method computeSpeed works out the runners speed,}
@tie{}@tie{}@tie{} @emph{*** based on their basic speed and the speed boost due to the}
@tie{}@tie{}@tie{} @emph{*** SportsShoe that they are currently wearing.}
@tie{}@tie{}@tie{} @emph{*/}

@tie{}@tie{}@tie{} @emph{// method goes here:}


@tie{}@tie{}@tie{} @emph{/**}
@tie{}@tie{}@tie{} @emph{** Prints the result of racing two runners against each other.}
@tie{}@tie{}@tie{} @emph{*/}
@tie{}@tie{}@tie{} @strong{@code{function}} void race(Runner r1, Runner r2)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{if}} (r1.computeSpeed()>r2.computeSpeed())
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{then}} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Runner " + r1.name + " beats " + r2.name);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{else}} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Runner " + r2.name + " beats " + r1.name);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @emph{/**}
@tie{}@tie{}@tie{} @emph{** Swaps the shoes of two runners.}
@tie{}@tie{}@tie{} @emph{*/}
@tie{}@tie{}@tie{} @strong{@code{function}} void swapShoes(Runner r1, Runner r2)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} SportsShoe tempShoe = r1.shoes;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} r1.shoes = r2.shoes;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} r2.shoes = tempShoe;
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} RunnerTest
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} SportsShoe nike    = new SportsShoe("Nike NX-71", 2.0);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} SportsShoe reebock = new SportsShoe("Reebock R20", 2.3);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} SportsShoe puma    = new SportsShoe("Puma P200-MMX",4.8);

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Runner sg = new Runner("Speedy Gonzalez", 55, nike);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Runner sw = new Runner("Slick Willy", 49, reebock);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Runner fa = new Runner("Fat Albert", 15, puma);

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} Runner.race(sg,sw);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{// Runner.race(sg,sw,fa);}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{// sg.raceAgainst(sw);}
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.12.2:} In the Runner class, write the @strong{@code{private}} @strong{@code{method}}
@code{computeSpeed} that has no arguments and returns a double-precision
floating point value that equals the runner's running speed. Note that
the speed of a runner is determined by multiplying their speed
property with the @code{speedBoost} property of the shoes that they are
wearing. For example, Speedy Gonzalez's running speed = 55 * 2.0 =
110.0.

@strong{Question 4.12.3:} Fix the @code{race} @strong{@code{method}} so that it checks for a draw.

@strong{Question 4.12.4:} By copying the @code{race} method, write a three-parameter
race method for racing three runners against each other. Two methods
in the same class with the same name is called overloading in
J.T.W. and Java. Add a call to this method from the @strong{@code{main}} @strong{@code{function}}.

@cindex Overloading methods
@cindex Methods, overloading

@strong{Question 4.12.5:} What is the difference between a @strong{@code{method}} and a
@strong{@code{function}}?  Write a one parameter method raceAgainst that behaves
exactly like two-parameter @strong{@code{function}} race. There are two ways of doing
this, one is to optionally use the this keyword rather than one of the
parameters r1 or r2. The second way is for race to simply call race
using @strong{@code{this}} as one of the arguments to the @strong{@code{function}}.

@cindex Converting from functions to methods and vice-versa
@cindex Functions to methods and vice-versa
@cindex Methods to functions and vice-versa

@strong{Question 4.12.6:} Is it true that any @strong{@code{method}} can be re-worked into a
@strong{@code{function}} and vice versa?

@cindex Swapping the properties of two objects
@cindex Property swapping

@strong{Question 4.12.7:} The swapShoes method in the @code{Runner} @strong{@code{class}} swaps the
shoes of two runners. Add some code to the @strong{@code{main}} @strong{@code{function}} to swap the
shoes of two runners and verify that the shoes do indeed get swapped.

@strong{Question 4.12.8:} Write a method called @code{swapNames} that swaps the
names of two runners. You can put this @strong{@code{function}} into any @strong{@code{class}} but it
makes the most sense to put it into the @code{Runner} @strong{@code{class}} since it has
two Runner parameters.

@strong{Question 4.12.9:} Write a method @code{swapSpeeds} that swaps the speed
properties of two runners.


@node    Tutorial 13 More about references
@section Tutorial 13 More about references

@strong{Question 4.13.1:} Study, compile and run the following code:

@example
@strong{@code{class}} Car
@strong{@code{begin}}
@tie{}@tie{}@tie{} @emph{/**}
@tie{}@tie{}@tie{} @emph{* Car's model name}
@tie{}@tie{}@tie{} @emph{*/}
@tie{}@tie{}@tie{} @strong{@code{property}} String model;

@tie{}@tie{}@tie{} @emph{/**}
@tie{}@tie{}@tie{} @emph{* Car's value in dollars}
@tie{}@tie{}@tie{} @emph{*/}
@tie{}@tie{}@tie{} @strong{@code{property}} int value;

@tie{}@tie{}@tie{} @emph{/**}
@tie{}@tie{}@tie{} @emph{* Car's serial number}
@tie{}@tie{}@tie{} @emph{*/}
@tie{}@tie{}@tie{} @strong{@code{property}} int serialNumber;

@tie{}@tie{}@tie{} @emph{/**}
@tie{}@tie{}@tie{} @emph{*   Global serial number counter}
@tie{}@tie{}@tie{} @emph{*/}
@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{classVar}} int serialCounter = 1000;

@tie{}@tie{}@tie{} @strong{@code{constructor}} Car(String aModel, int aValue)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} model = aModel;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} value = aValue;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} serialNumber = serialCounter;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} serialCounter = serialCounter + 1;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} String toString()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} return "I am a car, model=" + model + ", value=" + value +
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{}  ", serial number=" + serialNumber;
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} Owner
@strong{@code{begin}}

@tie{}@tie{}@tie{} @emph{/**}
@tie{}@tie{}@tie{} @emph{* Owner's full name}
@tie{}@tie{}@tie{} @emph{*/}
@tie{}@tie{}@tie{} @strong{@code{property}} String name;

@tie{}@tie{}@tie{} @emph{/**}
@tie{}@tie{}@tie{} @emph{* Owner's money in dollars}
@tie{}@tie{}@tie{} @emph{*/}
@tie{}@tie{}@tie{} @strong{@code{property}} int money;

@tie{}@tie{}@tie{} @emph{/**}
@tie{}@tie{}@tie{} @emph{* Owner's car}
@tie{}@tie{}@tie{} @emph{*/}
@tie{}@tie{}@tie{} @strong{@code{property}} Car ownersCar;

@tie{}@tie{}@tie{} @strong{@code{constructor}} Owner(String aName, int aMoney, Car aCar)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} name = aName;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} money = aMoney;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} ownersCar = aCar;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} String toString()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} return "I am a car owner, name=" + name + ", money=" + money +
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{}  ", car=" + ownersCar;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} void describe()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println(toString());
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} CarTest
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Car   ford = new Car("Ford Escort",1000);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Car   nissan = new Car("Nissan Nivara",2000);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Owner joe = new Owner("Joe Bloggs",500,ford);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{}) @emph{// Mary has no car to start with.}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Owner mary = new Owner("Mary Smith",600,null);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} joe.describe();
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.13.2:} What is the purpose of the @strong{@code{class}} variable serialCounter?

@strong{Question 4.13.3:} Write a @strong{@code{method}} @code{sellCar} that increases the owner's
money by half the value of their car and the owner's car reference
gets set to @strong{@code{null}}, for no car.  If the owner owns no car (@strong{@code{null}}) simply
do nothing.

@strong{Question 4.13.4:} Write a @strong{@code{method}} in the Owner @strong{@code{class}} called purchase so that:

@example
Car newCar = new Car("Mini Cooper",1000);
joe.purchase(newCar);
@end example

results in Joe's money going down by $1000 and Joe's car being set to
newCar.  Before Joe purchases their new car, call the @code{sellCar}
method so that Joe sells his current car before

@strong{Question 4.13.5:}  Write a @strong{@code{function}}  in the Owner  class called
@code{netWorth} so that:

@example
System.out.println("Joe's net worth = " + joe.netWorth());
@end example

prints out Joes' money plus the value of his car, if he has a car.

@strong{Question 4.13.6:} Write a method in the Owner @strong{@code{class}} called @code{smashCar}
so that:

@example
mary.smashCar();
@end example

@noindent halves the value of Mary's car.

@strong{Question 4.13.7:} Write a method in the Owner class called stealCarFrom so that:

@example
mary.stealCarFrom(joe);
@end example

results in Mary selling his current car (if he has one) for its market
value and Mary acquiring ownership of Joe's car. Also call Mary's
@code{sellCar} @strong{@code{method}} so that Mary sells her current car before stealing
Joe's car.

@strong{Question 4.13.8:} Write a @strong{@code{function}} in the @code{Owner} @strong{@code{class}} called
@code{swapMoney} so that:

@example
Owner.swapMoney(joe,mary);
@end example

@noindent swaps the money of Joe and Mary.

@strong{Question 4.13.9:} Write a @strong{@code{function}} in the Owner class called swapCars so that:

@example
Owner.swapCars(joe,mary);
@end example

@noindent swaps the cars of Joe and Mary.

@strong{Question 4.13.10:} Write a @strong{@code{function}} in the Car class called
swapSerialNumbers so that:

@example
Car.swapSerialNumbers(ford,nissan);
@end example

@noindent swaps the serial numbers of ford and nissan.

@strong{Question 4.13.11:} Write a @strong{@code{function}} in the Owner class called
@code{sellCarTo} so that

@example
joe.sellCarTo(mary);
@end example

@noindent results in Joe's money going up by the value of his car and Mary's
money going down by the value of his car, and the ownership of Mary's
car gets transferred to Joe.


@node    Tutorial 14 Linked lists
@section Tutorial 14 Linked lists

@cindex Yertle the Turtle
@cindex Linked lists

Dr Seuss' story @url{https://en.wikipedia.org/wiki/Yertle_the_Turtle,
@emph{``Yertle the Turtle''}} describes how a turtle called Yertle sits
at the top of a pile of other turtles. In this example, the pile of
turtles is represented by a linked list of Turtle objects, with the
@code{down} @strong{@code{property}} serving to connect one Turtle object to another. If
a Turtle object has a non-null @code{down} @strong{@code{property}}, then this represents
the fact that it is sitting on top of another turtle. The last turtle
in the linked list is the turtle that is at the bottom of the pile,
which has a @strong{@code{null}} value for its down @strong{@code{property}}.  Note that you cannot
use the @strong{@code{superfor}} construct for iterating through a linked list.  In
this case the @strong{@code{for}} construct is the most sensible.

@strong{Question 4.14.1:} Study, compile and run the following code:

@example
@strong{@code{class}} Turtle
@strong{@code{begin}}

@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{property}} String     name;   @emph{// Turtle's name}
@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{property}} int        age;    @emph{// Turtle's age in years}
@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{property}} double     weight; @emph{// Turtle's weight in kg}

@tie{}@tie{}@tie{} @emph{// NOTE: this property allows for linked lists}
@tie{}@tie{}@tie{} @strong{@code{property}} Turtle down;

@tie{}@tie{}@tie{} @strong{@code{constructor}} Turtle(String aName, int anAge, double aWeight)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} name   = aName;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} age    = anAge;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} weight = aWeight;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @emph{/** Getter method for name property */}
@tie{}@tie{}@tie{} @strong{@code{method}} String getName()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{return}} name;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @emph{/** Useful method for debugging */}
@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} String toString()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} return name;
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} TurtleTest
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Turtle yertle = new Turtle("Yertle", 103, 20);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Turtle zippy  = new Turtle("Zippy",  102, 30);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Turtle bungle = new Turtle("Bungle", 101, 40);

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{// *** see later}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} yertle.down = zippy;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} zippy.down = bungle;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} bungle.down  = @strong{@code{null}}; @emph{// NOTE: not needed as bungle.down is @strong{@code{null}} by default}

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} int totalWeight = 0;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{// NOTE: demonstrates how to iterate through a linked list:}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{for}} (@strong{@code{var}} Turtle current = yertle; current != null; current=current.down)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} totalWeight = totalWeight + current.getWeight();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("The total weight is " + totalWeight);
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

The code in the @strong{@code{main}} @strong{@code{function}} after the @code{***} sets down the
following relationships between the three Turtle objects (Yertle,
Bungle and Zippy). The following diagram shows the relationship
between the different turtles. When you traverse the list of turtles
you must always start at the top turtle (known as the head of the
linked list). If you give a different value for the @code{top} turtle,
your code will think that the given turtle is the one at the top of
the pile and you will get the wrong result.

@verbatiminclude Turtles.txt

Question 4.14.2: Move the code for calculating the total weight of the
turtles from the @strong{@code{main}} @strong{@code{function}} to a @strong{@code{function}} called @code{@strong{@code{function}} void
printTotalWeight(Turtle bottom)} in the Turtle class that prints out
the total weight of the turtles. Then call that @strong{@code{function}} from the @strong{@code{main}}
@strong{@code{function}} to get the same result as before. Note that that if
@code{printTotalWeight} was a method then calling that method using @strong{@code{null}}
(representing an empty list) like so: @code{null.printTotalWeight()}
would be an error, whereas @code{Turtle.printTotalWeight(null)} wouldn't
be and therefore is better. This is one example of how methods and
functions differ.

@strong{Question 4.14.3:} Revision question for getters. By copying the pattern
established by the getName method, add two getter methods to the
Turtle @strong{@code{class}}: @code{getAge} which returns the current turtle's age and
@code{getWeight} which returns the current turtle's weight. Then call
these methods on the Yertle object in the @strong{@code{main}} @strong{@code{function}}. Note that the
@code{toString} method would be more appropriate as it handles nulls
better but you know that the yertle reference is not null so you know
it is safe to call the @code{getAge} and @code{getWeight} methods on the
yertle reference.

@strong{Question 4.14.4:} Write a @strong{@code{function}} @code{Turtle findBottomTurtle(Turtle top)} that
returns the Turtle object that is at the top of the pile, and returns
null if there isn't one.

@strong{Question 4.14.5:} Then call this @strong{@code{function}} from the @strong{@code{main}} @strong{@code{function}} using
@code{System.out.println()} and the top turtle Yertle.

@strong{Question 4.14.6:} Write a @strong{@code{function}} @code{Turtle findOldestTurtle(Turtle top)}
that returns the oldest turtle or null if there isn't one.

@strong{Question 4.14.7:}Then call this @strong{@code{function}} from the @strong{@code{main}} @strong{@code{function}} using
@code{System.out.println()} and the top turtle Yertle.

@strong{Question 4.14.8:} Write a @strong{@code{function}} @code{Turtle
findHeaviestTurtle(Turtle top)} returns the heaviest turtle, or @strong{@code{null}}
if there isn't one.

@strong{Question 4.14.9:} Then call this @strong{@code{function}} from the @strong{@code{main}}
@strong{@code{function}} using @code{System.out.println()} and the top turtle Yertle.

@strong{Question 4.14.10:} Write a @strong{@code{function}} @code{sayPile(Turtle top)} that prints
the names of the turtles in the pile starting from the top turtle and
finishing at the bottom turtle. Then call this @strong{@code{function}} from the @strong{@code{main}}
@strong{@code{function}}.

@strong{Question 4.14.11:} Under what circumstances would it be okay to change
the visibility of the @code{down} @strong{@code{property}} to private, like the name, age
and weight properties?

@strong{Question 4.14.12:} Add an extra parameter to the @strong{@code{constructor}} which is a
reference the to the turtle on below the current one. Then remove all
occurrences of the @code{down} @strong{@code{property}} from the @strong{@code{main}} @strong{@code{function}}.  Note that
you will need to reverse the order that the turtles are created so the
bottom turtle is constructed first and so on.  The advantage of this
is that it enables you to change the visibility of the @code{down}
@strong{@code{property}} to @strong{@code{private}}.



@node    Tutorial 15 Introducing inheritance
@section Tutorial 15 Introducing inheritance

@subsection Basic Inheritance

@cindex Inheritance

When you see the following code: @strong{@code{class}} @code{X} extends @code{Y}, it means
that @strong{@code{class}} @code{X} inherits from the @strong{@code{class}} @code{Y}. Class @code{X} is called
the subclass and the @strong{@code{class}} @code{Y} is called the super-class or sometimes the
parent @strong{@code{class}}. When the class @code{X} extends from @code{Y}, it pulls in all of the
non-private methods and properties from the super-class Y. Inherited
methods can override the behaviour of that same method in the
super-class to give behaviour that is specific to the subclass. The
concept of methods overriding other methods is called dynamic method
binding or more commonly the more impressive-sounding name:
polymorphism. The main thing that this tutorial shows is the idea that
inheritance is a non-symmetrical relationship. For example: in the
code that follows, the Bird class inherits from the Animal class,
which corresponds to the idea that every bird is an animal. The
reverse, every animal is a bird is plainly not true! Inheritance
forces you to recognize this.

@strong{Question 4.15.1:} Study, compile and run the following code. The
following code shows how inheritance works. In the following code, the
@code{Bird} @strong{@code{class}} inherits from the @code{Animal} @strong{@code{class}}. The @code{Bird} @strong{@code{class}} pulls in
the Animal class's @code{age} property and the @code{canFly} and @code{talk}
methods. Importantly the @code{canFly} property overrides the behaviour of
the canFly method of the parent Animal class, which reflects that fact
that generally speaking, birds can fly. In the code that follows, note
that int properties are initialized to zero by default and the super
method (also known as the constructor of the super-class) is called by
default if there is a zero parameter constructor in the super-class,
which there is by default, even if you don't write one!

@example
@strong{@code{class}} Animal
@strong{@code{begin}}

@tie{}@tie{}@tie{} @strong{@code{property}} int age;    @emph{// Animal's age in years}
@tie{}@tie{}@tie{} @strong{@code{property}} int health; @emph{// Animal's health in hit points}

@tie{}@tie{}@tie{} @strong{@code{constructor}} Animal()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} age    = 0; @emph{// NOTE: not needed as set by default}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} health = 100;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{method}} boolean canFly()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} return @strong{@code{false}};
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{method}} void talk()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Hello");
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} Bird extends Animal
@strong{@code{begin}}

@tie{}@tie{}@tie{} @strong{@code{property}} double flySpeed;) @emph{// Bird's speed in km/h}

@tie{}@tie{}@tie{} @strong{@code{constructor}} Bird()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} super();      @emph{// NOTE: not needed as called by default}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} flySpeed = 0; @emph{// NOTE: not needed as set by default}
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{method}} boolean canFly()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{return}} @strong{@code{true}};
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{method}} void peck()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("peck");
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} InheriTest
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Bird eagle = new Bird();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} eagle.talk();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} eagle.peck();
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.15.2:} Override the talk method of the Animal class in the
Bird class to print out ``Tweet Tweet!'' rather than ``hello'' to give
more accurate talking of bird objects.

@strong{Question 4.15.3:} By copying the pattern established in the Bird class,
change the eagle from an instance of the Bird class to its own class
in its own right and then create an instance of that class in the @strong{@code{main}}
@strong{@code{function}} of InheriTest. Your Eagle class should have one @strong{@code{property}}: @code{int
numberOfKills} and one @strong{@code{method}}: @code{void attack()} that internally increments
the value of @code{numberOfKills}. In the @strong{@code{main}} @strong{@code{function}} you should call every
method of the Eagle class and its super-classes.

@strong{Question 4.15.4:} What is the advantage of using a new separate class to
represent a new object rather than using an instance of an existing
class?

@cindex Writing your own classes

@strong{Question 4.15.5:} Create a new @strong{@code{class}} @code{Kiwi} that inherits from the
@code{Bird} @strong{@code{class}}. Your @code{Kiwi} @strong{@code{class}} should override the @code{canFly}
method to return @strong{@code{false}}, which reflects the fact that generally
speaking birds can fly, but the kiwi bird in particular does not
fly. Your @code{Kiwi} @strong{@code{class}} have a @strong{@code{property}} @code{numberOfWorms}. Once you
have written the @code{Kiwi} @strong{@code{class}} you should create an instance of the
@code{Kiwi} @strong{@code{class}} in the @strong{@code{main}} @strong{@code{function}}.

@strong{Question 4.15.6:} Why does the following line of code in the @strong{@code{main}}
@strong{@code{function}} print out 100 but there is no setting of that variable to
that value in the Kiwi class?

@example
System.out.println(k.health);
@end example

@strong{Question 4.15.7:} In the classes @code{Animal}, @code{Bird}, @code{Eagle} and
@code{Kiwi}, remove all of the @code{canFly} methods and replace it with a
single @code{canFly} property of the Animal class. In the constructors
you will need to set the value of the @code{canFly} @strong{@code{property}} to a value
that is appropriate for that class. For example in the @code{Bird}
class's constructor you should set the @code{canFly} @strong{@code{property}} to @strong{@code{true}},
while in the @code{Kiwi} @strong{@code{class}}'s constructor you should set the
@code{canFly} @strong{@code{property}} to @strong{@code{false}}.

@strong{Question 4.15.8:} What is the advantage of having a @code{canFly}
@strong{@code{property}} over a bunch of @code{canFly} methods?

There is an equally valid alternative to having a @strong{@code{public}} @strong{@code{property}} in
the @code{Animal} @strong{@code{class}} and that is to have in the @code{Animal} @strong{@code{class}} a
@strong{@code{private}} @strong{@code{property}} @code{canFly} and a pair of methods for getting and
setting the value of the @code{canFly} property like so. These methods in
J.T.W. and Java are called getter methods and setter methods since, as
their names suggest, getters are used for getting the value of
something and setters are used for setting the value of
something. Nore that the @code{canFly} @strong{@code{method}} of the code above
corresponds to @code{getCanFly} @strong{@code{method}} in the code below.

@example
@strong{@code{private}} @strong{@code{property}} boolean canFly;

@strong{@code{method}} boolean getCanFly()
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{return}} canFly;
@strong{@code{end}}

@strong{@code{method}} void setCanFly(boolean aCanFly)
@strong{@code{begin}}
@tie{}@tie{}@tie{} canFly = aCanFly;
@strong{@code{end}}
@end example

@cindex Getter and setter methods
@cindex Setter and getter methods

You might think that it is simpler to have one thing (a single
non-private property) rather than three things (a private property and
a non-private getter method and a non-private setter method) and you
would be right. However from the point of view of the client code that
uses the Animal @strong{@code{class}}, the two approaches are identical. Later on when
you learn more you will understand under what circumstances the second
getter and setter approach is better.

@strong{Question 4.15.9:} Change the @strong{@code{main}} @strong{@code{function}} to what follows:

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{var}} Bird b = new Bird(10);
@tie{}@tie{}@tie{} @strong{@code{var}} Animal a = b;
@tie{}@tie{}@tie{} a.talk();
@tie{}@tie{}@tie{} a.peck();
@strong{@code{endMain}}
@end example

When you compile this code it gives a compilation error. What line
gives the error and what is the reason for the error?

@strong{Question 4.15.10:} Change the @strong{@code{main}} @strong{@code{function}} to what follows:

@example
@strong{@code{beginMain}}
@tie{}@tie{}@tie{} @strong{@code{var}} Animal a = new Animal();
@tie{}@tie{}@tie{} @strong{@code{var}} Bird b = a;
@tie{}@tie{}@tie{} b.talk();
@tie{}@tie{}@tie{} b.peck();
@strong{@code{endMain}}
@end example

When you compile this code it gives a compilation error. What line
gives the error and what is the reason for the error?

@subsection Run-time type inquiry

In J.T.W. and Java there is a keyword called @strong{@code{instanceof}} that does
a run-time check on the type of an object. The following @strong{@code{function}}:

@example
@strong{@code{function}} void say(Animal a)
@strong{@code{begin}}
@tie{}@tie{}@tie{} System.out.println(a instanceof Bird);
@strong{@code{end}}
@end example

uses the @strong{@code{instanceof}} keyword to determine the run-time type of the
reference a and prints out whether or not the reference is referring
to a @code{Bird} object. Some examples should clarify the situation:

@cindex @strong{@code{instanceof}} keyword

@itemize @bullet
@item @code{say(new Bird())} prints @strong{@code{true}}, Since the parameter a is pointing to a bird object at run-time,
@item @code{say(new Animal())} prints @strong{@code{false}} since not every animal is a bird,
@item @code{say(new Eagle())} prints @strong{@code{true}}, since every eagle is a bird, and
@item @code{say(new Kiwi())} prints @strong{@code{true}}, since every kiwi is a bird.
@item @code{@strong{@code{var}} Animal a = new Animal(); say(a);} prints @strong{@code{false}} since at run-time a is not pointing to a bird object
@item @code{@strong{@code{var}} Animal a = new Bird(); say(a);} prints @strong{@code{true}} since at run-time a is pointing to a bird object.
@end itemize

In Tutorial 17 you will learn why in most cases it is better to use
polymorphism instead of the instanceof keyword for run-time type
enquiry.

@subsection The superclass of all objects
@cindex @code{Object} superclass of all objects

Every @strong{@code{class}} in Java inherits either directly or indirectly from a
@strong{@code{class}} called @code{Object}. That is to say if @code{x} is a reference
variable, then the run-time expression @code{x instanceof Object} is
always @strong{@code{true}} except for the pathological case where @code{x} is @strong{@code{null}}
(i.e. is currently pointing to no object). The @code{Object} @strong{@code{class}}
contains a method called @code{toString} that returns a string containing
the run-time @strong{@code{class}} name of the object concatenated with the hash code
of the memory address of the object in base 16 (also known as
hexadecimal) format. Since every @strong{@code{class}} inherits from Object, every
object can have @code{toString} invoked upon it. Even better, every @strong{@code{class}}
@code{X} can override @code{toString} to provide debugging information that
is tailored to @code{X}. Therefore the @code{toString} @strong{@code{method}} is convenient
for debugging. Since the @code{toString} @strong{@code{method}} is a @strong{@code{public}} @strong{@code{method}} of the
@code{Object} @strong{@code{class}} it must be overridden as a @strong{@code{public}} method, since your
overridden @strong{@code{function}} cannot have weaker access privileges.

@cindex The @code{toString} method and its usefulness in debugging.


@node    Tutorial 16 More inheritance
@section Tutorial 16 More inheritance


This tutorial shows you a practical example of inheritance. The file
@code{StarWars.jtw} is comprised of three classes: @code{XWing}, @code{TieFighter} and
@code{StarWars}. The first two represent spacecraft from the two sides of the
Star Wars films. The class @code{StarWars} is the driver class and contains
code for executing a battle between the X-Wings and the Tie Fighters.

@cindex Inheritance and removing duplication of code.

@strong{Question 4.16.1:} Study, compile and run the following code:

@example
@strong{@code{class}} XWing
@strong{@code{begin}}

@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{property}} int     shields;
@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{property}} int     weapon;
@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{property}} boolean dead;

@tie{}@tie{}@tie{} @strong{@code{constructor}} XWing()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} shields = 1000;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} weapon  = 10;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{method}} int getWeapon()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{return}} weapon;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{method}} boolean isDead()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{return}} dead;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{method}} void hit(int damage)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} shields = shields - damage;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} if (shields<0)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{then}} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("BOOM!!!");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} dead = @strong{@code{true}};
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} TieFighter
@strong{@code{begin}}

@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{property}} int     shields;
@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{property}} int     weapon;
@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{property}} boolean dead;

@tie{}@tie{}@tie{} @strong{@code{constructor}} TieFighter()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} shields = 500;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} weapon  = 20;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{method}} int getWeapon()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{return}} weapon;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{method}} boolean isDead()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{return}} dead;
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{method}} void hit(int damage)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} shields = shields - damage;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{if}} (shields<0)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{then}} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("BOOM!!!");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} dead = true;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} StarWars
@strong{@code{begin}}

@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{function}} void duel(XWing x, TieFighter t)
@tie{}@tie{}@tie{} @strong{@code{begin}}

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} for (;;)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} x.hit(t.getWeapon());
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{if}} (x.isDead())
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{then}} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("X-Wing is dead");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{break}};
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} t.hit(x.getWeapon());
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} if (t.isDead())
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{then}} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Tie Fighter is dead");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} break;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{function}} void battle(XWing good, TieFighter evil)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} int g          = 0;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} int e          = 0;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} int goodDeaths = 0;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} int evilDeaths = 0;

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{while}} (g<good.length and e<evil.length)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("battling X-Wing #" + g + " versus Tie Fighter #" + e);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} duel(goodg,evile);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{if}} (goodg.isDead())
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{then}} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} g = g + 1;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} goodDeaths = goodDeaths + 1;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{if}} (evile.isDead())
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{then}} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} e = e + 1;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} evilDeaths = evilDeaths + 1;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} int finalGood = good.length - goodDeaths;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} int finalEvil = evil.length - evilDeaths;

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Battle Report: @tie{}@tie{}@tie{} X-Wings @tie{}@tie{}@tie{} Tie Fighters");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("----------------------------------------------");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Initial ships:" + good.length + "  " + evil.length);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Killed ships:"  + goodDeaths  + "  " + evilDeaths);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Final ships:"@tie{}@tie{}@tie{} + finalGoodPD + "  " + finalEvil);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{if}} (finalGood>finalEvil)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{then}} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("The rebel alliance is victorious!");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{else}} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("The dark side has conquered!");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println();
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{// defines the goodies array}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} XWing goodies = new XWing3;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{// initialises the elements of the goodies array}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i=0 @strong{@code{to}} goodies.length-1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} goodiesi = new XWing();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{// defines the baddies array}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} TieFighter baddies = new TieFighter3;
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{// initialises the elements of the baddies array}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i=0 @strong{@code{to}} baddies.length-1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} baddiesi = new TieFighter();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} battle(goodies,baddies);

@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@strong{Question 4.16.2:} Compile and run this file to see the battle between the
X-Wings and the Tie Fighters unfold.

@strong{Question 4.16.3:} If you look at the Java code for the XWing and
TieFighter classes you will notice that they are almost identical:
They have the same methods and properties, the only difference is that
the @code{XWing} objects are initialized with a different value for their
@code{shields} and @code{weapon} properties to the @code{TieFighter} objects.

The next few questions will guide you through the process of using
inheritance to eliminate this unnecessary duplication of code. A new
class called SpaceShip will be created and all of the code that is
common to XWing and TieFighter will be moved into this class. The
XWing and TieFighter classes will then be modified so that they both
inherit from SpaceShip.

@strong{Question 4.16.4:} The first step in this process is to create the outer
shell of the SpaceShip class, which you should now type in:

@example
@strong{@code{class}} SpaceShip
@strong{@code{begin}}
@strong{@code{end}}
@end example

@strong{Question 4.16.5:} Move the properties @code{shields}, @code{weapon} and
@code{dead} out of the @code{XWing} and @code{TieFighter} classes and into the
@code{SpaceShip} @strong{@code{class}}. You must change the privacy status of the
properties from @strong{@code{private}} to @strong{@code{protected}}. The protected modifier was
invented as an intermediate level of privacy between @strong{@code{public}} and
@strong{@code{private}}. Like @strong{@code{private}}, it allows visibility to the same class in which
the method or property was defined, but unlike @strong{@code{private}} it also allows
visibility to sub-classes of the class in which the @strong{@code{method}} or @strong{@code{property}}
was defined.

@strong{Question 4.16.6:} Move the three methods @code{getWeapon}, @code{isDead} and
@code{hit} out of the @code{XWing} and @code{TieFighter} classses and into the
@code{SpaceShip} @strong{@code{class}}. At this point, the @code{XWing} and @code{TieFighter}
classes should contain nothing but a constructor.

@strong{Question 4.16.7:} Finally, add the extends keyword to the first line of
the @code{XWing} and @code{TieFighter} classes:

@example
class XWing extends SpaceShip)
@end example

@noindent and

@example
class TieFighter extends SpaceShip)
@end example

@strong{Question 4.16.8:} Compile and run your program again, making sure that it
produces the same results now that it is using inheritance.

@strong{Question 4.16.9:} The SpaceShip class is a super-class of both XWing and
TieFighter containing everything that X-Wings and Tie Fighters contain
in common. Because the role of the SpaceShip class is simply to hold
these commonalities, we might choose to label the class with the
abstract keyword:

@example
abstract class SpaceShip)
@end example

This prevents us from creating instances of the SpaceShip
class. Without the abstract modifier, we could happily create a new
SpaceShip(), which would be an object that is not an X-Wing, nor a Tie
Fighter, but just a vague "space ship". If we consider this to be a
logical mistake then we can use @strong{@code{abstract}} to prevent such calls to the
SpaceShip constructor. Change the class SpaceShip to be @strong{@code{abstract}} and
observe how the compiler will not accept any lines of the form:

@example
@strong{@code{var}} SpaceShip s = new SpaceShip();) @emph{// compiler error}
@end example

@noindent Remove the @strong{@code{abstract}} keyword and notice how the compiler will then
allow this line to compile.


@node    Tutorial 17 Arrays inheritance and polymorphism
@section Tutorial 17 Arrays inheritance and polymorphism




@strong{Question 4.17.1:} Study, compile and run the following code:

@example
@strong{@code{class}} AnimalTest
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{private}} @strong{@code{function}} void chatter(Animal[] a)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i=0 @strong{@code{to}} a.length-1)
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a[i].talk();
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Animal[] farm = @{ new Dog(), new Cow(), new Fish() @};
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Animal[] ark  = @{ new Dog(), new Dog(), new Cow(), new Cow(), new Fish(), new Fish() @};
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} Cow[]    herd = @{ new Cow(), new Cow(), new Cow() @};
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} chatter(farm);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} chatter(ark);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} chatter(herd);
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}

@strong{@code{class}} Animal
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{method}} boolean breathesUnderwater()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{return}} @strong{@code{false}};
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{method}} boolean isPredator()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{return}} @strong{@code{false}};
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{method}} void talk()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}

@strong{@code{class}} Dog @strong{@code{extends}} Animal
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{method}} boolean isPredator()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{return}} @strong{@code{true}};
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{method}} void talk()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Woof woof!");
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}
@end example

@strong{Question 4.17.2:} Write the following classes that subclass the Animal
class above: @code{Cow}, @code{Cat}, @code{Fish}, and @code{Whale}.

@cindex Writing your own classes

@strong{Question 4.17.3:} Write the @code{Shark} @strong{@code{class}} which extends @code{Fish}
@strong{@code{class}}. Override all necessary methods. For the sake of this example
and the code that follows, suppose that shark's @code{talk} @strong{@code{method}} prints out
"Chomp Chomp!".

@cindex Polymorphism

@strong{Question 4.17.4:} Run the @code{AnimalTest} class to make sure that all the
methods work correctly.

@strong{Question 4.17.5:} Rewrite the chatter method so that it never calls the
talk methods and instead uses a series of @strong{@code{if}} (...) @strong{@code{then}} ...
statements and the @strong{@code{instanceof}} operator to test the run-time type of
each object in the a array. Here is some code to get you started:

@cindex Arrays
@cindex Arrays of @code{Object} type

@example
@strong{@code{private}} @strong{@code{function}} void chatter(Animal[] a)
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{superfor}} (@strong{@code{var}} int i=0 @strong{@code{to}} a.length-1)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{if}} (a[i] instanceof Cow) @strong{@code{then}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Moo!");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{elseif}} (a[i] instanceof Cat) @strong{@code{then}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Meow!");
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{end}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @emph{/* other code goes here */}
@tie{}@tie{}@tie{} @strong{@code{end}}
@strong{@code{end}}
@end example

@noindent Note that the sub-classes must appear before super-classes in the above
code, otherwise the wrong message will be printed out for sub-classes.

@strong{Question 4.17.6:} Why is the code from the last question not as
good as calling each animal's talk method?  In general polymorphism is
preferable to run-time type inquiry.

@cindex Polymorphism versus run-time type inquiry
@cindex Run-time type inquiry versus Polymorphism
@cindex Why it is better to use polymorphism rather than run-time type inquiry




@node    Tutorial 18 Advanced J.T.W.
@section Tutorial 18 Advanced J.T.W.

@menu
* Mapping J.T.W. to Java::
* Piping the output of javac and java::
* Makefile for building *.jtw into *.java and running *.class files::
@end menu

See @ref{How to build a collection of class files or an entire package}
for more information about compiling an entire package worth of
classes.


@node Mapping J.T.W. to Java
@subsection Mapping J.T.W. to Java

@cindex Mapping from @code{*.jtw} -> @code{*.java}
@cindex J.T.W. internal details
@cindex Internal details of the J.T.W. system

Here is how to map from J.T.W. to Java:



@multitable @columnfractions .1 .7
@item @strong{@code{function}}
@tab -> @strong{@code{static}}
@item @strong{@code{var}}
@tab -> @emph{nothing}
@item @strong{@code{classVar}}
@tab -> @strong{@code{static}}
@item @strong{@code{property}}
@tab -> @emph{nothing}
@item @strong{@code{method}}
@tab -> @emph{nothing}
@item @strong{@code{constructor}}
@tab -> @emph{nothing}
@item @strong{@code{begin}}
@tab -> @{
@item @strong{@code{end}}
@tab -> @}
@item @strong{@code{beginMain}}
@tab -> @code{@strong{@code{public}} @strong{@code{static}} void @strong{@code{main}}(String[] args) @{}
@item @strong{@code{endMain}}
@tab -> @}
@item @strong{@code{and}}
@tab -> @code{@strong{&&}}
@item @strong{@code{or}}
@tab -> @code{@strong{||}}
@item @strong{@code{then}}
@tab -> @emph{nothing}
@item @strong{@code{elseif}}
@tab -> @strong{@code{else}} @strong{@code{if}}
@end multitable

Here is an J.T.W. program:

@example
@strong{@code{class}} HelloWorld
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Hello, World!")
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

Here is the same J.T.W. program, after conversion to the Java language:

@example
@strong{@code{class}} HelloWorld
@{
@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{static}} void @strong{@code{main}}(String[] args)
@tie{}@tie{}@tie{} @{
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("Hello, World!")
@tie{}@tie{}@tie{} @}
@}
@end example

Note that these J.T.W. keywords on the left hand side of the above
diagram should not map to their Java equivalents inside strings and
comments. The transformation was originally written to use the m4
language to map J.T.W. onto Java but this approach had the
disadvantage that keywords like begin and end inside strings were
mapped to their Java equivalents like so:


@multitable @columnfractions .1 .7
@item @code{System.out.println("function");}
@tab @code{-> System.out.println("static");}
@item @code{System.out.println("classVar");}
@tab @code{-> System.out.println("static");}
@item @code{System.out.println("property");}
@tab @code{-> System.out.println("");}
@item @code{System.out.println("method");}
@tab @code{-> System.out.println("");}
@item @code{System.out.println("constructor");}
@tab @code{-> System.out.println("");}
@item @code{System.out.println("begin");}
@tab @code{-> System.out.println("@{");}
@item @code{System.out.println("end");}
@tab @code{-> System.out.println("@}");}
@item @code{System.out.println("beginMain");}
@tab @code{-> System.out.println("public static void main(String[] args) @{");}
@item @code{System.out.println("endMain");}
@tab @code{-> System.out.println("@}");}
@item @code{System.out.println("and");}
@tab @code{-> System.out.println("&&");}
@item @code{System.out.println("or");}
@tab @code{-> System.out.println("||");}
@item @code{System.out.println("then");}
@tab @code{-> System.out.println("");}
@item @code{System.out.println("elseif");}
@tab @code{-> System.out.println("else if");}
@end multitable



@noindent which is of course the wrong behaviour. A hack to get around this
limitation is to break apart the J.T.W. keywords like so:

@example
System.out.println("be" + "gin");)
@end example

This problem can be fixed for good either by using Flex to compile
J.T.W. into Java or to use Emacs to do the same thing, only a little
slower than what Flex can do. In the end I chose GNU Emacs as the host
for the preprocessor language J.T.W. because it is free, libre and
open source software, is adequate for my programming needs and is more
powerful than Flex or m4. To remedy this deficiency Emacs' batch mode
is used to do the transformation from J.T.W. to Java. This implies
that GNU Emacs must be present on the client's system to do the
J.T.W. to Java mapping. Of course, there is no compulsion to use Emacs
as an editor, although there are a couple of advantages in doing
this. Number one is that J.T.W. keywords and comments have automatic
@code{@strong{syntax} @emph{highlighting}}. And number two is that Emacs can do
correct automatic indentation of J.T.W. code.

@node       Piping the output of javac and java
@subsection Piping the output of javac and java
@cindex     Piping the output of javac and java

Output from the executables @strong{@code{javac}} and @strong{@code{java}} have their standard output
stream and standard error stream piped into Emacs' batch mode so that
error messages like @code{Foo.java:123} point back to the correct file
@code{Foo.jtw:123} even if file inclusion (@ref{J.T.W. Proof of concept
#2 file inclusion}) has been used.  The programs @code{grep} and @code{sed}
are also used as pipes in the transformation process so they must be
present on the client's system.

@node       Makefile for building *.jtw into *.java and running *.class files
@subsection Makefile for building *.jtw into *.java and running *.class files
@cindex     @code{Makefile} for generating @code{*.class} files from @code{*.jtw} files

Here is the @emph{GNU Makefile} for building @code{*.java} files and
@code{*.class} files and running them.

@example
.PRECIOUS:
.PRECIOUS: %.java %.class

JAVAC_FLAGS = -source 1.5 -Xlint:unchecked -Xlint:deprecation
JAVA_FLAGS  = -enableassertions
SHELL       = /bin/bash

%.java: %.jtw
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @@echo "* Stage 1 : Debugging $*.jtw and building $*.java file"
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} emacs --batch --eval "(setq *stump* \"$*\")" --load jtw-build-jtw.el --funcall doit

%.class: %.java
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @@echo "* Stage 2 : Debugging *.java and building *.class file(s)"
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} javac $(JAVAC_FLAGS) $$(find . -name "*.java") |& emacs --batch --eval "(setq *stump* \"$*\")" --load jtw-javac.el --funcall doit |& grep "input0-9:" - |& sed -e "s/input0-9:s//g" -

%.run: %.class
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @@echo "* Stage 3 : Running $*.class File"
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} java $(JAVA_FLAGS) $* |& emacs --batch --load jtw-java.el --funcall doit |& grep "input0-9*:" - |& sed -e "s/input0-9*://g" -

build: clean
@end example

@noindent The first line @code{.PRECIOUS} without any arguments clears the list
of precious files, the list of files not to delete during the build
process.



@node    Packages in J.T.W. and Java
@chapter Packages in J.T.W. and Java

The structure of a @strong{@code{package}} mirrors the file system.  For example you
can have a @strong{@code{package}} named (for argument's sake) @code{pkg} which
corresponds to a folder @code{pkg} in your @code{~/jtw-tutorials} folder.
You can have a sub-package called (for argument's sake) @code{inner}
which will reside in the folder @code{~/jtw-tutorials/pkg/inner}.  Even
though the second @strong{@code{package}} resides inside of the first @strong{@code{package}}, they
are still considered as separate packages.



There is a naming convention that I will not bother to use that helps
to give unique names to your packages.  If you own a website like
@uref{http://davinpearson.com,@code{davinpearson.com}} you can name your packages like so:
@code{com/davinpearson/inner/inner2} where @code{com/davinpearson} where
@code{com.davinpearson.inner} and @code{com.davinpearson.inner.inner2} are
separate packages.  The fact that I own the domain name
@code{davinpearson.com} ensures that my @strong{@code{package}} specification
@code{com/davinpearson} is unique.  The @code{com} comes first because it is
the actual domain name rather than the @code{com} extension that is
unique.  It is therefore non-sensible to place any code directly in
the @code{com} folder.  So in effect we are piggy-backing onto an
existing standard i.e. Internet Domain Names.  The same feature is
exploited by Websites which ask for your email address as your login,
as email addresses are unique to individual people.

@menu
* Moving a class into a package::
* Moving a class into a sub-package::
* Importing a package::
* Importing a package from another package::
* How to build a collection of class files or an entire package::
* How to invoke javadoc on a package::
@end menu

@node    Moving a class into a package
@section Moving a class into a package

@cindex Packages, moving a class into a package

Consider a typical @strong{@code{class}}:



@example
@noindent @code{@strong{@code{class}} A
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{property}} int data;

@tie{}@tie{}@tie{} @strong{@code{classVar}} int data2 = 666;

@tie{}@tie{}@tie{} @strong{@code{constructor}} A(int d)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} data = d;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{method}} @code{void} meth1()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("meth1:" + data);
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{method}} @code{void} meth2()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("meth2:" + data);
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{function}} @code{void} func()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("func:" + data2);
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} A a1 = @code{@strong{new}} A(123);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a1.meth1();} @i{// prints out "meth1:123"}
@code{@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} A a2 = @code{@strong{new}} A(456);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a2.meth2();} @i{// prints out "meth2:456"}
@code{@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} A.func();} @i{// prints out "func:666"}
@code{@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}}
@end example

To move this @strong{@code{class}} into a @strong{@code{package}} called (for argument's sake)
@code{pkg}, you need to set the @strong{@code{class}}'s visibility status from none
(i.e. @strong{@code{package}} visibility) to @strong{@code{public}}.  Also each package visible
(i.e. no @strong{@code{private}} or @strong{@code{public}} or @strong{@code{protected}} specification) @strong{@code{class}} variable,
@strong{@code{function}}, @strong{@code{method}} and @strong{@code{property}} needs to have its visibility status
changed from package to @strong{@code{public}} if you want to be able to access these
items from outside of the package.  If you have more than one class in
the same file, they will have to be separated into separate files as
you can only have one @strong{@code{public}} @strong{@code{class}} per file.  Also the name of the
package must be declared via a @strong{@code{package}} specification like so
@code{@strong{@code{package}} pkg;} at the top of the file before any actual @strong{@code{class}} or
@strong{@code{interface}} definitions.  Here is the same source file, ready to be put
into a package:

@example
@strong{@code{package}} pkg;

@strong{@code{public}} @strong{@code{class}} A
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{property}} int data;

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{classVar}} int data2 = 666;

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{constructor}} A(@code{int} d)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} data = d;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} @code{void} meth1()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("meth1:" + data);
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} @code{void} meth2()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("meth2:" + data);
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{function}} @code{void} func()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("func:" + data2);
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} A a1 = @code{@strong{new}} A(123);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a1.meth1(); @i{// prints out "meth1:123"}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} A a2 = @code{@strong{new}} A(456);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a2.meth2(); @i{// prints out "meth2:456"}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} A.func(); @i{// prints out "func:666"}
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

Also the source file for the class needs to be moved into the
folder @code{~/jtw-tutorials/pkg}.  To run the class, you will need to
invoke the @code{Makefile} command:

@center @code{make clean pkg/A.run}

@node Moving a class into a sub-package
@section Moving a class into a sub-package

Suppose you want to move a class @code{A} from no package (the folder
@code{~/jtw-tutorials}) to a package called for argument's sake
@code{pkg.inner}, the steps from @ref{Moving a class into a package}
needs to be followed, the only difference being that the @strong{@code{package}} spec
needs to be changed to @code{@strong{@code{package}} pkg.inner;} and the file needs to be
moved into the folder @code{pkg/inner}.  To run the @strong{@code{class}} file you need
to invoke the following Make command:

@center @code{make clean pkg/inner/A.run}.

Here is the class definition for the file
@code{~/jtw-tutorials/pkg/inner/A.jtw}:

@example
@strong{@code{package}} pkg.inner;

@strong{@code{public}} @strong{@code{class}} A
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{property}} @code{int} data;

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{classVar}} @code{int} data2 = 666;

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{constructor}} A(@code{int} d)
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} data = d;
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} @code{void} meth1()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("meth1:" + data);
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{method}} @code{void} meth2()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("meth2:" + data);
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{public}} @strong{@code{function}} @code{void} func()
@tie{}@tie{}@tie{} @strong{@code{begin}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} System.out.println("func:" + data2);
@tie{}@tie{}@tie{} @strong{@code{end}}

@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} A a1 = @code{@strong{new}} A(123);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a1.meth1(); @i{// prints out "meth1:123"}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} A a2 = @code{@strong{new}} A(456);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a2.meth2(); @i{// prints out "meth2:456"}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} A.func(); @i{// prints out "func:666"}
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@node Importing a package
@section Importing a package

@cindex Packages, importing

When referring to a @strong{@code{class}} or @strong{@code{interface}} in a @strong{@code{package}} you need to
specify the @strong{@code{package}} name in front of every @strong{@code{class}} name and @strong{@code{interface}}
name in the @strong{@code{package}} you want to access, like so, in the @strong{@code{main}} folder
@code{~/jtw-tutorials} (outside of any package):

@example
@strong{@code{class}} B
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} pkg.A a1 = @code{@strong{new}} pkg.A(123);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a1.meth1(); @i{// prints out "meth1:123"}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} pkg.A a2 = @code{@strong{new}} pkg.A(456);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a2.meth2(); @i{// prints out "meth2:456"}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} pkg.A.func(); @i{// prints out "func:666"}
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

To avoid having to qualify each class name and interface name with
it's package, you need to use the @strong{@code{import}} directive like so before the
definition of the class like so:

@example
@strong{@code{import}} pkg.*;

@strong{@code{class}} B
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} A a1 = @code{@strong{new}} A(123);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a1.meth1(); @i{// prints out "meth1:123"}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} A a2 = @code{@strong{new}} A(456);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a2.meth2(); @i{// prints out "meth2:456"}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} A.func(); @i{// prints out "func:666"}
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@node Importing a package from another package
@section Importing a package from another package

When referring to a class or interface in a package you need to
specify the package name in front of every @strong{@code{class}} name or @strong{@code{interface}}
name in the package you want to access, like so, in the folder
@code{~/jtw-tutorials/pkg} (i.e.\ in the @code{pkg} package).

@example
@strong{@code{package}} pkg;

@strong{@code{public}} @strong{@code{class}} C
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} pkg.inner.A a1 = @code{@strong{new}} pkg.inner.A(123);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a1.meth1(); @i{// prints out "meth1:123"}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} pkg.inner.A a2 = @code{@strong{new}} pkg.inner.A(456);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a2.meth2(); @i{// prints out "meth2:456"}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} pkg.inner.A.func(); @i{// prints out "func:666"}
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

To avoid having to qualify each class name or interface name with it's
package, you need to use the @strong{@code{import}} directive like so after the
@strong{@code{package}} declaration but before the definition of the @strong{@code{class}} or
@strong{@code{interface}} like so:

@example
@strong{@code{package}} pkg;

@strong{@code{import}} pkg.inner.*;

@strong{@code{public}} @strong{@code{class}} C
@strong{@code{begin}}
@tie{}@tie{}@tie{} @strong{@code{beginMain}}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} A a1 = @code{@strong{new}} A(123);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a1.meth1(); @i{// prints out "meth1:123"}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} @strong{@code{var}} A a2 = @code{@strong{new}} A(456);
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} a2.meth2(); @i{// prints out "meth2:456"}
@tie{}@tie{}@tie{} @tie{}@tie{}@tie{} A.func(); @i{// prints out "func:666"}
@tie{}@tie{}@tie{} @strong{@code{endMain}}
@strong{@code{end}}
@end example

@node How to build a collection of class files or an entire package
@section How to build a collection of class files or an entire package

@cindex Building code that uses a @strong{@code{package}}
@cindex Building a collection of classes
@cindex Packages, building
@cindex Collection of classes, building

When your class @code{X} uses another class @code{Y} in a different file
then you need to add to the @code{build} target of your @code{Makefile}
which is initially like so:

@center @code{build: clean}

to what follows:

@center @code{build: clean @strong{Y.java}}

If your class @code{Y} is in another @strong{@code{package}} such as the @strong{@code{class}}
@code{~/jtw-tutorials/path/to/dir/Y.class} i.e. in the @strong{@code{package}}
@code{path.to.dir} then you need to add to the build target of your
@code{Makefile} like so:

@center @code{build: clean @strong{path/to/dir/Y.java}}

This process should be repeated for every @strong{@code{class}} that is called,
directly or indirectly from your @strong{@code{main}} @strong{@code{class}} @code{X}.  By applying this
process to every file in your package, you can build an entire
package, simply by invoking the @code{Makefile} command @code{make build}.
To actually compile and run the @code{X} @strong{@code{class}}, let
@code{~/jtw-tutorials/path2/to/dir/X.class} be the location of the
@code{X} @strong{@code{class}}.  Then you need to invoke the following @code{Makefile}
target:

@center @code{make build @code{path2/to/dir/X.run}}

The build target calls the "@code{@strong{clean}}" target which deletes all
@code{@strong{*.java}} and @code{*.class} files directly or indirectly in the
folder @code{~/jtw-tutorials}.  If you don't do this then @code{@strong{java}}
might run an old version of @code{*.class} files despite earlier errors
in the build process. This is because the use of pipes in building and
executing @code{*.class} files hides the return values of the programs
@code{@strong{javac}} and @code{@strong{java}}.

@node How to invoke javadoc on a package
@section How to invoke javadoc on a package

@noindent To invoke @code{javadoc}, you first need to issue the following
command from the folder @code{~/jtw-tutorials}:

@center @code{make build}

@noindent See the @ref{How to build a collection of class files or an entire
package} for more information about setting up the @code{build} target.
Then you need to issue the following command from the folder
@code{~/jtw-tutorials}:

@center @code{javadoc path3/to/pkg -d /path4/to/dir}

where @code{path3.to.pkg} is the name of the package that you want to
build and @code{/path4/to/dir} is the desired location for your
documentation files in @code{*.html} format.



@node     GNU Free Documentation License
@appendix GNU Free Documentation License

@include fdl-1.3.txt

@node     Passwords for the answers to the tutorials
@appendix Passwords for the answers to the tutorials


Here are the passwords for the tutorials, which are located at the
following Website: @url{http://davin.50webs.com/J.T.W}.  They can be
found by clicking on the link in @emph{Section 3 Answers to the
tutorials} of the document.

@multitable @columnfractions .1 .5
@item @strong{No.}
@tab @strong{Password:}
@item 1
@tab policefish
@item 2
@tab chessweta
@item 3
@tab tallpencil
@item 4
@tab freshwhale
@item 5
@tab sneakermagic
@item 6
@tab kingpump
@item 7
@tab lakemarmite
@item 8
@tab nutriciouslamps
@item 9
@tab sadbutter
@item 10
@tab skyfresh
@item 11
@tab fivemagpies
@item 12
@tab phonesheds
@item 13
@tab dawnsweet
@item 14
@tab nightroads
@item 15
@tab blackscrews
@item 16
@tab snowfrog
@item 17
@tab tenflower
@end multitable



@node Index
@unnumbered Index

@printindex cp

@bye

