JAVA EXAMPLE PROGRAMS

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 1.2-1.6. That is, Netscape 4.x with appropriate plugins, Java-enabled Netscape 7 or 8 (appropriate plugins are now embeded in browser), or Java-enabled versions of Microsoft IE 5-6.


JAVA BASICS

PROGRAM OUTPUT AND SOURCE CODE

"Peace on Earth" Java Application Program and Java Applet Program. Peace.java is a small standalone program. Peace2.html and Peace2.java are sourcefiles for the applet counterpart.

Standalone Program: Peace.java
Program Output: output
Run Applet: Peace2.html
Applet Program: Peace2.java
Basic Data Types, Arithmetic, and Math Functions. 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. This program demonstrates how output of the basic data types (int, float, double), can be easily formatted.

Code: DemoFormat.java
Program output
Numerical Errors. This program illustrates Java's capability in handling error conditions related to:
  • Overflow and underflow of numbers (i.e., Infinity and -Infinity),
  • Arithmetic expressions where the result is not-a-number (i.e., NaN).

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
Branching Constructs. This program demonstrates the use of simple if-else branching constructs, and branching constructs where the decision making involves evaluation of multiple relational and logical expressions.

Code: DemoBranching.java
Program output
Looping Constructs. This program demostrates use of "while" and "for" looping constructs, and nested looping constructs...

Code: DemoLoops.java
Program output
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
One-Dimensional Arrays. 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.

Code: DemoArrays1.java
Program output
Two-Dimensional Arrays. This program demonstrates the declaration and usage of one-dimensional arrays (i.e., so-called arrays or arrays) of numbers and Strings. Java supports ragged arrays, that is, two-dimensional arrays where the length of each row may be different.

Code: DemoArrays2.java
Program output
Strings. 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.

Code: DemoStrings.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.

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  false
The 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
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().


Code: Sphere.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
WORKING WITH OBJECTS
Circle Objects. The Circle class is a specification for circle objects defined by the (x,y) coordinate of their center point, their radius, and a "name".

Code: Circle.java
Program output
Colored Circle Objects. The Colored Circle class is a specification for colored circle objects. The implementation extends the Circle class and adds color for individual colored circle objects.

Code: ColoredCircle.java
Program output
Complex Number Arithmetic. This library specifies complex number objects and complex number arithmetic. 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 provides 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).

Code: DataArray.java
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!

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.

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
MORE JAVA
Abstract Classes. This program demonstrates the use of abstract classes to build a class hierarchy of rectangle and circle shapes. The source code is contained within a single file TestShape.java. After the program has been compiled, the bytecodes are:
    Circle.class        Location.class       TestShape.class
    Rectangle.class     Shape.class


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
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
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 JAVA COLLECTIONS
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
Array List4. This program creates Person objects for Homer Simpson, Bart Simpson, Lisa Simpson and Abe Simpson (Bart and Lisa's grandfather). 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.

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
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 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. 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. Footprint Model for AV Williams Building

Now let's move onto details of the software implementation.

Figure. 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.


Code: To be added soon ....

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. 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.


Code: To be added soon ....

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. 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. 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. 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:

  • When will the metro open? When will it close?
  • How do I get from station A to station B?
  • Will I have to change trains? Where?
  • How long will it take to get there? And how must will it cost?
  • I'm going to the Smithsonian -- what station should I get off?
  • I'm at station A. When is the last train to station B?

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
How would you extend the basic node-edge graph structure to make the model more realistic.


Program ... output
Code: ...
Route Selection Problem. A fundamental problem in Transportation Engineering is the planning of routes for expansion of transportation networks.

Figure. 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. 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. 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

  1. Walrath K. et al. (1999), Java Swing Tutorial , Sun Microsystems.


Developed in May 2005 by Mark Austin
Copyright © 2007, Department of Civil and Environmental Engineering, University of Maryland