ACSL Handout: Boolean Algebra 
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 programmes that allow us to practice Boolean logic are:
Check out former student web pages on this topic:
- Boolean Logic
by Lisa Chen (2002).
- Boolean Logic by Brian Lau (2003).
- 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:
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.
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.
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].
|
|
ACSL Handout: Bit-String Flicking 
Bit and Shift Operations
| Operator | Logical | Bitwise |
| NOT | ! | ~ |
| AND | & && | & |
| OR | | | | | | |
| XOR | ^ |
^
 |
| shift left | Not Applicable | << |
| arithmetic shift right | Not Applicable | >> |
| bitwise shift right | Not Applicable | >>> |
Check out this TopCoder article that applies bit-wise operators to challenging computing
programming contest problems:
A bit of fun: fun with bits
|
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:
- Immediate Operands and Bitwise Logic
- 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");
}
}
|
|
ACSL Handout: Computer Number Systems 
Computer Java Program Example: Rolodex.java
Rolodex.in
Strategies and Tactics For Reading and Processing Data From A Text File
Before doing anything else, Get ready to code by first launching Java's current
API.
Ideally, you should download and install Java's current API to your work station
rather than relying upon Internet access.
Java's API
is the official "Java Dictionary". It is the single most important reference that
there is for working with the Java programming language. Consult it often!!
You should immediately familiarize yourself with methods of the following classes.
Use the most current stable version of Java and your IDE.
Java is a moving target. There were huge changes from Java 1.4 to Java 1.5 (aka Java 5.0) in generics (where
structures such as an ArrayList can handle "generic" objects of many different types), autoboxing and
unboxing (where Java automatically converts between primitive and wrapper types), an enhanced for loop
(which automatically and safely iterates over collections and arrays), et cetera.
Failure to use current tools explains why code written that uses those tools does not work!
Duh!! Personally, I could throw quite the party if I had a nickel for every "error message" thrown
after I tried to run code using current features with legacy versions of a language and/or IDE.
In Eclipse, set the IDE to use a current Java JDK (Java Development Kit) version with:
Window → Preferences... → Expand "Java" → Compiler
→ Use the drop down menu to set the "Compiler compliance level".
At the time of writing this point (February 2008) the most recent version of Java is 6.0.
The most recent version of Eclipse is 3.3.1.
Master the use of the Eclipse Debugger.
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.
| Function | Button | Hot Keys | Purpose |
| 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. |
Use knowledge of the common behaviours (methods) that many classes share.
All Java classes inherit all methods of the
Object class, which means that all Java objects have the following
(and other) methods in addition to their own inherited methods.
A method inherited is a method realized.
equals(Object obj) indicates "true or false" that the
content of some other object is "equal to" this one.
Mathematical equality "==" is not used because it compares values of
addresses. Two otherwise identical objects in terms of their
values may be located in different parts of memory and therefore have different addresses.
The programmer may override default criteria for comparing two objects.
toString() returns a string representation of the object.
The programmer may override the default way of representing an object as a string.
hashCode() usually (but not always) produces distinct integer results
for two objects that are unequal according to the
equals(Object obj) equals(java.lang.Object) method.
Many classes have "getter" and "setter" methods.
The eight primitive types each have a corresponding "wrapper class" with methods
that act upon or express the value of the primitive. Example methods are:
returns a new primitive initialised to the value represented by a specified
String [ eg: double price = Double.parseDouble("123.45") ].
returns a string representation of the primitive
[ eg. String myAge = num.toString( ) ].
tests whether a character is a letter or digit or lowercase, etc.
[ eg. Character.isLetter('5') == false ].
The eight primitives and their corresponding wrapper classes are:
|
Display line numbers:
Window → Preferences... → General → Editors → Test Editors
→ Check the box "Show line numbers" → OK.
Import a XML file that sets code style format to your preferred style:
Select (highlight) the project → Window → Preferences... → Expand (click "+" sign)
"Java" → Expand "Code Style" → Formatter → Import... → Locate XML file
→ Open → OK.
The file CPSC211CodeFormat.xml forces
conformity to a style of source code advocated by Cay Horstmann in his textbook Big Java.
Force your preferred format often with:
Right Mouse Click → Source → Format.
Use "baby steps" to break up big problems into small problems. It is emphatically
easier to solve small problems than large problems. Remember the "KISS Principle".
KISS =
Keep It
Simple Stupid.
When a task becomes complex, solve it in it's own method.
Close all open editor windows to avoid accidentally editing code of an incorrect file:
File → Close all.
Also close all other (non-editor) Eclipse windows that you don't intend to use with the current
project, thus reducing distractions and maximizing the real estate used by windows that you do use.
You can always reopen any window in a given perspective after: Window →
Show View → whatever.
An Example of Reading and Processing Data From A Text File
Create the data base in a text file:
Rolodex.in :
Select the project → File → New → File →
"Rolodex.in" → Finish.
Gerry Donaldson 123_Anywhere_Street Calgary AB 4032899241 456.26
John Blow 987_Crescent Cranbrook BC 6045559875 98273.4
Jane Doe 89_DeerHunt_Way Huntsville SK 3063968148 29.44
|
 |
Your program will bomb if it does not find a data file to read. If you get error messages
like the following, ensure that your data file is located in the
project directory outside of any package directory!!
Drag and drop the data file into the selected (blue) project directory if need be.
Exception in thread "main" java.io.FileNotFoundException: Rolodex.in
(The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileInputStream.(Unknown Source)
at java.io.FileReader.(Unknown Source)
at Rolodex.main(Rolodex.java:11)
|
|
Create a class: Rolodex.java
Create a java.io.FileReader object which reads text data as a stream
of characters.
FileReader charStream = new FileReader ( "Rolodex.in") ;
Create a java.io.BufferedReader object to read the character-input stream
(spooled into a buffer of memory by the
FileReader object), buffering characters so as to provide for the efficient
reading of characters, arrays, and lines.
BufferedReader in = new BufferedReader( charStream ) ;
Instead of giving the FileReader object a separate identifier (Example: charStream)
as above, it is customary to immediately pass the
FileReader object (charStream) anonymously as a parameter to the
constructor of the BufferedReader object.
|
BufferedReader in = new BufferedReader(
new FileReader ( "Rolodex.in") ) ;
|
The BufferedReader class method
readLine( ) captures strings of characters, line by line, passing
each string onto a String object, "line".
String line = in.readLine() ;
|
Use a while loop to continuously read
BufferedReader objects of strings to the end of the file. Determine that
the end of file has been reached when the address of a string "line" == null. Two critical
decisions must be followed.
Prime the while loop* by reading the first
string of data BEFORE reaching the while loop.
The test to enter the while loop is whether the String object "line" continues to
contain data. After the last data object has been read, line == null,
thus it is false that " line != null ", thus execution proceeds to the first
instruction coming AFTER the end of the body of the while loop.
*
"Prime the while loop" is a metaphor that refers to the need to prime (place water in)
an outdoor water pump to create a partial vacuum before water will start flowing.
Once there is some water in the water pump, the flow ("processing") of the water
proceeds until there is no more water in the pump. Similarly, the while loop continues
to process data until there is no more data read from the buffered stream of characters.
.
Continuously read the next String data object just before the END of the while loop
so that it may be immediately tested for "line != null" to determine whether there
continues to be data that can be processed by re-entering the while loop.
String line = in.readLine() ;
while ( line != null )
{
// TODO: Process line
line = in.readLine() ;
}
|
Pass each string of data into a method for the sole purpose of storing all the data
as records in an java.util.ArrayList<Element> object.
placeRecordInArrayList ( line ) ;
|
Create an inner class that will act as a "blueprint" for records of fields of each
string of data.
Declare the record class to be static so that it may be used without having to create
native record objects.
static private class Record
{
public String field1 ;
public long filed2 ;
public double field3 ;
}
|
Create a java.util.ArrayList<Element> object, each cell of which will
contain a separate record of the data read from the text file data base.
The ArrayList<Element> class implements operations for processing
the ArrayList<Element> list of data objects.
Note that you must use a Java compiler of version 1.5 or later to support an ArrayList
that may contain "generic" types of data objects, such as the records of data.
Ensure a sufficiently recent compiler "level" of Java:
Window → Preferences... → Expand "Java" → Compiler →
Set the "Compiler compliance level" to 1.5 (5.0) or higher. → OK.
static private ArrayList<Record> list = new ArrayList<Record>() ;
|
Create a java.util.StringTokenizer object which breaks the string object into
"tokens" of substrings of the string that was used to create the StringTokenizer object ...
the string containing a record of data.
The white space may be a single character or sequence of characters.
Use a while loop to determine that there continues to be yet a "next" token. So long as
there continues to be yet another token, enter the loop and assign each token to a field of
the string "record". (Each string object is deemed to contain a record of fields of data.)
Build a temporary record within each loop by assigning each token to a separate
field of the data record.
After assigning a value to each field of the temporary record, add the temporary record
to the ArrayList<Element> object.
StringTokenizer st = new StringTokenizer (record) ;
Record temp = new Record() ;
while ( st.hasMoreTokens() )
{
temp.var1 = st.nextToken() ;
temp.var2 = Long.parseLong( st.nextToken() )
temp.var3 = Double.parseDouble( st.nextToken() ) ;
list.add(temp);
}
|
Process data using loops,
ArrayList<Element> methods, and methods of classes that
manipulate strings and characters.
Kjell's Tutorial, ArrayLists and Iterators, in an excellent introduction to Java's
ArrayList class.
|