This web page contains the java example programs that will be covered in class. A couple of new basic programs will be added each semester. One new Civil Engineering Application Program will added each semester. Web page in progress!!!
To view the java programs that require graphics, you will need a browser that supports Java (e.g., Safari, Microsoft IE 7 and Netscape with the appropriate plug-ins).
JAVA BASICS |
PROGRAM OUTPUT AND SOURCE CODE |
||||||||||||||||||||
"Peace on Earth" Application with Text Output.
Java application programs are written, compiled and run locally on your computer.
Our first version of Peace.java is a small standalone program that simply prints
Peace on Earth! to your console (computer screen).
For a detailed description of this program, see Sections 18.2.1 - 18.2.8 of
the class text Austin/Chancogne.
|
Standalone Program:
Peace.java Program Output: output |
||||||||||||||||||||
"Peace on Earth" Java Applet Program.
An applet is simply a Java miniprogram that runs within a web browser or viewer.
As such, it is usually spectified in an html file.
Peace2.html and Peace2.java are source files for the applet counterpart of Peace.java.
This program is explained in Section 18.3 of Austin/Chancogne.
Java application programs and java applet programs are both compiled into executable bytecodes. But, then, an applet bytecode can be downloaded over the network and run locally on any computer that has a java virtual machine (JVM). To facilitate this process, most modern web browsers contain a JVM. You can also execute an applet with the appletviewer program, i.e., appletviewer Peace2.html
The appletviewer will ignore all of the html markup except those
tags directly conneted to the display and execution of the applet.
|
Run Applet:
Peace2.html Applet Program: Peace2.java |
||||||||||||||||||||
"Peace on Earth" Application with Graphics.
Although graphics will not be a central part of this course,
Java provides very strong support for the development
of two- and three-dimensional graphical interfaces.
Our third version of Peace on Earth! displays the message as a character string on a graphical component.
![]() Figure 1. Screendump of Peace on Earth! graphics frame.
The graphical component is an object of type JComponent,
and it is embedded inside a frame (an object of type JFrame).
|
Standalone Program:
PeaceApplication1.java PeaceComponent1.java |
||||||||||||||||||||
"Peace on Earth" Application with Graphics and Mouse Interaction.
Our last version of Peace on Earth! displays a textual message on a graphical component.
It also provides mechanisms for a user to grab and move the text about the component.
See Figure 2.
![]() Figure 2. Screendump of Peace on Earth! graphics frame.
This new capability is enabled by attaching a mouse-motion listener to
the graphical component. Whenever a mouse motion event occurs within
the component, the program will be notified, and the text will be
drawn in its new location.
|
Standalone Program:
PeaceApplication2.java PeaceComponent2.java |
||||||||||||||||||||
Basic Data Types, Arithmetic, and Math Functions.
Java has eight basic data types -- for details see the FAQ web page -- that
cover integers, floating-point numbers, booleans and characters.
This program demonstrates declaration of Java's most commonly used
basic data types (int, float, double, boolean),
their arithmetics and use of the math functions.
|
Code: GettingStarted.java Program output |
||||||||||||||||||||
Formatting of Basic Data Types.
One of the first things you might want to do is print out a table of
number in a tidy format. In the latest versions of Java, the most
straight forward way of doing this is with the printf() method.
This program demonstrates how output of the basic data types (int, float, double), can be easily formatted through use of the System.out.printf() method. A summary of very basic formatting specifications is as follows:
Table 1. System.out.printf() formatting specifications.
For more details, see Sections 3.4.7 and 12.2 in Austin/Chancogne.
|
Code: DemoFormat.java Program output |
||||||||||||||||||||
Numerical Errors.
This program illustrates Java's capability in
handling error conditions related to:
The last part of the program contains a looping contruct to
evaluate a function y(x) that is designed to generate all three error conditions.
|
Code:
NumericalErrorConditions.java Program output |
||||||||||||||||||||
Using a Scanner to Read Input from the Keyboard.
One of the new features in Java 1.5 is the class Scanner,
which provides support for parsing of primitive
data types (e.g., int, float and double) and strings.
This program demonstrate use of a Scanner for input of text, integers,
and floating-point numbers from the keyboard (i.e., System.in).
|
Code: Scanner1.java Program output |
||||||||||||||||||||
Branching Constructs.
A branching contruct -- also known as a selection construct -- allows for
the pathway of execution in a Java program to be controled by the results
of conditional statements assembled from expressions involving relational
and logical operators.
This program demonstrates wht use of if() branching contructs, if-else constructs, and branching with else-if clauses. Conditional statements can be very simple, or complicated, involving multiple relational and logical operators.
For more info, see Section 18.7.1 of Austin/Chancogne.
Branching constructs in Java are very similar to those in C.
Hence, also see Section 6.3 of the C tutorial in Austin/Chancogne.
|
Code:
DemoBranching.java Program output |
||||||||||||||||||||
Switch Statements.
Sometimes a program is required
to evaluated multiple relational/logical expressions in the
computation of a multi-way decision making pathway.
This can be done with a hierarchy of if and if-else statements.
However, often, a better solution is to use a switch statement.
A switch statement begins with an expression whose type is either an int or char or byte. As of Java 5, Enums are also allowed. This expression is followed by a block of code in curly braces that contains entry points corresponding to the possible values for the expression.
This program contains a few straight forward implementation of
the switch statement.
|
Code: DemoSwitch.java Program output |
||||||||||||||||||||
Evaluation of Logical Expressions.
The purpose of logic is to enable the construction of
valid arguments which satisfy the basic principle
"If all of the premises are true, then the conclusion must be true."
In order for this process to be clearly defined and reliable,
the participating logical operations must obey a set of consistent properties.
In logic we use variables to represent propositions (or premises). Java allows for the representation of these propositions as boolean variables; they can take only one of two values -- true (T) or false (F). For example, the statement boolean p = (3 >= 2); sets up a boolean variable p whose value evaluates to true (T). Any logical statement which contains a finite number of logical variables (which of course covers any problem we have to deal with) can be analyzed using a table which lists all possible values of the variables: a "truth table". Since each variable can take only two values, a statement with "n" variables requires a table with 2n rows.
Table 2. A simple truth table.
Table 2 shows, for example, a simple truth table for two propositions
represented by p and q.
The notation p ^ q means p AND q.
The notation p v q means p OR q.
Notice that p AND q is true if an only if both p and q are true.
|
Code: TruthTable.java Program output |
||||||||||||||||||||
Looping Constructs.
Looping constructs enable a Java program to iterate (or loop) over one or
more statements of code while a conditional statement evaluates to true.
This program demostrates use of "while" and "for" looping constructs, and nested looping constructs...
See Section 18.7.2 of Austin/Chancogne.
Looping constructs in Java are almost identical to those in C.
Hence, also see Section 6.4 in the C tutorial.
|
Code: DemoLoops.java Program output |
||||||||||||||||||||
Checking input scanned from the Keyboard.
This program demonstrates use of a Scanner for input of text, integers,
and floating-point numbers from the keyboard (i.e., System.in).
However, unlike Scanner1.java, this version includes support for
repeating a prompt until the correct type of data is supplied.
This expanded level of functionality is acheived by putting the scanning
operation inside a while loop -- looping operations continue until
the correct type of data is provided.
|
Code: Scanner2.java Program output |
||||||||||||||||||||
Polymorphism of Methods.
A method is a named sequence of Java statements that can be invoked
by other Java code. When the method is invoked it is passed
zero or more values known as arguments. The method will make a computation
and then return either nothing, or a single value. Thus, the signature
of a method is defined by three parts:
Polymorphism, on the other hand, is the capability of an action to do different things based on the details of the object that is being acted upon. This is the third basic principle of object oriented programming.
This program demonstrates "polymorphism of methods" in Java.
The program contains three versions of a method called doSomething().
However, each implementation is unique in its argument specfications.
The test program exercises these methods and shows how Java automatically
determines which implementation to call, based upon the details of argument usage.
|
Code: DemoPolymorphism.java Program output |
||||||||||||||||||||
One-Dimensional Arrays.
In Java an array is simply a sequence of numbered items of the same type.
You can create arrays of the primitive data types (e.g., characters, ints, floats,
doubles) and instances of a class (e.g., an array of circle objects).
This program demonstrates the declaration and usage of one-dimensional arrays of numbers and Strings, including the printing contents of a large array in a tidy format. Figure 3 shows, for example,
![]() Figure 3. Declaration and layout of memory for a one-dimensional array of ints.
the declaration for an array of five integers called iaA,
and the corresponding layout of memory.
Notice that the array element indices range from iaA [0] through iaA [4].
|
Code: DemoArrays1.java Program output |
||||||||||||||||||||
Two-Dimensional Arrays.
Two-dimensional arrays are stored as arrays of arrays.
Figure 4 shows, for example,
![]() Figure 4. Declaration and layout of memory for a two-dimensional array of ints. the declaration for a five-by-two array of integers called iaaA, and the corresponding layout of memory. In the first level of indirection, the array element indices range from iaaA [0] through iaaA [4]. Each of these elements is a reference to a row in the matrix. Then, the array elements themelves are referenced by iaaA[0][0] .. through .. iaaA[4][1]. This program demonstrates the declaration and usage of two-dimensional arrays of numbers and Strings.
Java also supports ragged arrays; that is, two-dimensional arrays where
the length of each row may be different. For matrices that are symmetric
and/or are only sparsely populated with non-zero elements,
use of ragged array mechanisms can lead significant savings in required storage.
|
Code: DemoArrays2.java Program output |
||||||||||||||||||||
Strings.
Java represents strings of characters and text with the builtin class String (actually, it's java.lang.String).
Unlike the eight basic data types, String is a class from which objects can be
created and methods can be invoked. String objects are immutable, meaning
that once a String object has been created, there is no way to modify the
string of text it represents. Thus, each method that operates on a string typically
returns a new String object that holds the modified string.
This program demonstrates the use of "character strings," arrays of character strings, and conversion of strings to numerical values of type integer, float and double.
A few examples of these methods and their usage can be found in Section 18.9.4
of Austin/Chancogne.
|
Code: DemoStrings.java Program output |
||||||||||||||||||||
Basic Enumerated Data Type.
An enumerated type is a type whose instances describe a finite set of values.
Typically, an enumerated type is used when the most
important information is the existence of the value.
A static enumerated type is an enumerated type whose set of possible values is fixed, and does not vary at run time. For example, the concept of days of the week includes the set:
Monday, Tuesday, Wednesday, Thursday, Friday, Saturday. Not only are these seven values the only possible values for the concept, but there will never be another possible value, and none of these values will ever become obsolete.
This program demonstrates how an enumerated data type for days of the week
can be used in conjuction with selection implemented via a switch statement.
|
Code:
DayOfWeek.java WorkSchedule.java Program output |
||||||||||||||||||||
Read Text from Console.
This program demonstrates the process of reading lines of text from the terminal (Console)
window and storing the input in a character string inLine.
The program loops for more input until either "exit" or "quit" is
typed at the terminal prompt.
Note: In recent semesters students have written programs with
equivalent functionality by using a Scanner, a feature now supported by Java 5.
|
Code: ReadTextFromConsole.java Program output |
||||||||||||||||||||
Read Text from File.
This program demonstrates the process of reading
lines of text (numbers and strings) from a file data.txt:
4 Red1 25 18 true Red2 25 -23 false Blue 03 123 true Green 13 03 falseThe first line contains the number of records to be read in -- in this case 4. Then the program systematically reads each line of input, breaks the input into tokens, and then converts the character string representations to the appropriate datatypes (e.g., String, double, boolean). |
Code: TestIOFile.java , data.txt Program output |
||||||||||||||||||||
Read Text from File located at a Remote Location.
This program demonstrates the process of reading lines of
text (numbers and strings) from the file:
4 Red1 25 18 true Red2 25 -23 false Blue 03 123 true Green 13 03 false located at: http://www.isr.umd.edu/~austin/ence200.d/data.d/data.txt |
Code:
TestIOReadFromURL.java , Program output |
||||||||||||||||||||
Passing Data to Methods.
Like C, Java employs a call-by-value mechanism to pass data to methods.
Notice how the value variable "i" remains unchanged in main(),
even after it has apparently been changed in the method TryChange().
This behavior is due to the fact that a copy of the variable value is
passed to a method -- not its address!!!!
|
Code: DemoTryChange.java Program output |
||||||||||||||||||||
SIMPLE APPLICATIONS
Here are a few simple application programs. In most cases, they
are solutions to problems in the "java programming exercises" handout.
|
|||||||||||||||||||||
Volume/Surface Area of a Sphere.
This program prompts a user at the keyboard for the radius of a sphere,
checks that the input value is greater than or equal to zero,
and then computes and prints the sphere volume.
From a software perspective, this program demonstrates use of functions and constants in the Math library, and simple decision making with an if() branching construct. Input from the keyboard is handled by the method keyboardInput() and a character string sLine. Equivalent functionality can be achieved with the method getTextFromConsole().
Note.
In recent semesters some students have used the Scanner class to read
and process numbers typed at the keyboard.
|
Code: Sphere.java Program output |
||||||||||||||||||||
Compute and Print Factorials.
This program demonstrates:
(1) the use of a simple looping construct to compute the factorial of an integer n!, and
(2) evaluation of arithmetic expressions involving factorials.
|
Code: Factorial.java Program output |
||||||||||||||||||||
Roots of a Quadratic Equation.
This program prompts a user for coefficients "a" "b" and "c" in a quadratic
equation, prints the equation in symbolic form, and then computes and prints
the roots of the quadratic equation.
Note. Notice use of getTextFromConsole() as a replacement for keyboardInput().
|
Code: Quadratic.java Program output |
||||||||||||||||||||
Economics: Single Payment Interest Computation.
This program uses a "for looping" construct to compute the
compound interest for an investment lasting a number of years.
|
Code: CompoundInterest.java Program output |
||||||||||||||||||||
Water Flow Rate Needed for Fire Fighting.
This program computes the water flow rate needed for fire fighting in a metropolitan area.
The formula for flow rate is written in terms of population in 1000's. Hence, for example,
a formula argument value of "5" would be used for a small city of population 5,000.
From a software standpoint, this program demonstrates
use of the if()-elseif()-else branching construct.
|
Code: WaterFlow.java Program output |
||||||||||||||||||||
Wind Forces on a Yacht Sail.
This program computes and prints the force on a yacht
sail due to gusts of wind. Each gust lasts one second.
Gusts of wind repeat for three seconds.
From a software standpoint, this program demonstrates use of the modulo arithmetic operator.
The software implementation is simplified by organizing the code into methods: main()
and windForce(). Notice how windForce accepts one argument of type double,
and returns the wind force as a double.
|
Code: WindForce.java Program output |
||||||||||||||||||||
Tidy Table.
This program formats columns of numbers into a tidy table.
The details of the methods are rather complicated, but are nonetheless very useful.
See, for example, the "data matrix" application below.
You will need these routines if you are working with Java 1.3/1.4.
In Java 1.5, much of the same functionality can be
achieved with the System.out.printf(...) method.
|
Code:
TidyTable.java Program: output |
||||||||||||||||||||
WORKING WITH OBJECTS
So far, the only objects we have seen are those associated with character strings and arrays.
In this section we see how to create objects having user-defined data and methods.
|
|||||||||||||||||||||
Circle Objects.
The Circle class is a specification for circle objects defined by the (x,y) coordinate
of their center point and their radius.
![]() Figure 5. Data and methods in the Circle class. Two constructor methods are provided for the instantiation of circle objects. The first constructor simply creates a circle object with centerpoint (0,0) and radius 0. The second constructor allows for the specification of circles with centerpoint (dX,dY) and radius (dRadius). The method Area() computes the circle area and returns the result as a type double. The toString() method assembles and returns a String representation of the circle object. The main() method exercises methods in the Circle class.
For a more detailed writeup, see Section 18.8 of Austin/Chancogne.
|
Code: Circle.java Program output |
||||||||||||||||||||
Colored Circle Objects.
The Colored Circle class is a specification for colored circle objects.
![]() Figure 6. Relationship between the ColoredCircle and Circle classes. The implementation extends the Circle class and adds color for individual colored circle objects.
For a more detailed writeup, see Section 18.8.7 of Austin/Chancogne.
|
Code:
ColoredCircle.java Program output |
||||||||||||||||||||
Complex Number Arithmetic.
This library specifies complex number objects and complex number arithmetic.
A detailed desription of the formulae for complex number arithmetic
may be found in the "Numerical Recipies in C" text.
Code in the main() method systematically exercises each of the opertors for
complex number arithmetic.
|
Code: Complex.java Program output |
||||||||||||||||||||
Simple Data Array.
This program implements a simple data array; that is,
a class that stores a one-dimensional array of floating-point numbers and its name,
and methods to compute basic statistics (e.g., minimum, maximum
and average array element values) and arithmetic operations (e.g., sum
and difference of two data arrays).
Figure 7 shows a typical statement for setting up a data array object, followed by the layout of memory that is generated.
![]() Figure 7. DataArray object creation and layout of memory. Notice that the array element values are automatically set to zero. Individual array elements can be initialized with statements of the type: A.setElement ( 0, 1.0 ); A.setElement ( 1, 2.0 ); and so forth.
Version 2 (April 2009): The method readData() has been added. Arrays
can now be read from a file located locally on your computer.
File format: The first line contains the number of elements in the array.
Then, one array element is located on each line.
See, for example, the layout of data in
sensor1.txt .
|
Code:
DataArray.java sensor1.txt Program output |
||||||||||||||||||||
Line Segment Objects.
A line segment is a line of finite length.
For a given line segment, there are lots of questions an engineer
might want to ask? For example, what is its length and orientation
with resepect to the x- and y- axes?
How far is the line segment from a particular point?
Does the line segment intersect another line segment?
From a computational standpoint,
some of these questions are easy to answer. And some aren't!
![]() Figure 8. Model and class diagram for line segments.
The adjacent figure shows that line segments can be modeled by
their two endpoints (i.e., with the classes Vector, Node and LineSegment).
|
Code: LineSegment.java , Node.java , Vector.java Program output |
||||||||||||||||||||
Triangle Objects.
The adjacent figure shows how triangles can be modeled
using Vector, Node, Edge and Triangle classes.
![]() Figure 9. Model and class diagram for triangles.
The class Vector models two dimensional vectors
characterised by (x,y) coordinate pairs.
The class Node extends Vector. It adds a name.
An edge line segment is characterised by its two "node" end points
(i.e., The class Edge uses instances of class Node).
Finally, the class Triangle uses three instances of class Node
and three instances of class Edge.
|
Code: Triangle.java , Edge.java , Node.java , Vector.java Program output |
||||||||||||||||||||
Inheritance Mechanisms in a Simple Class Hierarchy.
This program demonstrates the various capabilities of
"inheritance mechanisms" in a simple class hierarchy.
|
Program output Code: Planet.java |
||||||||||||||||||||
Encapsulation, Data Hiding, and Public Interfaces.
Encapsulation involves separating the interface of a class from its implementation.
There are two key benefits in the use of encapsulation:
In this example we rework the colored circle application to implement encapsulation.
![]() Figure 10. Relationship among Circle, ColoredCircle, and test classes. As illustrated in Figure 10, this involves:
|
Program: output Code: Circle.java ColoredCircle.java TestCircle.java TestColoredCircle.java |
||||||||||||||||||||
Typesafe Enumerated Data Types.
|
Code:
ReadTextFromConsole.java Program output |
||||||||||||||||||||
WORKING WITH ABSTRACT CLASSES AND INTERFACE CLASSES | |||||||||||||||||||||
Abstract Classes.
An abstract class is a class that is declared abstract.
It may or may not include abstract methods.
Abstract classes cannot be instantiated (i.e., you cannot create an
object from an abstract class),
but they can be subclassed.
When an abstract class is subclassed,
the subclass usually provides implementations for all
of the abstract methods in its parent class.
This program demonstrates the use of an abstract Shape class that contains a reference to a location and three methods: toString(), area() and perimeter(). The abstract class is subclassed by Circle and Rectangle classes. The system is exercised by a test class TestShape. The class hierarchy is as follows:
![]() Figure 11. Model and class diagram for hierarchy of shapes. The files before and after program compilation are: Before After =============================================================== TestShape.java TestShape.java TestShape.class Shape.java Shape.java Shape.class Location.java Location.java Location.class Circle.java Circle.java Circle.class Rectangle.java Rectangle.java Rectangle.class =============================================================== |
Code:
TestShape.java Shape.java Location.java Circle.java Rectangle.java Program: output |
||||||||||||||||||||
Interfaces 1.
Objects are defined by their interaction with the outside world through
the methods (and possibly also constants) that they expose.
Interfaces provide a formal contract between the class and the outside world which, in turn,
will be enforced at build time by the compiler.
If your class claims to implement an interface,
all of the methods defined by that interface
must appear in its source code before the class will successfully compile.
As we will soon see in the example below,
interfaces also allow collections of objects to be manipulated independently
of the details of their representation.
Here we present code for a simple interface that represents farm workers, that is, the farmer and the dog and horse that help the farmer.
![]() Figure 12. Class diagram for implementation and use of a farm workers interface. Figure 12 shows a class diagram for the implementation of farm worker entities. WorkingDog and WorkingHorse are extensions of Dog and Horse respectively, which in turn, are extensions of Animal. The Farmer is an extension of Person. Workers is simply an abstract class that defines an interface, i.e., public interface Working { public abstract void hours (); } The interface is implemented by using the keyword "implements" in the class declaration, e.g., public class Farmer implements Working { .... This declaration sets up a contract that guarantees the Farmer class will provide a concrete implementation for the method hours(). The class FarmWorkers builds a model of the working entities on the farm. (i.e., Farmer, WorkingDog and WorkingHorse objects). The key benefit in using interfaces is that they allow collections of objects to be manipulated independently of the details of their representation. Hence, instead of writing code that looks like: Farmer mac = new Farmer (...); WorkingDog max = new WorkingDog (...); WorkingHorse silver = new WorkingHorse (...); we can treat this group of objects as a set of Working entities, i.e., Working mac = new Farmer (...); Working max = new WorkingDog (...); Working silver = new WorkingHorse (...); Methods and algorithms can be defined in terms of all "Working" entities, independent of the lower-level details of implementation. The files before and after program compilation are: Before After ================================================================== FarmWorkers.java FarmWorkers.java FarmWorkers.class Animal.java Animal.java Animal.class Dog.java Dog.java Dog.class Farmer.java Farmer.java Farmer.class Horse.java Horse.java Horse.class Person.java Person.java Person.class Working.java Working.java Working.class WorkingDog.java WorkingDog.java WorkingDog.class WorkingHorse.java WorkingHorse.java WorkingHorse.class =================================================================== |
Code:
FarmWorkers.java Animal.java Dog.java Farmer.java Horse.java Person.java Working.java WorkingDog.java WorkingHorse.java Program: output |
||||||||||||||||||||
WORKING WITH JAVA COLLECTIONS
The Java Collections framework is a set of utility classes and interfaces (located in the java.util package) for working with collections of objects. The framework includes implementation of four interfaces:
Customized implementations of classes are provided for each interface. For example, the List interface may be implemented as an ArrayList or a Linked List.
|
|||||||||||||||||||||
Array List1.
This program demostrates the use of the arraylist construct to create
lists of "strings" and lists of edges and nodes in a polygon.
|
Code: ArrayTest1.java Edge.java Node.java Vector.java Program output |
||||||||||||||||||||
Array List2.
This program uses the arraylist construct to create a list of triangle objects.
Each triangle contains references to three edge and three nodal point objects.
|
Code: ArrayTest2.java Triangle.java Edge.java Node.java Vector.java Program output |
||||||||||||||||||||
Array List3.
This program demonstrates more of the advanced features of array lists,
including the ability to store more than one object type,
retrieve the position of an object having a certain name,
retrieve neighboring -- next and previous -- objects.
|
Code:
ArrayListExample.java Program output |
||||||||||||||||||||
![]() In simple terms, Figure 13 says:
![]()
Figure 13.
UML class diagram for relationships among Person, FamilyMember, Relatives is a generalized (or abstract) concept for the set of family members that fullfil the roles of father, mother, spouse, children and siblings. Each person object is instantiated with the relevant name and date of birth. Then the objects are added to an array list and printed by walking along the list. Notice how the toString() method in Person is used to print the abbreviated details of a person's credentials.
Finally, the person objects are ordered according to their age --
from youngest to oldest. Because an arraylist is a Collection,
we can use the sort() method in Collections to take care of the details.
All that we have to provide is a method to compare relative age
of two person objects. These details can be found in Family.java.
|
Code:
Person.java
Family.java
Program output |
||||||||||||||||||||
Symbol Table.
A symbol table is a data type that associates a value with a key.
Users store (put) an entry by specifying the key-value pair.
They they can retrieve (get) a value corresponding to a particular key.
While the key is always assumed to be a String,
the value can be any Object.
When two inputs hash to the same key, then items are chained into a linked list, e.g.,
![]() Figure 14. Layout of memory in a hash table. Here is a very simple example. The fragment of code: SymbolTable st = new SymbolTable(); st.put( "mark", "acura" ); st.put( "dianne", "bmw" ); stores two entries in the symbol table, namely, that "mark drives an acura" and "dianne drives a bmw." To retrieve these records from the symbol table, we write something like: String s = "mark" System.out.println ( s + " drives a " + st.get(s) ); String t = "dianne" System.out.println ( t + " drives a " + st.get(t) ); The example code creates a series of MetroStation objects, which are then stored in the symbol table.
Then an array of "metro station names" are defined for
the red and green lines. The corresponding metro station
objects are retrieved from the symbol table, and
the "line" attribute is added to the metro station object description.
Some metro stations will service more than one metro line.
|
Code:
AdjList.java Edge.java MetroStation.java Node.java SymbolTable.java Track.java Vector.java Program output |
||||||||||||||||||||
WORKING WITH SOFTWARE FACTORIES | |||||||||||||||||||||
A Simple Factory.
Here we present code for a simple factory .....
|
Code: ... Program ... |
||||||||||||||||||||
A Simplified Component Factory.
Here we present code for a factory of components that can be
connected via ports and relationships.
|
Code: ... Program ... |
||||||||||||||||||||
Abstract Factory Pattern.
An abstract factory pattern .....
![]() Figure 15. Relationship among concrete and interface classes in an abstract factory setup.
|
Code: ... Program ... |
||||||||||||||||||||
WORKING WITH TIME | |||||||||||||||||||||
Working with Dates and Calendars.
Java provides facilities for working with dates and calendars.
Relevant concerns include formatting of output (e.g., the format for writing
dates in the US is different than in Australia, NZ and England),
comparison of dates, and working with time zones.
This example creates and prints date objects in a variety of formats.
It then shows how dates can be compared and incorporated into if-else statements.
|
Code: DateExample.java Program output |
||||||||||||||||||||
Tasks and Task Managers.
Here we present code for analysis of time-dependent tasks ....
|
Code: ... Program ... |
||||||||||||||||||||
Clocks.
Here we present code for a simple clock applicatio ....
|
Code: clock code ... Program ... |
||||||||||||||||||||
StopWatch.
Here we present code for a simple stop watch ...
|
Code: ... Program ... |
||||||||||||||||||||
Model of Class Teaching and Student Enrollment.
In this example we assemble a simple model of class teaching
and student enrollment.
|
Program ... Code: .... |
||||||||||||||||||||
Threaded Model of Class Teaching and Student Enrollment.
In this model, classes and students are modeled as ensembles
of concurrent processes (threads).
|
Program ... Code: .... |
||||||||||||||||||||
BASIC JAVA GRAPHICS WITH SWING | |||||||||||||||||||||
Simple Swing Application.
A simple Swing applet/application to demonstrate writing
a text string to a label. Notice that this program can be run as both an
applet and standalone Java program.
|
Run Program Code: HelloSwing.java |
||||||||||||||||||||
Canvas and Panel Containing Buttons.
The program creates a simple GUI containing a canvas and a panel with three buttons
labeled "Clear," "Squares" and "Circles".
The first button clears the graphics screen -- that is, paints the canvas white.
The second and third buttons would be used to draw squares and circles on the
canvas ... to keep the program short, this functionality has not been implemented.
All of the source code is contained within a single file DemoGUI.java. The files before and after compilation are as follows: Before Compilatioon After Compilation =============================================================== DemoGUI.html DemoGUI.html DemoGUI.java DemoGUI.java ButtonAction.class DemoGUI.class DemoGraphicsScreen.class GraphicsListener.class ===============================================================
The buttons are positioned within a panel and connected to button listeners.
A "border layout manager" is used to position the canvas in the center
of the window and the panel along the South border.
|
Run Program Code: DemoGUI.java |
||||||||||||||||||||
WORKING WITH CONCURRENT PROCESSES | |||||||||||||||||||||
Implementation of a Thread.
This program demonstrates the implementation of a simple thread ....
![]() Figure 16. Class hierarchy for basic implementation of a thread. Lifecyle of a thread. .....
![]() Figure 17. Methods in the lifecyle of a thread. |
Program ... Code: ..... |
||||||||||||||||||||
Implementation of a Runnable Interface.
This program demonstrates the implementation of a runnable interface.
![]() Figure 18. Implementation of a runnable interface. |
Program ... Code: ..... |
||||||||||||||||||||
Demonstrate Mutual Exclusion.
Mutual exclusion is ....
|
Program ... Code: ..... |
||||||||||||||||||||
Demonstrate Semaphores.
A semaphore is ....
|
Program ... Code: ..... |
||||||||||||||||||||
Parking Lot Simulation.
Here we use threads to implement arrival and departure
processes in a parking lot simulation.
The parking lot is modeled as a bounded buffer.
Insert screendump ....
|
Run Program Code: ..... |
||||||||||||||||||||
Parcel Sorting Simulation.
Here we use threads and a discrete-time model to
simulate parcel sorting controled by sensors and gates.
Insert screendump ....
|
Run Program Code: ..... |
||||||||||||||||||||
WORKING WITH PACKAGES AND JAR FILES | |||||||||||||||||||||
Packages and Jar File.
A package is simply a group of classes. Packages are a convenient
mechansim for organizing code and, in the case or team development
of code, separating the work of one developer from another.
A JAR file is simply a ZIP file that contains classes, possibly other files that a program may need (e.g., image and sound files), and a manifest file describing the special features of the archive.
This example demonstrates how java source code can be organized into packages,
compiled, and then bundled into a jar file.
The unpacked source code will
be in a directory called packages-and-jar.d.
Move to that directory and then read the file
called README.txt.
|
Code: The java source code files are
bundled into a zip file called
PackagesAndJar.zip .
To unpack the zip tar file, type:
unzip PackagesAndJar.zip |
||||||||||||||||||||
JAVA PROGRAM COMPILATION WITH ANT | |||||||||||||||||||||
Working with Ant.
Ant is tool for automating the compilation of Java Programs.
Here, we use ant to compile the source code in the
"packages and jar" example.
The unpacked source code will be in a directory called
packages-and-ant.d. Move to that directory and then
read the file called README.txt.
|
Code: The source code files are bundled into a file called
PackagesAndAnt.zip .
To unpack the zip tar file, type:
unzip PackagesAndAnt.zip |
||||||||||||||||||||
CIVIL ENGINEERING APPLICATIONS | |||||||||||||||||||||
Triangle and Point.
There are lots of problems in Civil Engineering where we need to compute the
relationship of a point (or set of points) to a shape. For example,
in concrete design, we need to check that rebar has adequate cover.
This problem can be abstracted as: (1) is the rebar (a point) inside
the concrete (a polygon), and (2) is the point located an adequate
distance from the edge of the concrete.
This program computes the distance of a point from the edge contour of a polygon.
![]() Figure 19. Screendump of triangle and point program
The triangle is composed of three edges and three nodes.
Each edge is simply a line segment.
Hence, the problem of computing the closest distance to the edge of the
triangle boils down to computing the distance of the point from each
edge and then taking the minumum value. These computations can be found
in Edge.java and Triangle.java, respectively.
|
Code: DemoGUI.java Edge.java Node.java Vector.java Triangle.java To compile the program, type: javac DemoGUI.java The program can be run as an applet. I just type: appletviewer DemoGUI.html where DemoGUI.html is a suitable file containing a reference to the point-and-triangle bytecode files. |
||||||||||||||||||||
Building Footprint.
A footprint model simply defines the area that will be covered by an object.
Footprint models of buildings are commonly used in the
earliest stages of design and in high-level models of urban areas.
Because the footprint area is defined by its perimeter,
naturally, a general-purpose polygon model
is the first approach that comes to mind.
However, it turns out that the computation of simple
polygon operations (e.g., computing the area) can quickly become very complicated.
Many potentially difficult problems can be avoided by modeling the footprint as a collection of simple triangular regions. The next figure shows, for example, a six-triangle footprint model for the AV. Williams Building.
![]() Figure 20. Footprint model for AV Williams Building Now let's move onto details of the software implementation.
![]() Figure 21. Class diagram for footprint implementation
Simply put, the adjacent figure says that one Footprint object will be composed of
many Triangle objects. In turn, triangles will be defined
in terms of Node and Edge objects. Nodes are an extension of Vector.
Properties of the building footprint (e.g., area, center of mass)
will be computed and summed across the ensemble of triangles.
|
Download the zipped source code . To compile the program, type: javac Footprint.java The program can be run as an application.
|
||||||||||||||||||||
Model of a Wheel Cross-Section.
In this example we assemble a cross-section model of a wheel from
triangle objects, and display the wheel cross section and its area in a graphics window.
Pixel coordinates (as measured from the top left-hand corner of the graphics canvas)
can also be printed on the canvas by moving the cursor to a
desired position and then clicking.
![]() Figure 22. Cross section model of a Wheel. In this specific example, the minumum radius is 50 and the maximum radius is 150. Coordinates in the radial and angular directions are divided into three and sixteen intervals, repectively. Theoretical considerations indicate that the cross section will be 62,831. However, because the triangles only approximate the circular cross section, the computed area will be a little less. Individual triangle objects are assembled from Node and Edge objects, as shown above in the Footprint model. The wheel cross section is simply a collection of triangles stored in an array list.
The mesh of triangles in generated with a double loop. One loop increments
the coordinates from the minumum radius to the maximum radius.
A second loop systematically generates nodal coordiates in an angular
direction, from 0.0 through 2*pi radians.
|
Download the
zipped source code . To compile the program, type: javac DemoWheel.java The program can be run as an applet i.e., appletviewer DemoWheel.html |
||||||||||||||||||||
Centroid and Principal Axes of a Polygon Cross-Section.
This program computes the engineering properties (cross section area; (x,y) coordinates of
the centroid; moments of inertia about the centroid) for a polygon cross section,
possibly containing holes.
![]() Figure 23. Screendump of bridge cross section and engineering properties ... Polygon cross sections are modeled as an exterior ring, possible containing multiple interior rings. Each ring corresponds to a list of nodes have (x,y) coordinates. The nodes in an exterior ring are stored in a clockwise direction. Interior rings (holes) have nodes stored in an anti-clockwise direction. Polygon cross sections are defined in an xml file. For example: <?xml version="1.0" encoding="UTF-8"?> <!-- Polygon Layout XML document --> <!DOCTYPE polygon SYSTEM 'polygon.dtd'> <polygon> <loop type="exterior"> <coordinate> 100.0 0.0 </coordinate> <coordinate> 100.0 200.0 </coordinate> <coordinate> 300.0 200.0 </coordinate> <coordinate> 300.0 0.0 </coordinate> </loop> </polygon>
defines a small square.
|
Code: Rather than put individual java and xml files online, I have bundled them into a
tar file called BridgeAnalysis.tar .
To unpack the tar file, type:
tar xvf BridgeAnalysis.tar The unpacked program will be in a directory called bridge-analysis.d. Move to that directory and then compile the program with the command: javac PolygonGUI.java To run the program, type: appletviewer PolygonGUI.html |
||||||||||||||||||||
Day Planner.
A day planner is simple graphical program for presenting
a calendar of events. For example,
![]() Figure 24. Screendump of Day Planner application. The schedule of events in stored in an XML file called planner.xml. Here is an abbreviated snippet of code: <?xml version="1.0" encoding="UTF-8"?> <!-- Travel Planner XML document --> <!DOCTYPE planner SYSTEM 'planner.dtd'> <planner> <year value="2004"> <date month="1" day="27"> <note time="0000"> Last day to cancel spring registration </note> </date> .... details of code removed .... </year> </planner> |
Program ... output Code: ... |
||||||||||||||||||||
Modeling of a Simple Transportation Network.
Networks are a fundamental aspect of Civil Engineering Systems.
For example, transportation engineers are concerned with the
design and operation of rail, road, shipping, and air traffic networks.
Hydrology engineers work with networks of waterways.
Structural engineers work with networks of load bearing members (usually
beams and columns).
The following figure is a simplified model of the Washington DC metro system (most of the stations have been omitted):
![]() Figure 25. Simplified view of the Washington DC Metro System Passengers need to be familiar with the routes, schedule, and cost of using the metro. Typical questions include:
The Smithsonian question is particularly interesting because: (1) it requires that a transportation model be linked to a geographic information systems (GIS) model, and (2) there really isn't a unique answer. In its most rudimentary form, the Metro System can be modeled as a graph structure. Nodes in the graph correspond to train stations; the edges correspond to the tracks connecting stations. Graph theory is useful because it provides algorithms to answer questions about routes connecting stations A and B. The adjacent code is a first-cut implementation at modeling this problem domain.
Question |
Program ... output Code: ... |
||||||||||||||||||||
Route Selection Problem.
A fundamental problem in Transportation Engineering is the planning
of routes for expansion of transportation networks.
![]() Figure 26. Framework for route selection problem As indicated in the adjacent figure, this problem is complicated by the multitude of physical/.geographic, environmental, economic and political factors that can influence the final cost and efficiency of the system. Suppose, for example, that we want to build a road from city A to city B, but that a mountain range spans the most direct route. Is it better to build a road around the mountains, or pay more money upfront to build a tunnel through the mountains and provide a shorter route? The standard approach to problems of this type is to deal with each concern separately, and then combine the results. For example, the physical constraints might look like:
![]() Figure 27. Dealing with physical constraints in the route selection problem The final result is always never a single point, but rather a family of good solutions:
![]() Figure 28. Pareto Optimal Curves |
Program ... output Code: ... |
||||||||||||||||||||
Model of "Blue Pole" Security System.
The "blue pole" security system ....
|
Program output Code: Pole.java PoleNetwork.java |
ACKNOWLEDGEMENTS
Developed in May 2005 by Mark Austin
Copyright © 2005-2008,
Department of Civil and Environmental Engineering, University of Maryland