Computer Science Alone


Computer Science 201 Web Page
Computer Science 202 Web Page

This page, like life-long learning, is permanently under construction. Learning for life is like a great party that never ends. It just goes on and on. This is the stuff that makes life worth living.

This page is designed for students who cannot access Computer Science courses during the daytime timetable but who wish to study Computer Science in a flexible format that allows them to do so when it suits them, perhaps during a Professional Development Day, Saturday morning, Spring Break or summer holiday. It is specifically designed with IB Diploma students in mind who have an otherwise very full timetable. All learning materials are free for downloading. The student may do the work as they see fit and then arrange a time with a teacher to present solutions to exercises and arrange opportunities to write quizzes covering the material studied. The sequence of the material for these courses corresponds to that of Kjell Tutorials.

Ideally, the student should really follow the Kjell Tutorials in precisely the sequence that Kjell presents them, thus ensuring that the student will have any necessary background assumed by a particular tutorial.

Most students at my school beginning the Kjell Tutorials will have completed a 3-credit half course in Alice, but the Kjell Tutorials themselves assume no programming background whatsoever.

There is a "hidden agenda" in the back of this teacher's mind. (It won't be hidden to those reading this.) A great high-school experience in Computer Science, in this teacher's opinion, would be successfully negotiating Higher Level IB Computer Science (IB = International Baccalaureate), AP-AB Computer Science, the topics tested each year by the American Computer Science League, with ongoing competition in the TopCoder, USACO and Canadian Computing competitions. All this would be topped off by a resounding success in the Iverson Alberta University Computer Science Test. Somehow, like so many disparate pieces of a puzzle, this page will endeavour to shoehorn those pieces together. Now don't tell anyone. This is our secret. This is, after all, the hidden agenda!

Go for lime & cyan courses to prepare for computing competitions.
Go for lavendar courses for graphics and graphical user interfaces.
Go for yellow courses to learn advanced Java programming.
Go for INF courses to get 5 grade twelve CTS credits in one stream.

CLICK HERE TO INSTALL JAVA & ECLIPSE

Course #           IB Prereq Topics Kjell's Java Tutorials
ELT 2070       SL/HL
Computer Technology
None Operating System, Network.
Data Representation
Kjell's Assembly (Not Java)
Tutorials:   1 2 3 4 5 6 7 8
INF 2160       SL/HL
Programming 3
INF 2150 Introduction to Java & Branching 8 9a 9b 9c 10 11 12 13 14
INF 2170       SL/HL
Programming 4
INF 2160 Loops 15 16 17 18 19 20
39 40 40b 41 42 43 44
INF 2180       SL/HL
Programming 5
INF 2170 Arrays & ArrayList 46 47 48 49A 49B 49C 49D
INF 2210       SL/HL
Computer Science 2
INF 1210
INF 2180
Recursion
Sorting and Searching
70 71 72 73 74
Big Java 18 & 19
INF 2220     HL Only
Obj Oriented Prog 1
INF 2170 Objects & Classes 25 26 27 28 29 30 31 32 33
INF 3220     HL Only
Obj Oriented Prog 2
INF 2220 Encapsulation, Inheritance,
Polymorphism
34a 34b 35
50 51 52 53a 53b 54
DES 3010     HL Only
2-D Design Studio 1
INF 2180Event Handling:   Buttons,
Text & Mouse Input
Event Listeners
55 56 57 (Omit 58) 59 60
BIG JAVA 12
DES 3020     HL Only
2-D Design Studio 2
DES 3010Graphical User Interfaces:
Frames, Containers, Components,
Layout Managers, Menus
61 62 63 64
BIG JAVA 14
DES 3030
2-D Design Studio 3
INF 2180Applets, Graphics, HTML 36 37 38 Appendix-A
BIG JAVA 5
INF 3150
Programming App 1
INF 2180 Algorithms 1:   Canadian Computing,
TopCoder & USACO Competitions
Introduction, Math,
Divide & Conquer Algorithms
INF 3160
Programming App 2
INF 3150 Algorithms 2:   Canadian Computing,
TopCoder & USACO Competitions
Randomization, Backtracking,
Dynamic Programming
INF 3170
Programming App 3
INF 3160 Algorithms 3:   Canadian Computing,
TopCoder & USACO Competitions
Greedy Algorithms, Hill Climbing,
Graph Algorithms
INF 3210     HL Only
Computer Science 3
INF 2210 Exception Handling,
Files & Streams
80 81 82 83 84 85 86 87
BIG JAVA 15
INF 3230     HL Only
Data Structures 1
INF 2180 Linked Lists, Stacks, Queues BIG JAVA 20
INF 3240     HL Only
Data Structures 2
INF 3230 Sets, Maps, Binary Search Trees,
Heaps, Hash Tables
BIG JAVA 21


Today's files are BIG. Consider a flash drive.

JAVA HISTORY

You'll find the history of Java to be fascinating. Did you know that the original designer of Java was James Gosling from Calgary, Alberta?

Pop on your earphones and watch and listen to the following flash presentation on the: History of Java from PublicStaticVoidMain.

This page is for students studying
CTS Computer Science Independently.

This page is this teacher's attempt to set forth a course of study and resources which could be used to prepare students to earn credit in high school computer science courses.

This is not an official web site of any educational jurisdiction.

This page uses the Kjell Tutorials because this teacher's experience has shown that high school students learn to program in Java effectively, correctly and confidently with these tutorials. Other resources are also used. The Kjell Tutorials are freely obtainable.

This course uses the Java programming language because Java promotes the use of OOP: Object Oriented Programming. Today (June 1, 2008) OOP is the most popular and "respectable" programming paradigm in the professional programming community. Java is by far the most popular programming language in that community. Java is currently also the most accepted programming language used at secondary and post-secondary institutions in the world. Java is the prescribed language for both the Advanced Placement and International Baccalaureate high school computer science syllabi. Java is also the programming language most used in post-secondary institutions for teaching computer programming.

This course uses the Eclipse IDE (Integrated Development Environment) because it has proven to be incredibly powerful, scalable for the needs of a rank beginner to a professional developer, easily the most popular IDE in both academia and industry and thus the target the most extensive support. It is fun to use and grows with the needs of the student. It is freely obtainable.

Powerpoint slide shows by various authors are posted. Slideshows generally cover material corresponding to a textbook written by the author and are freely available. I have used Deitel's Java How To Program 4/e and Horstmann's Big Java 2/e in recent years. My experience with these textbooks and their corresponding Powerpoint slide shows suggests that these uses of Powerpoint slide shows is great for getting an overview of the topic, but because such slideshows are made with the assumption that a teacher or presenter is talking to them, such slideshows in themselves do not (and were not meant to) explain concepts very well. That said, they really are great for "getting the lay of the land".

More recently we have seen the rapid appearance of screencasts which, in my opinion, are a very large step beyond Powerpoint slideshows for independent learning. TechSmith, the makers of the superb commercial project Camtasia has rapidly become the standard for screencasting. Anyone who wants to see just how effective Techsmith's Camtasia screencasts can be for learning Java and the Eclipse IDE can download the free screencasts of Mark Dexter's tutorials.

Each Dexter tutorial is about 15 minutes of (screencast) video, which really takes at least twice that time if students implement the code as they go, and I recommend that students do so. Dexter has so far made available four sets of tutorials.

  1. Using the Eclipse Workbench (Do these first.)
  2. Eclipse and Java for Total Beginners (Excellent, but not really for "total" beginners.)
  3. Eclipse and Java: Introducing Persistence (Wait until you are more advanced.)
  4. Eclipse and Java: Using the Debugger (Superb!! Finally there is an excellent resource for learning this incredibly powerful programming tool. Best learned when learning arrays.)

You may download any or all four sets of the Dexter Tutorials at: http://eclipsetutorial.sourceforge.net/

I have used Big Java 2/e in teaching Java programming in the classroom. In case a student has access to that textbook, you will find links to that book's example code in white boxes. Just double click the link and, when the code appears in some application (like a browser or text editor), create a corresponding project and class (and perhaps package as well) in Eclipse and copy and paste it to the Eclipse editor. Likewise with the Kjell Tutorial examples, just copy the code and paste it in Eclipse.

There are a number of excellent free electronic books that should be considered for reference. Where a topic is frustrating or inadequately explained, reading different authors' explanations usually finds a clearer explanation. Some available electronic books are:

  1. The Java Tutorials created and maintained by Sun MicroSystems, the creator and owner of the Java programming language, are the most authentic, reliable, correct and currently updated tutorials in the world. There is and will continue to be reasons to turn to other tutorials, but because of the devotion and dedication that Sun has given to this resource, this is the single, most important primary resource with which to learn Java.

  2. Bruce Eckel's Thinking in Java, 3rd Edition is an industry standard. While the third edition is free, the fourth edition costs US$25 at Thinking in Java, 4th edition. Eckel's Hands-on Java CD-ROM 2nd Edition available for US$62 is a terrific deal. I have had in my lab for several years and recommend it highly for independent learning. It is a huge set of slides with accompanying audio!!

  3. David J. Eck's Introduction to Programming Using Java 5/e is an excellent text for independent learning.

  4. Canadian Mind Products Java & Internet Glossary is an incredible Java resource that seems to touch on ... just about everything.

  5. Blue Pelican Java is used by many schools in Texas and comes highly recommended by a number of their teachers.

  6. Java Beginner.com is really a collection of a number of smaller Java tutorials.

  7. 1000 Java Tips [csg] [web] is but one offering at a site containing a plethora of great Java learning resources.

  8. Java Lecture Notes are notes from the author's senior, undergraduate course taught at Polytechnic University in Brooklyn.

  9. Kick Java, Jeffrey Hunter's DBA Web Site, A Gentle Introduction to Java Programming offer interesting examples.

In Alberta, each "credit" of a course is roughly (sometimes very, very roughly) designed to reflect approximately 25 hours of classroom time. The material and work required to cover each of the following "topics" is intended to cover one Alberta CTS course and earn 1 CTS credit. CTS is Alberta Education's abbreviation for Career and Technology Studies. This page represents this teacher's attempt and judgement and does not in any manner whatsoever represent an official policy of Alberta Education.

CLICK HERE TO INSTALL JAVA & ECLIPSE

CLICK HERE TO INSTALL JAVA & ECLIPSE

TopicResourcesAssignments

Create
Your
First
Java
Program

Horstmann Chap 1

Kjell Chaps 5 6 7

Sedgewick Chap 2.1

Litvin Chap 2-GUI

Deitel Chap 2


TextPad

Crimson Editor

jEdit

sciTE

jGrasp

Horstmann 1

Deitel 2

Wu 2

King 2

You will now do your first Java program. It is customary that the first program developed when learning a programming language is printing the sentence, "Hello World!". Do that now.

If you have not already done so, you should now install Java and Eclipse!

It is important that you keep all of your Java source code in one place. Eclipse won't work until you give it a path where it will save Eclipse generated files. It does this by asking you where your "Workspace" is located. For now, first (outside of Eclipse) create a folder called ws where you want to save your work. Ideal directory names are short, mnemonic strings.

Launch Eclipse. Go to the Welcome page. (Click Help → Welcome.) Click the "Tutorials" icon. (Use mouse-over to identify it, if necessary.) Click "Create a Hello World application". Directions for the tutorial appear in the right frame. Follow them. Note: You are not ready for the other Eclipse tutorials at this point.

Read the Kjell Tutorials 5, 6 and 7 and do the examples.

Kjell presents examples using the command prompt and the Notepad text editor which have been included with every version of the Windows operating system from Windows 95 through Vista.

Do not feel compelled to use the Notepad text editor!! There are many far superior text editors, links to some of which are in the frame to the left. Do learn to use the command line prompt and some text editor at this time.

Text editors are convenient when you want to do something "quick and dirty" without troubling yourself to launch a large IDE. Every programmer should feel comfortable using a text editor. Both I and a number of teaching colleagues long used TextPad to develop Java source code.

Early developers of Java programs used these primitive tools. The advantage in learning to program with these tools is that you get to see development stages more clearly than with a powerful integrated development environment [IDE] which "automates" many functions. However, in this course, you will usually program using the Eclipse IDE because of the many and varied learning resources that it presents to a student.

Study Horstmann's Chapter 1 slide show. Note especially the development stages presented near the end of this slideshow.

Hereafter organize your Eclipse files into projects → packages → classes. Note that typical Java programs contain several classes.

  1. Make a project for each Kjell tutorial and/or Horstmann chapter.
  2. Make a package for each program within the chapter's project.
  3. Make a class for each bundle of code with a program's package.

Code, Compile & Execute Horstmann's HelloTester.java I told you that it was conventional to begin with "Hello World".

HelloTester.java

Initially, as with this initial example, an exercise may be solved using only one class; thus there would be only one class in a package. Later you will use multiple classes in a program that solves an exercise problem. In that event, all classes in such a solution would be in the same package. Here is how to do it.

For each exercise, submit a printed copy of a wordprocessing document containing:

  1. Footer
  2. Java source code following Horstmann's Styling Guide
  3. Identification Template
  4. Screen Dump
  5. Print on both sides of a sheet of paper, two pages per side == four pages per sheet of paper. See Make Hard Copy of Source Code.

Follow these directions to place line numbers with source code in Eclipse and later in WORD.

Follow these directions on organizing assignments when working with Eclipse.

The Icons of Eclipse

TopicResourcesSlide ShowAssignments

Data

Horstmann Chap 4

Kjell 8
Kjell 9a
Kjell 9b
Kjell 9c
Kjell 10
Kjell 11

Sedgewick Chap 2.2

Litvin Chap 6

Deitel Chap 2 3

Horstmann 4

Wu 3

King 3

Litvin 4

CashRegister.java CashRegisterTester.java InputTester.java

Study Horstmann's Fundamental Data Types: Chapter 4.

Learn about reading input and writing output using Java's Scanner class by reading the following Java's Scanner Class Overview [csg] [web] retrieved from the web site of North Carolina teacher Ruth Hartsook. Note that the overview is done in Flash. You may copy and paste code from the examples after clicking the capital "I" at the top of the screen, just to the right of the hand icon.

Read about understanding the problem with double arithmetic in Java, solving the double problem with the BigDecimal class, creating BigDecimal objects and doing arithmetic with BigDecimal objects in a bonus chapter, Using the BigDecimal Class [csg] [web], from Java All-in-One Desk Reference For Dummies (2nd Ed) ISBN: 0470124512 by Doug Lowe and Barry Burd (Wiley Publishing, Inc, 2007). Here is the source code of the examples:   BigDecimal Examples.

Learn about methods by studying the Methods Tutorial [csg] [web] retrieved from the web site of North Carolina teacher Ruth Hartsook. See two frames from her tutorial below.


A method's signature includes it's name and parameter list but not its return type.

The reason that the data type of a method is not part of its signature is because a method can be called without specifying the data type of its return value. Thus, given a situation whereby several methods are overloaded with the same method name and parameter list, the compiler would not know which method to call.

In the following example, if the return type were the only distinction between several methods of foo( ) which differed only in terms of the data type of the return value, then the compiler wouldn't know which method to call because the invoking line does not specify the data type of a return value.

The following method is legal but does not indicate the return data type.

foo( ) ;

Javadoc Comments:   Study the Learn Javadoc page.   Learn how to compose Javadoc comments and how to create a Javadoc HTML set of files.

  1. Give a Javadoc comment describing the purpose of every class.

  2. Give a Javadoc comment describing the purpose of every constructor.

  3. Give a Javadoc comment describing the purpose of every method.

  4. Give the Javadoc tag @param for every parameter of all constructors and methods.

  5. Give the Javadoc tag @return for all methods. Note that constructors do not have return statements.

Hereafter all methods should include the above five Javadoc comments in the source code.

TopicResourcesAssignments

Branching
&
Loops


Kjell 12
Kjell 13
Kjell 14
Kjell 15
Kjell 16
Kjell 17
Kjell 18
Kjell 19
Kjell 20

Sedgewick Chap 2.3

Litvin Chap 7

Deitel Chap 4

BRANCHING
Horstmann 6
Wu 5
King 4
Litvin 7

LOOPS
Horstmann 7
Wu 6
Litvin 11

Study Horstmann's Decisions: Chapter 6.

Earthquake.java EarthquakeTester.java
TaxReturn.java TaxReturnTester.java

Pay particular attention to the use of Boolean expressions, noting that using two Boolean operators such as && or | | short circuits the evaluation whereas using a single Boolean operator such as & or | always evaluates both operands.

Peruse interesting presentations of Boolean Expressions and Short-circuit Operators and Truth Tables and De Morgan's Rules by Bradley Kjell.

Study Horstmann's Iteration: Chapter 7.

DataSet.java InputTester.java
Investment.java InvestmentTester.java
Investment2.java InvestmentTester2.java
Die.java DieTester.java
Needle.java NeedleTester.java
Triangle.java TriangleTester.java

Learn about using the traditional "for loop" in Java by studying the following For Loop Tutorial [csg] [web] retrieved from the web site of North Carolina teacher Ruth Hartsook.

Learn about for loops by studying the For Loops Tutorial [csg] [web] retrieved from the web site of North Carolina teacher Ruth Hartsook.

Observe an example of the sequence of changes in values with nested loops in the following Nested Loops Demonstration [csg] [web] retrieved from the web site of North Carolina teacher Ruth Hartsook.

Learn to follow and trace the flow of execution through the following Nested Loop Demonstration [csg] [web] retrieved from the web site of North Carolina teacher Ruth Hartsook.

Study Horstmann's Iteration: Chapter 7.

Study Eck's Programming in the Small II Control for a traditional, easy to understand, treatment of loops and branching statements.

TopicResourcesAssignments

Number Systems

Computer numbering formats [Wikipedia] Check "External Links" at the bottom of the Wikipedia article.

Binary numeral system [Wikipedia] Check "External Links" at the bottom of the Wikipedia article.

Octal numeral system [Wikipedia] Check "External Links" at the bottom of the Wikipedia article.

Hexadecimal numeral system [Wikipedia] Check "External Links" at the bottom of the Wikipedia article.

Bits and Bit Patterns [Kjell's MIPS Tutorial #3]

Number Representation [Kjell's MIPS Tutorial #6]

Binary and Hex Representation [Kjell's MIPS Tutorial #7]

Binary Addition and Two's Complement Representation [Kjell's MIPS Tutorial #8]

Binary Addition Calculator (Java applet) [Kjell's MIPS Tutorial Appendix E]

Working with Binary and Hexadecimal Numbers

Computer Arithmetic

ACSL Handout: Computer Number Systems

Computer Number Systems Handout To Prepare For ACSL Contest #1

Click here for links to further resources on number systems.

What you must know about number systems for the 2007/08 ACSL Contest #1:

  1. Count in the binary, octal and hexadecimal number systems.

  2. Convert numbers from one base (decimal, binary, octal, hexadecimal) to another.

    • Convert a decimal number to a binary number.
    • Convert a binary number to a decimal number.
    • Convert a decimal number to an octal number.
    • Convert an octal number to a decimal number.
    • Convert a decimal number to an octal number.
    • Convert an octal number to a binary number.
    • Convert a binary number to a hexadecimal number.
    • Convert a hexadecimal number to a binary number.
    • Convert a binary number to a binary number.
    • Convert a decimal number to a binary number.

  3. Add, subtract, multiply and divide in the number systems.

    Convert everything to decimal → do the math → convert to target base.

  4. Solve for the unknown value X in an equation with values of the same base.

    Example:      X16 = FEED16 - 6ACE16
  5. Solve for the unknown value X in an equation with values of different bases.

    Example:      X378 = 1XF16

TopicResourcesSlide ShowAssignments

Object
Oriented
Programming

Kjell 25
Kjell 26
Kjell 27
Kjell 28
Kjell 29
Kjell 30
Kjell 31
Kjell 32
Kjell 33
Kjell 34A
Kjell 34B
Kjell 35

Sedgewick Chap 3

Litvin Chap 3

Deitel Chaps 8 9

Horstmann 3

Wu 4

King 3

Litvin 4

Study Horstmann's Implementing Classes: Chapter 3.

BankAccount.java BankAccountTester.java
CashRegister.java CashRegisterTester.java

Learn about encapsulation by studying the Encapsulation Tutorial [csg] [web] retrieved from the web site of North Carolina teacher Ruth Hartsook. Links to source code for this tutorial follows.

Student.java TwoStudents.java MyStudents.java

Create and automatically generate an ID template. You only need one ID template per program. Do not attach an ID Template to every class. Attach the ID Template only to the class containing the public static void main(String[] args) method, since it is the first line of this method where the program begins to execute. But do indeed attach a Javadoc comment to every other class describing the purpose of the class.

Click here to see how a method can return multiple values by returning an object containing values of multiple instance variables!!

Click here to see pros and cons about whether instance variables (aka "fields of a class") should be declared at the top or bottom of a class.

TopicResources & Assignments

Eclipse Workbench

Follow and implement the lessons and activities of Mark Dexter's six 15-minute tutorials of Using the Eclipse Workbench [csg] [web]

Refer to this Tutorial Companion Guide [pdf].
Refer to this Eclipse Project For Lesson 1.
  1. Workbench Layout, Views & Perspectives
  2. How to Arrange Views & Views Options
  3. Use & Customize Eclipse Perspectives
  4. Help Features & Navigation Tips & Tricks
  5. Key Assist & Keyboard Shortcuts
  6. Compare Editor, Restore Deleted Files
ResourcesAssignments

Boolean
Algebra

In past years students successfully practiced Boolean Logic with Electronic Workbench 5.12. It is more powerful than Eck's xLogicCircuits Java applet, but has a steeper learning curve. Eck's xLogicCircuits applet is sufficient to practice all of the electronic aspects of Boolean Logic that we require. Less powerful but interesting programmers that allow us to practice Boolean logic are:

  1. xLogicCircuits applet and labs & other applets
  2. DLSim 2.2
  3. Leggo My Logg-O
  4. Logic Gates Circuit Simulation Program
  5. Digital Workshop
  6. Multimedia Logic
  7. Xilinx ISE WebPACKTM
  8. The Iowa Logic Specification Language

Check out former student web pages on this topic:

  1. Boolean Logic by Lisa Chen (2002).
  2. Boolean Logic by Brian Lau (2003).
  3. Karnaugh Maps by Jacky Yeung (2003).

Boolean Algebra

The ACSL Handout: Boolean Algebra [doc] offers a brief introduction.

Read How Boolean Logic Works on the web site How Stuff Works.

Digital Logic by Ken Bigelow offers a structured and cohesive introduction to Boolean Logic.

Richard Jones' treatment of IB - Boolean Logic as found on his web site, IB Computing Home clarifies IBO's expectations.

Check out xLogicCircuits Lab 1: Logic Circuits from David Eck's book, The Most Complex Machine: A Survey of Computers and Computing.

Do all 10 exercises in Eck's LogicCircuits Lab 1: Logic Circuits [csg] [web].

You cannot normally save from an applet. Do a screen dump to a wordprocessor or paint programme to capture the image: Focus (mouse click) on the applet --> [Alt-PrtScn] --> Go to wordprocessor or paint program --> Focus --> [Ctrl-v].

Note: It is possible to import the files associated with the applet into Eclipse, launch the applet from within Eclipse, and then save the diagrams from the applet. To do this:

  1. Download the applet's source code files from Eck's Source Code Page:

    • the folder:   xLogicCircuits/
    • the file:   xLogicCircuitsApplet.java
    • the file:   xLogicCircuitsFrame.java
    • the file:   xLogicCircuitsLauncher.java

    OR

    import the Eclipse project from this Circuit directory.

  2. To import the project into Eclipse, do this:

    Launch Eclipse → File → Import... → Existing Projects in Workspace → Next> → Select root directory: copy path of the Circuit directory → Browse → Check the box of the Project "Circuit" → Finish → Expand (click "+" sign) the newly imported project "Circuit" → Expand the directory "src" → Expand the package "tmcm" → Select (right mouse click) "xLogicCircuitsLauncher.java" → Run as → Java applet.

  3. Circuit Diagrams may now be named, saved and loaded from within Eclipse.

Check out xLogicCircuits Lab 2: Memory Circuits from David Eck's book, The Most Complex Machine: A Survey of Computers and Computing.

Do all 9 exercises in Eck's xLogicCircuits Lab 2: Memory Circuits [csg] [web].

You cannot normally save from an applet. Do a screen dump to a wordprocessor or paint programme to capture the image: Focus (mouse click) on the applet --> [Alt-PrtScn] --> Go to wordprocessor or paint program --> Focus --> [Ctrl-v].


TopicResourcesAssignments

FOR and DO Loops

SWITCH Statement
== Multi-Branching

Bit and Shift
Operations

OperatorLogicalBitwise
NOT!~
AND&
&&
&
OR|
|  |
|
XOR^ ^
shift leftNot Applicable<<
arithmetic shift rightNot Applicable>>
bitwise shift rightNot Applicable>>>

Check out this TopCoder article:
A bit of fun: fun with bits

Kjell 39
Kjell 40
Kjell 40B
Kjell 41
Kjell 42
Kjell 43
Kjell 44

The ACSL Handout Bit-String Flicking [doc] uses the slang but colourful term flicking to describe these operations which change a one to zero and vice versa.

Review interesting presentations of Boolean Expressions and Short-circuit Operators and Truth Tables and De Morgan's Rules by Bradley Kjell.

Bit and Shift operations are summarized in Horstmann's Big Java 2nd Ed, Appendix M, pages 1158-1160.

This topic is better described as Binary Numbers and Logical Operators. It is an extension of the larger topic about Java Operators.

Note that a pair of symbols are used for the logical operations, "logical AND" [&&] and "inclusive OR" [ | | ] whereas a single symbol is used for bitwise operations, "bitwise AND" [&], "inclusive OR" [ | ], and "exclusive OR" [^].

The usefulness and application of these operations are seen in context in Kjell's course for assembly language programming, Programmed Introduction to MIPS Assembly Language. See in particular Kjell's chapters:

  1. Immediate Operands and Bitwise Logic
  2. Shift Instructions and Logic Instructions

Bit and shift operations compare equivalent binary patterns of decimal or other integers. See example below.

public class BooleanOps
{
   public static void main(String[] args)
   {
      System.out.println(3 & 22);                 // 2
      System.out.println(13 ^ 6);                 //11
      System.out.println(0 & (3-3));              // 0
      System.out.println(45 | 16);                //61
      System.out.println((2 & 5) | ((7^3) & 5 )); // 4
   }
}
XOR is supported by Java, but it is not possible to short-circuit an XOR expression because overall evaluation of the XOR expression always depends upon both operands. Java uses the caret (aka "circumflex") [^] as its XOR operator.

public class DemoXOR
{
    public static void main( String[] args )
    {
        int x = 5, z=10 ;
        if ( (x<10) ^ (z>5) )
            System.out.println("True Block") ;
        else System.out.println("False Block");
    }
}
TopicAssignments

Test-Driven Development

Shortcut To Print To Console:   Enter the "stuff" to be printed. → Highlight "stuff" with the mouse. → <Ctrl-Space> → <Up-Arrow> → <Enter> → Eclipse surrounds the "stuff" with System.out.println( ).

To create a separate testing folder to isolate JUnit testing code from application code:   File → New → Source Folder → Folder Name: test → Finish. This avoids deploying testing code with an application.

To create a JUnit package containing the same name as the application package being tested:   Select ("highlight") the name of the testing folder in the package view → File → New → Package → Type the same name as the source code package. (Both the application and testing package have the same names.) → Finish.

To create a JUnit test class:   Right mouse click the testing package → New → Other → JUnit → JUnit Test Case → Type name of testing class == name of class to be test followed by "Test" (eg: "BeHappyTest") → Place desired ✓s for method stubs → Finish → Finish.

To create a JUnit test suite:   Highlight the testing package. → Right mouse click → New → Other → JUnit → JUnit Test Suite → Next → Place desired ✓s → Finish. This creates a single-button test for an entire application!

Names of all JUnit testing methods begin with "test..."

Variable name that is italicized is a static variable.

To open a new Java Scrapbook Page:   File → New → Other.... → Select Java → Java Run/Debug → Scrapbook Page. → Click Next. Don't forget to later select ("highlight") the code before clicking the "inspect" button.

To automatically generate accessor &/or mutator methods:   Source → Generate Getters and Setters... → Place desired ✓s → OK.

Quick Fix:   <Ctrl><1> ( ie: Control-One ) OR Click on the light bulb. The Java editor offers corrections for most problems underlined with a problem highlight line.

TODO Comment:   // TODO tada
(No space between "TO" and "DO") Eclipse maintains a task "ToDo" list for you. Window → Show View → Tasks.

Comment a section of code:   Highlight the section of code → <Ctrl>< / > Toggling <Ctrl>< / > "uncomments" commented code.

To provide package access to a class member:   Remove all scope modifiers. Scope modifiers are private, public and protected.

To convert a local variable to an instance variable (ie: instance "field"):   Select a declaration or a reference to a local variable → Refactor → Convert Local Variable to Field... → Select access modifier → Select location for initialization → Select whether field is to be static → Select whether field is to be final (ie: a constant) → OK

To automatically extract a method from a block of code:   Highlight the lines → Refactor → Extract Method... → Type methodName → OK Same blocks of code throughout the class are replaced by the method call!

To automatically create a public method template:   Type "pub" (initial three letters of "public") → <Ctrl-Space> → Select "Public_method - public method" → Type "void" or other return type → Enter → Tab → Type "testToString" or other name of method Do a similar process for a private method template.

To automatically create the public static void main( String[ ] args ) template:   Type "main" → <Ctrl-Space> → Press <Enter> This is the point in Java where execution of the program begins.

To automatically create an assertEquals( expected, actual) call:   Type "assert" (initial letters of "assertEquals...") → <Ctrl-Space> → Press Enter → Type "Smith" or other string → Enter → Tab → Type b2.toString() or other string reference call → Type a semicolon to end the statement Do a similar process for other standard method calls.

Test-Driven Development
  1. Think about what the method should do.
  2. Write a test case that will test this method.
  3. Write the new method.
  4. Test the new method.
  5. When it passes ... we're done!

... the unit tests document the program without the need to maintain separate written documentation that can easily become out of date.

Mark Dexter, Using Test-First Development


Follow and implement the lessons and activities of Mark Dexter's sixteen 15-minute tutorials of Eclipse And Java For Total Beginners [csg] [web]

Toggle <F11> to switch between IE's normal and full screen views.

Toggle <Alt-Tab> to switch to your last application, as between Eclipse (program development) and Internet Explorer (tutorial).

Preserve the project at the end of each tutorial. To do this, create a new project at the beginning of each tutorial and import the project from the end of the last tutorial into a the new tutorial's project. Projects can be called TB1, TB2 .... (TB == Total Beginner)

Refer to this Tutorial Companion Guide [pdf].

Beware This GOTCHYA: The tutorial code refers to an object "ml" of a class "MyLibrary". The "ml" is "m" followed by the letter "l" (pronounced "el"), not the digit "1" (one).

  1. Create Your First Class
  2. Add Methods to Class
  3. Use Eclipse Scrapbook
  4. JUnit: Create Test Class
  5. JUnit: Create Test Methods
  6. Using Test-First Development
  7. Create Book Class
  8. Add Person to Book Class
  9. MyLibrary Class and ArrayList
  10. Start on MyLibrary Class
  11. Create first methods in MyLibrary class
  12. Create checkOut( ), checkIn( ) Methods
  13. Continue checkOut( ) Method
  14. Finish checkOut( ) Method
  15. Finish MyLibrary Methods
  16. Create main( ) Method and JAR File

For the final code, including all application and testing code, submit a printed copy of a wordprocessing document containing:

  1. Footer
  2. BIG JAVA's Formatting Style by importing UBC's file.
  3. Identification Template
  4. Screen Dump(s)
  5. HTML Javadoc files including the standard tags @author, @version, @param, @return and the customized tags @invariant, @pre and @post
  6. Print on both sides of a sheet of paper, two pages per side = = four pages per sheet of paper. See Make Hard Copy of Source Code.

To create an executable JAR file:   [ Hint: First save the path to your project so you can later paste it as the destination location of your executable JAR file → Right mouse click name of project → Properties → Select ("highlight") the location (eg: "H:\TotalBeginnerProjects\TB11") → Copy with → Cancel ] File → Java → JAR file → Next > → Select by checking ✓ only the #src directory → Select a directory to save the JAR file in → Give the JAR file a name (eg: mylibrary.jar) → Next > → Tell Eclipse which class has the main() method (Click the "Browse..." button.) → Finish    JAR == Java ARchival File. An executable JAR file will execute on any system that has a JRE (Java Runtime Engine) installed. Selecting only the #src directory allows us to now easily exclude the bundling of testing code with the application.

To check the run of your JAR file from the command line prompt:   Copy the path of your JAR file location: Right mouse click name of JAR file → Properties → Select ("highlight") the location sans name of file (eg: "H:\TotalBeginnerProjects\TB16") → Copy with <Ctrl-C> → OK ] → [ Note: In order for the JAR file to "automatically" execute at the command line prompt, the O/S environmental path variable must be contain the path to Java's jar.exe file. An example of the location of a jar.exe file is: C:\Program Files\Java\jdk1.6.0_01\bin.] → Start → Run... → Type cmd in the Open dialog window → A command prompt window (aka DOS window) opens → On the prompt line, type the drive location of the file (eg: "H:) → Press <Enter> → The prompt now reflects the root of the drive where the JAR file is located ( eg: H:\> ) → On the prompt line, type "cd" (stands for "change directory") → Press the space bar once. → Right mouse click the title bar. → Edit → Paste → The prompt line should now include the path of the JAR file. [ eg: H:\TotalBeginnerProjects\TB15\TB16> ] → Type "dir" to call the directory → You should now see the jar file. → At the command line, type "java -jar followed by the name of the jar file. [ eg: java -jar mylibrary.jar ] → Press <Enter> → The JAR file should now execute.

Create A "New" Project From An Existing Project

These are really "backups of prior stages" of a single, cumulative project. It would be tragic if, upon experiencing a "bug" during tutorial #12 that could not be corrected, you had to redo all eleven prior tutorials in order to continue the project. Taking a few moments at the beginning of each new stage of the project (each new tutorial) ensures that you always have a "last good stage" that is only one tutorial away. This also facilitates later review of code of a specific tutorial at that particular stage of development.

  1. Create a new project:   File → New → Project.. → Java → Java Project → Next → Project Name: TB12 → Create new project in workspace → Select a JRE (Java Runtime Environment) → Select Project layout → Finish

  2. Copy path of location of source project:   Right mouse click name of project → Properties → Select ("highlight") the location (eg: "H:\TotalBeginnerProjects\TB11") → Copy with <Ctrl-C> → Cancel

  3. Open the Import Wizard:   Select ("highlight") name of new project → From the main menu bar, select File → Import....

  4. Select Type of Resources To Import:   General → File System → Next.

  5. Specify Path and Files To Import:   Identify source directory as the "From directory:" → Paste <Ctrl-V> location of the source project (eg: "H:\TotalBeginnerProjects\TB11") → Click the "Browse..." button → The "Import from directory" dialog box appears with name of source folder → Click "OK" → Click the "Select All" button → Type name of "Into folder" (existing destination folder) if it is not already there. → Check ✓ "Overwrite existing resources without warning" → Select "Create selected folders only" → Finish

Why Study Arrays Independently Before Studying Java's Array List Class?
TopicResourcesSlide ShowAssignments

Arrays
and
Array
Lists

Kjell 46 47 48 49A 49B 49C 49D

Sedgewick Chap 2.5

Litvin Chap 12

Deitel Chap 7

Horstmann 8

Wu 10

King 5

Litvin 12 12½

Study the Kjell chapters: 46 47 48 49A 49B 49C 49D

Do all the exercises and quizzes associated with the Kjell chapters on arrays.

Programming Exercises To Be Graded: 46 [1-5], 47 [1-5 ], 48 [1-3], 49B [1-3]. 49C [1-9] and 49D [1-3]. For each exercise, submit a printed copy of a wordprocessing document.

Chapter 8 Demo Source Code

ArrayListTester.java BankAccount.java
Bank.java BankAccount.java BankTester.java
TicTacToe.java TicTacToeTester.java
The Debugger is the single most powerful, effective, efficient tool there is for learning and analyzing the implementation of grand plan and elaborate design. It is a microscope that tests thought. It is a gyroscope of that stabilizes implementation. It is a laboratory for dissection and inspection. Use it often.
TopicResourcesSlide ShowAssignments

Testing
and
Debugging

Horstmann Chap 10

Sedgewick Chap 3.0

Using the Debugger
[csg] [web]

Horstmann 10

King 10

Chapter 10 Demo Source Code

Word.java
WordTester.java

junit/Numeric.java
junit/RootApproximator.java
junit/RootApproximatorTest.java

TaxReturn.java
TaxReturnTester.java

root1/Numeric.java
root1/RootApproximator.java
root1/RootApproximatorTest.java

root2/Numeric.java
root2/RootApproximator.java
root2/RootApproximatorHarness1.java
root2/RootApproximatorHarness2.java
root2/RootApproximatorHarness3.java
root2/RootApproximatorHarness4.java
root2/test.in

root3/Numeric.java
root3/RootApproximator.java
root3/RootApproximatorHarness5.java
root3/RootApproximatorHarness6.java

The Debugger is used for development and not just error identification!!

  • Create a breakpoint where you want to start inspecting the state of your program while it executes, line by line.

    To set a breakpoint:   Double click the gutter to the immediate left of the targeted line of source code.   The Breakpoint tells the debugger to pause at this point.   To eliminate a breakpoint:   Double click the breakpoint.

  • To initially START a debug session from within the Java Perspective:   Run → Debug As → Java Application → Editors → There appears the dialogue box "Confirm Perspective Switch" → Check "Remember my decision" → Yes.   Eclipse switches to the Debug perspective.

    Thereafter simply press <F11>.

  • In any "perspective", keep open only those frames that contain information that you will use.

    When initially using the Debug Perspective, open the Edit, Breakpoints, Variables, Console and Tasks frames. Close all other frames. Rearrange and resize the remaining open frames for optimal viewing.

    Place Edit frames vertically on the left separated by tabs. Place the Variables and Breakpoints frames vertically on the right separated by tabs. Place the Console and Tasks frames horizontally on the bottom separated by tabs.

  • To STOP a debug session:   Press the stop button.

  • To start a NEW debug session:   Press the Debug Button.

  • Use control keys to walk through the code line-by-line while inspecting values of variables.

    All Eclipse action keys are documented in the Eclipse Run Menu Actions documentation. Begin by using the following debug actions when generating and debugging code.

    FunctionButtonHot KeysPurpose
    Debug   Begin execution until reaching a breakpoint or end of program.
    Resume <F8> Continue execution until another breakpoint or end of program.
    Terminate   Stop the debug session.
    Step Into <F5> Move into the method or constructor being called and pauses.
    Step Over <F6> Execute current line of code and stop at next line.
    Step Return <F7> Finish current method then return to the calling method.
    Debug Last <F11> Debug last launch or debug current selection.
    Run Clean <Ctrl><F11> Run last launch or run current selection without debugging.

TopicAssignments

Testing and Debugging

Test-Driven Development
  1. Think about what the method should do.
  2. Write a test case that will test this method.
  3. Write the new method.
  4. Test the new method.
  5. When it passes ... we're done!

... the unit tests document the program without the need to maintain separate written documentation that can easily become out of date.

Mark Dexter, Using Test-First Development


Debugging
  1. Start a debug session.
  2. Set and use breakpoints.
  3. Navigate through a program with step commands.
  4. Examine variables and expressions.
Mark Dexter, Eclipse & Java: Using the Debugger


Follow and implement the lessons and activities of Mark Dexter's seven 15-minute tutorials of Using the Debugger [csg] [web]

Refer to this Tutorial Companion Guide [pdf].
Import this DebuggerTutorial project into your Eclipse workspace. Click here for directions.
  1. Startup, Step Over, Step Into, Step Return [End Prj 01]

  2. Examine Contents of Variables [End Prj 02]

  3. Add Watch Sessions, JUnit Tests [End Prj 03]

  4. Exception Breakpoints, Change Values [End Prj 04]

  5. Breakpoint Options, Watchpoints [End Prj 05]

  6. Debug into Java System Classes → Object references and the equals( ) method. [End Prj 06]

  7. Study Recursion, Stack Frames → Anatomy of a recursive method. [End Prj 07]

Mark Dexter

Eclipse & Java: Using the Debugger

The link to the Camtasia movie tutorial where each note is found follows that note. If you are confused by the note or don't understand what it is referring to, you may peruse that tutorial to refresh your memory.

Debugger is a set of tools that allows us to:
      * pause a running program at any point.
      * examine the contents of the variables.
[ Lesson 01 ]

To display line numbers:   Window → Preferences... → General → Editors → Test Editors → Check the box "Show line numbers" → OK [ Lesson 01 ]

To set a breakpoint:   Double click on gutter to immediate left of line of source code. Breakpoint tells debugger to pause at this point. To eliminate a breakpoint:   Double click the breakpoint. [ Lesson 01 ]

To START a debug session:   Run → Debug As → Java Application → Editors → There appears the dialog box "Confirm Perspective Switch" → Check "Remember my decision" → Yes Eclipse switches to the Debug perspective. [ Lesson 01 ]

To STOP a debug session:   Press the stop button (red square). [ Lesson 02 ]

To start a NEW debug session:   Press the Debug Button (looks like an insect "bug"). [ Lesson 02 ]

Debugger's Debug View:   shows
      * Class being run.
      * Thread being run.
      * Stack Frame(s) - where we are in the program.

To work the Debug View:  
      Resume button continues execution until another breakpoint or end of program.
      Terminate button stops the debug session.
      Step Into <F5> button moves into the method or constructor being called and pauses.
      Step Over <F6> button executes current line of code and stops at next line.
      Step Return <F7> button finishes the current method and returns to the calling method.
[ Lesson 01 ]

To go to another line without using a breakpoint → Use the "Run to Line" command:   Select (click on) the target line → Run (or Right Click) → Run to Line <Ctrl><R> [ Lesson 02 ]

Debugger's Job Editor: highlights line of code that we are about to execute. [ Lesson 01 ]

Debugger's Outline View: [ Lesson 01 ]

To set up Debug Filters to skip Java language classes and third party libraries:   Right click in Debug Window → Edit Step Filters... → Check box "Use Step Filters → Check box "Java.*" → OK   This filters out any packages starting with the word "Java" and thereby lets us skip all of the "Java" related stack frames. Note, back in the Debug Window, that the "Use Step Filters" button is now toggled on. Ensure that it is on when you want the filters to be operational. [ Lesson 02 ]

Debugger's Stack Frames (in the Debug View): The top stack frame in a stack always point to where we are presently. A new stack frame is added to the top of the stack when entering a constructor or method. The top stack frame is removed when returning from a constructor or method. Selection of Stack Frame correspondingly changes the members in the Variables View and the selected line in the Editor View. [ Lesson 02 ]

Debugger's Variables View (Upper right portion of screen) let's us see the value of variable in real time: [ Lesson 01 ] Variables are defined (ie: "in scope") corresponding generally to the currently selected stack frame (Debug View) and specifically to the currently selected source code line (Editor View). Variables and their values change as you step through the code. Detailed Pane of Variables View: Select a variable or object → Notice the display in the lower portion of the view, aka "the detailed pane" → This is the output of the toString() method of the selected variable.   Menu of Variables View: Select options from the two submenus, "Java" (which members to display) and "Layout". [ Lesson 02 ]

To inspect the value of an object that is in scope:   [ <Ctrl><Shift><I> ] or Select (click on) the object → Right Click → Inspect   View values of variables (Variables View) [ Lesson 02 ]

Add a Dynamic Watch Expression:   To see the value of an expression that is not a simple variable Window → Show View → Expressions Right Click → Add Watch Expression... Type any expression → OK   Values will change dynamically as you step through the code. [ Lesson 03 ]

Add a Static (Snap Shot) Watch Expression:   Window → Show View → DisplayNotice Display View has opened at the bottom of the screen Type any expression (can use Code Assist) → Highlight the expression → Right Click → InspectWe see values in the pop-up window → <Ctrl><Shift><I> → moves everything to the Expressions View → Will NOT change dynamically as you step through the code unless you do this: → Right mouse click → Convert to Watch Expression. [ Lesson 03 ]

Add Dynamic code to the Display Window:   Window → Show View → DisplayNotice Display View has opened at the bottom of the screen.Type any Java code (can use Code Assist). → Highlight the expression. → Right click. → Execute →   Output is printed in the Console View just as if running from a Java application. [ Lesson 03 ]

Selecting Valid Parts of an Expression → Highlight top-most part of an expression → then drill down one level at a time:   Place cursor anywhere on the expression → <Alt><Shift><UP> To restore previous selection:   Place cursor anywhere on the expression → <Alt><Shift><DOWN> [ Lesson 03 ]

Debugger's Breakpoints View (Upper right portion of screen):   Can toggle breakpoints on and off, create new breakpoints or delete breakpoints. Add Java Exception breakpoint:     Click Java Exception Breakpoint Button (just above Breakpoints View) OR → Run → Add Java Exception Breakpoint... → Opens a Java Exception Breakpoint dialog box   Type the kind of exception to look for { Note: With JUnit Tests, always use caught exceptions since all JUnit Tests are caught exception. ] → Click on the "Matching Item" selection → A NullPointerException is added to the Breakpoints View. Change Java Exception breakpoint Properties:     Go to Breakpoints View → Right click on a particular exception → Breakpoint Properties... → You see the Java Exception Breakpoint Properties dialog box. → Check/uncheck as desired → OK [ Lesson 04 ]

To Terminate & Relaunch a Debug Session:   Right click in the Debug dialog window. → Terminate and Relaunch [ Lesson 04 ]

Hot Code Replace:   Change code in debugger. → Resume [ Lesson 04 ]

To go back to beginning of method:   Click "Drop To Frame" button. [ Lesson 04 ]

Set number of times to bypass breakpoint before suspending execution:     Breakpoints tab → Right click the breakpoint → Breakpoint Properties... → Enter number of times to bypass breakpoint. → OK [ Lesson 05 ]

Conditional Breakpoints (suspend only if condition is true):   Set number of times to bypass breakpoint before suspending execution:     Breakpoints tab → Right click the breakpoint → Breakpoint Properties... → Type condition ( Example: this.getBooksForPerson( p1 ).size() > 0 ) → OK [ Lesson 05 ]

Watchpoints (field breakpoints):   This is useful for identifying where a certain value is used or changed. Set one watchpoint instead of setting multiple breakpoints!   Click in trough beside name of a field Click on Debug Perspective → Breakpoints tab → Right click breakpoint → Breakpoint Properties dialog appears → May suspend on Field Access or on Field Modification → OK Execution suspends whenever that field is accessed. [ Lesson 05 ]

Set breakpoint only the first time that a new class is loaded:     Click in trough beside name of a class. [ Lesson 05 ]

Stop in Main Breakpoint:   Set breakpoint at first line of code, which is upon entering the main method.   Run → Open Debug Dialog... → Java Application → Class (eg: MyLibrary) → OPens the run configuration dialog → Check Stop in main → Debug   Execution will now always stop at the first line of code in the main( ) method. [ Lesson 05 ]

Suspend a program during a debug session at any moment     Press the Suspend Button. [ Lesson 05 ]

Step into Selection     Hold <Ctrl><Alt> → Hover over name of method → Name of method turns into a hyperlink → Click hyperlink with mouse → You will step into the method. → OR → Select name of method → <Ctrl><F5> [ Lesson 05 ]

See source code without Debugger stepping into the selection. Works in Editor and does not require that there be a Debugger session working.     Select name of method → Press <Ctrl> and hover over name of method → Name of method turns into a hyperlink → Click on method hyperlink &rarrr; Source code of method then opens.   Note that position of Debugger has not moved at all. [ Lesson 05 ]

Configure Eclipse to use a special version of a JRE (Java Runtime Engine) that will allow us to Debug into Java classes.   This allows us to study the source code of the standard Java libraries.   This allows us to step into and study the code of the top Java programmers themselves!     Window → Preferences → Java → Installed JREs → Observe that you have your standard JRE installed. → Add... → JRE Type: Standard VM → JRE Name: Debug JRE → Browse... → Go to the JDK home directory. Example: C:\Program Files\Java\jdk1.6.0_01Expand (click "+") and observe that you have both source code and Javadocs. → OK → Keep the standard JRE as the default for new projects by leaving it checked. Do not place a check beside the new Debug JRE. → OK → Now add the Debug JRE to the project. → Select the project → Project → Properties → Java Build Path → Libraries tab → Add Library → JRE System Library → Next> → Click radio button to select Alternate JRE → Select Debug JRE → Finish → We will now remove the standard JRE. → Click on the standard JRE → Remove → Standard JRE is only removed from the project, not the system! → OK   Now when you look at your project, it says JRE System Library [Debug JRE]Eclipse rebuilt the project using the new Debug JRE.   We can now debug right into the Java System classes. [ Lesson 06 ]

Use the Debugger to Study Object references and the String .equals( ) method. [ Lesson 06 ]

Run a recursive method in debug mode to learn more about how recursion works.   A recursive method is a method that calls itself (that calls itself, that calls itself ....) Some value(s) change during the calls to eventually end the program, otherwise the program would never end.     Open the factorial method in the MyUtilities class. → Note that this method works only if n<=12 since the maximum value that a Java integer can be is 2,147,483,647.     Press resume → Observe the creation of a new stack frame on top as you call the new method again, going one level deeper into the program. → Notice that the variable "result" does not take on a value while the method continues being called because it has not yet been evaluated. → Continue pressing resume observing the value of n decreasing until it becomes less than 1 → Step over → The base case (n<=1) kicks in, ending the recursive process → This is where we BEGIN doing our calculation → Step over until n=2, then we find our first stack value for result (result=2) → Press "Step Return" to get out of that stack frame, noting that n=3 → Step over, noting that result=6 → Step Return and Step Over again to see n=4, result=24 → Step Return and Step Over again to finally get n=5 and result=120 [ Lesson 07 ]

Run a recursive method in debug mode a second time for more explanation. (Begin at time 6:20 of lesson #7.)     Click the Debug button. (It looks like an insect type bug.) → Click the resume button until you get to n=1. → Think of it this way → Each time that we call the recursive method, we add another frame on top of the stack until we eventually get to the point where n=1. Up until this point, no real calculations have been done. The frames are just holding the places for the yet-to-be-determined return values from the factorial (recursive) methods. When we finally get the value n=1, we will not return any more stack frames because we are just going to return the value of 1. Since the top frame can now return the value of 1, the result is returned from the top frame to the frame just below it. That is when the actual calculation(s) take place.

Thus there are two parts to processing a factorial method:

  1. Add stack frames for each method call until the method stops calling itself.
  2. Return the result from the top frame to the one below, remove the top stack, and continue returning results until we are back to the original calling method.

There are thus two conditions for recursive methods.

  1. The method must eventually stop calling itself.
  2. You need enough memory to hold the stack frames. [ Lesson 07 ]

Rewind the Program Back to An Earlier Frame. Take another look at the Drop To Frame command.   Rerun the debug session.   Press resume until n=1. → In lesson 4, we learned that pressing the "Drop to Frame" button would "rewind the debug session" by pressing a previous line in the Editor View and then pressing the "Drop-to-Frame" button. → OR → Select a lower stack frame and go back to that frame. → Remember that the top stack frame is where we are right now in the program. Thus each lower stack frame is from an earlier point in the program. Therefore selecting a lower stack frame takes us back in time. → Click on a lower stack frame → Click on the Drop to Frame button. → The program returns to that point in the program. → There are some things that are done in a program that prevents rewinding the program. The the Drop to Frame button becomes disabled. [ Lesson 07 ]

Uses of Drop to Frame Button if the Program Can Be Rewound

  1. Select an earlier line in the Editor View.
  2. Select a lower stack frame. [ Lesson 07 ]
TopicResourcesSlide ShowAssignments

Inheritance
Interfaces
Polymorphism

Horstmann Chap 11

Horstmann Chap 13

Sedgewick Chap 3.0

Horstmann 11

Horstmann 13

King 10

Study Horstmann's Interfaces & Polymorphism: Chapter 11.

Chapter 11 Demo Source Code

BankAccount.java Coin.java DataSet.java DataSetTester.java Measurable.java

DataSet.java DataSetTester2.java Measurer.java RectangleMeasurer.java

DataSet.java DataSetTester3.java Measurer.java

TimerTester.java

TimerTester2.java


Read Gerry Donaldson's explanation of an interface in response to another teacher's question.

Read Joe Bergin's explanation of an interface in response to another teacher's question.

Study Horstmann's Inheritance: Chapter 13.

Chapter 13 Demo Source Code

AccountTester.java
BankAccount.java
CheckingAccount.java
SavingsAccount.java

Programming Exercises To Be Graded: Kjell's Chapter 53B - Exercises 1 and 2

TopicAssignments

Chap 18
Recursion

"In order to understand recursion you must understand recursion."
- Dan R. Ghica, Java Workshop: Recursion

Three Rules For Recursion:

  1. Find out how to take just one step.

  2. Break each journey down into one step plus a smaller journey.

  3. Know when to stop.

Source: How TO teach and NOT TO teach Recursion (opinions from the experts?), page 14 [pdf] by Fran Trees


Check out the following two parts of a TopCoder tutorial that applies recursion to computing contest programming problems.

  1. An Introduction to Recursion, Part 1
  2. An Introduction to Recursion, Part 2

Teaching Strategies

  1. Martin and the Dragon
  2. Evaluate combo(4,3)
  3. The Cat In The Hat Comes Back

Real Recursion - Fibonacci Numbers and Nature

Kjell's Java Tutorials
70, 71, 72, 73, 74

Sedgewick Chap 2.7

Horstmann 18 [ppt]

Carrano/Savitch 10 [ppt]

  1. Learn about recursion by studying the Recursion Tutorial [csg] [web] retrieved from the web site of North Carolina teacher Ruth Hartsook.

  2. Study Mark Dexter's 15-minute screencast tutorial Study Recursion, Stack Frames → Anatomy of a Recursive Method. Implement the tutorial's code after importing this Eclipse project. Go here for instructions on importing an Eclipse project.

  3. Read and do the recursive examples in Fran Trees' presentation, How TO teach and NOT TO teach Recursion (opinions from the experts?) [pdf].

  4. How does the song There's a Hole in the Bucket exemplify infinite recursion?

  5. Read and study the Kjell Java Tutorials covering "Recursion": 70, 71, 72, 73, and 74.

  6. Study Horstmann's Recursion: Chapter 18.

    Chapter 18 Demo Source Code

    Triangle.java TriangleTester.java
    PermutationGenerator.java PermutationGeneratorTester.java
    FibTester.java FibTrace.java FibLoop.java
    Evaluator.java ExpressionTokenizer.java EvaluatorTester.java

  7. Recursion = Russian Nesting Dolls: Russian nesting dolls (aka "matryoshka") may be seen as a metaphor for recursion. Can you see why? In what way does each smaller doll represent a smaller version of the same "problem" of the larger doll in which it was/is encased?

  8. Recursion = Shockwave app of a red square tilting recursively
    A neat animation of recursion (no source code) here.

  9. Recursion = Escher's Ascending Descending Staircase

    The animated M.C. Escher's Ascending Descending Staircase may also be viewed as a representation of recursion. It was retrieved from the site, M.C. Escher work (c) Cordon Art B.V. - Baarn - the Netherlands.

    Incidentally, the initials M.C. in Escher's name stand for "Maurtis Cornelis". Click here to see what Escher's actual Ascending Descending Staircase looked like.

    Now check out the beauty of the java code implementing recursion at The Animation of Recursion"


  10. Towers of Hanoi is the most famous recursion exercise in Computer Science. Virtually every book that covers recursion uses the Towers of Hanoi as either a demonstration or an exercise.


  11. Assignment for Programming Exercises To Be Graded

    1. First: Read and do the recursive examples in Fran Trees' presentation, How TO teach and NOT TO teach Recursion (opinions from the experts?) [pdf].

    2. Read and study the Kjell Java Tutorials on recursion: 70, 71, 72, 73, and 74

    3. Do the eleven Kjell exercises that correspond to the Kjell Java Tutorials on recursion: 70 (no exercises), 71 (1 exercise), 72 (2 exercises), 73 (5 exercises), and 74 (3 exercises).

    4. Do two Horstmann exercises in BIG JAVA, chapter 18 (pp 695-700): P18.2 and P18.4.

    5. Implement in Eclipse's JDT recursive source code that solves the Towers of Hanoi puzzle. You may obtain the source code from any source.

    6. For each exercise, submit a printed copy of a wordprocessing document containing:

      1. Footer
      2. BIG JAVA's Formatting Style by importing UBC's file.
      3. Identification Template
      4. Screen Dump(s)
      5. Print on both sides of a sheet of paper, two pages per side = = four pages per sheet of paper. See Make Hard Copy of Source Code.

TopicAssignments

Chap 19
Sorting
and
Searching

AVI clips of Students Sorting Cups

Horstmann 19 [ppt]

Roedy Green's
Canadian Mind Products

Eck's xSortLab Lab

Woi Ang's Sorting Animations

Duane Jarc's Interactive Visualizations

Big-O Notation [Wikipedia]

Sedgewick:    4   4.1   4.2  

Eck: Arrays, Searching, Sorting

Videotape: Sorting Out Sorting
[Baeker, 1981, ISBN: 1558600302]

Carrano & Savitch:
ppt --> 9  11  12  16 

PRACTICAL TEST: Students must schedule a time with their teacher to demonstrate various sorting algorithms using stacking cups.

BIG JAVA Chapter 19 Demo Source Code

Measuring Selection Sort in Milliseconds:
ArrayUtil.java SelectionSorter.java SelectionSortTester.java
SelectionSortTimer.java StopWatch.java

Measuring Selection Sort in Nanoseconds:
ArrayUtil.java SelectionSorter.java SelectionSortTester.java
SelectionSortTimer.java StopWatch.java

Insertion Sort:
ArrayUtil.java InsertionSorter.java InsertionSortTester.java

Measuring Merge Sort in Milliseconds:
ArrayUtil.java MergeSorter.java MergeSortTester.java
MergeSortTimer.java StopWatch.java

Measuring Merge Sort in Nanoseconds:
ArrayUtil.java MergeSorter.java MergeSortTester.java
MergeSortTimer.java StopWatch.java

Quick Sort (Uses Recursion):
ArrayUtil.java QuickSorter.java QuickSortTester.java

Linear Search:
ArrayUtil.java LinearSearcher.java LinearSearchTester.java

Binary Search:
ArrayUtil.java BinarySearcher.java BinarySearchTester.java

Read about Measuring Time In Java by Roedy Green.
  1. View Horstmann 19 Sorting and Searching Powerpoint Slide Show.

  2. Get an intuitive feeling for sorting generally and then the Insertion Sort and Quick Sort at Sorting Bricks and Sticks on the Berkley MathSite.

  3. View Measuring the Difficulty/Complexity of a Problem web page by Gerry Donaldson

  4. View Tradeoffs, Intuition Analysis, Understanding Big-Oh aka O-Notation Powerpoint Slide Show by Owen Astrachan. Also view the Java source code examples associated with this PowerPoint slide show.


  5. From the 2003 text Data Structures and Abstractions With Java by Frank M. Carrano and Walter Savitch [ISBN 0-13-017489-0], view the following Powerpoint slide shows.


  6. Read the brief Sedgewick 4 Fundamental Abstract Data Types

  7. Read the text and review all examples from Sedgewick 4.1 Analysis of Algorithms

  8. Read the text and review all examples from Sedgewick 4.2 Sorting

  9. A super reference (really an entire university course) is Data Structures and Algorithms by John Morris at the University of Western Australia! The course includes great coloured diagrams and algorithmic animations of sorting and searching algorithms.

  10. Read Eck's Explanation of Arrays
    Read Chapter 8: Arrays from the 4th edition of David Eck's book Introduction to Programming Using Java.

  11. You want to know how to trace and implement the searching and sorting algorithms.

  12. Read about the four sorting algorithm's required by IB's 2000 syllabus by viewing Raksha Vasudevan's Kyell-style tutorial, The 4 Array Sorts Required by IB.

  13. Ask Mr. Donaldson to let you view the 30 minute videotape entitled, "Sorting Out Sorting".
    [Baeker, Ronald M., published by Morgan Kaufman, 1981, ISBN: 1558600302]

  14. Check out xSortLab Lab: Sorting and the Analysis of Algorithms from David Eck's book, The Most Complex Machine: A Survey of Computers and Computing.

  15. Learn to demonstrate each of the six sorting algorithms with the stacking cups. Its fun and, incidentally, an excellent way to visualize and internalize each of the sorting algorithms, and that is our objective! First study the visualization of an algorithm. Then, once you have the hang of it, implement it using a dozen stacking cups.

  16. In the last term of 2002 the first eight students to take Computer Science 201 in Java were examined in their application of sorting algorithms using stacking measuring cups. Judge for yourself as you watch AVI clips of their final tests .. a physical demonstration of each of four different sorting algorithms using a dozen toddler stacking cups.

  17. Students must generate and/or complete trace tables of searching and sorting algorithms.

    Hint To Automatically Generate A Trace Table:

    1. Place an output statement with the heading before the first call to the loop or recursive method that generates the next "pass" of the sorting algorithm.

    2. Place an output statement in the body of the loop or recursive method which generates the next "pass" of the sorting algorithm so it will output the values of each of the variables.

    Check out an example of how to do this taken from an answer key by Gerry Donaldson to Question 16 of Paper 1 of the May, 2002 IB Higher Level final examinations: [WordPerfect file] [pdf file] [WORD file]

  18. Programming Exercises To Be Graded (pp 738-739): P19.2, P19.4, P19.8, P19.10, P19.12, P19.14.

    For each exercise, submit a printed copy of a wordprocessing document containing:

    1. Footer
    2. BIG JAVA's Formatting Style by importing UBC's file.
    3. Identification Template
    4. Screen Dump(s)
    5. HTML Javadoc files including the standard tags @author, @version, @param, @return and the customized tags @invariant, @pre and @post
    6. Print on both sides of a sheet of paper, two pages per side = = four pages per sheet of paper. See Make Hard Copy of Source Code.

  19. There will be three tests for this chapter.

    There will be the usual brief 20 question quiz.

    The quick sort must be reproduced without reference to resources other than the student's mind. Hint: Understand it thoroughly and you will be able to think your way through it.

    Students will physically demonstrate all of the following searching and sorting algorithms using 12 stacking cups.

    • Linear Search
    • Binary Search
    • Bubble Sort
    • Selection Sort
    • Insertion Sort
    • Bucket Sort
    • Quick Sort
    • Merge Sort

Kjell
Tutorials

Graphical User Interface Programming

Bradley Kjell, Central Connecticut State University, Java 5.0 version, January 2006
Kjell GUI 1 Chapter 55  Introduction to GUI Programming
Kjell GUI 2 Chapter 56  JFrames
Kjell GUI 3 Chapter 57  Adding Buttons to a Frame
Kjell GUI 4 Chapter 59 Buttons and Action Events Exercises 1-6    
Kjell GUI 5 Chapter 60  JTextFields and JLabels Exercises 1-4    
Kjell GUI 6 Chapter 61  GUI Applications Exercises 1-2    
Kjell GUI 7 Chapter 62  JPanel and BoxLayout  
Kjell GUI 8 Chapter 63  Radio Buttons and BorderLayout Exercises 1-3    
Kjell GUI 9 Chapter 64  JSliders and Change Events Exercise 1    

Review GUI
With
Yakov Fain

Java GUI Review:   Fain's Tutorials

Yakov Fain writes an online series for the Java Development Journal [JDJ] on learning to program with Java for the Java Development Journal. Review his two excellent columns on Java GUI


[Counter On Strike [Home of Gerry Donaldson's Com Sci Gate]
[Gerry Donaldson's Email Address]
gerry@comscigate.com
[EFC Blue Ribbon - Free Speech Online]

On the Internet Since March 9, 1996    URL:   http://www.comscigate.com    Last Revised:   June 2, 2008.