BASIC JAVA PROGRAMMING

This web page contains background material and a collection of basic java example programs that will be covered in class.
This is a work in progress!


PART 1. BASIC PROGRAMS

PROGRAM OUTPUT AND SOURCE CODE

Program 01. "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
Program 02. "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
Program 03. "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
Program 04. "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
Program 05. 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.

The Java language has eight basic data types:

Data Type Contains Default Size Range
boolean true or false false 1 bit N.A.
char Unicode character \u0000 16 bits \u0000 to \uFFFF
byte Signed integer 0 8 bits -128 to 127
short Signed integer 0 16 bits -32768 to 32757
int Signed integer 0 32 bits -2147483648 to 2147483647
long Signed integer 0 64 bits -9223372036854775808 to 9223372036854775807
float IEEE 754 floating point 0.0 32 bits -1.4e-45 to 3.402e+38
double IEEE 754 floating point 0.0 64 bits -4.9e-324 to 1.79e+308

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

Format Meaning Example
%d integer output System.out.printf("iA = %d\n", iA )
%f floating-point output System.out.printf("fA = %f\n", fA )
%e exponential format output System.out.printf("fA = %e\n", fA )

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
Program 07. 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
Program 08. 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.

  • A Scanner breaks its input into tokens, which by default will be delimited by whitespace.
  • The tokens may then be converted into values of different types using the various next methods.

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
Program 09. 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
Program 10. 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
Program 11. 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.

p q p ^ q p v q
T T T T
T F F T
F T F T
F F F F

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
Program 12. 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
Program 13. 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
Program 14. 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:

  • It's name,
  • The number, order, type and name of the parameters used by the method, and
  • The type of the value returned by the method.

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
Program 15. 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
Program 16. 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
Program 17. Working with 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
Program 18. 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
Program 19. 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: Equivalent functionality can be achieved by using a Scanner, a feature now supported by Java 5.


Code: ReadTextFromConsole.java
Program output
Program 20. 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
Program 21. 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
Program 22. 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
PART 2. SIMPLE APPLICATIONS

Here are a few simple application programs that use programming constructs covered in the previous section.


Program 23. 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
Program 24. 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
Program 25. 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
Program 26. 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
Program 27. 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
Program 28. 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. Also, the method windForce() is static, meaning that it may be called without first creating an object.


Code: WindForce.java
Program output
PART 3. 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.


Program 29. 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
Program 30. 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
Program 31. 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
Program 32. 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
Program 33. 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
Program 34. 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
Program 35. 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:

  • You can't "accidentally" corrupt the value of a field -- instead, you have to use a method to change a value.
  • The separation of interface and implementation makes it easier to modify the code within a class without breaking any other code that uses it.

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:

  • Data hiding

    Variables and methods internal to the object implementation will be declared as private and/or protected. Private data is only available within the class in which it is declared. Protected data is only available within the class in which it is declared, and, its subclasses.

  • Access methods

    Access to data/properties of the object will only be possible through setXXX() and getXXX() methods (e.g., the Circle class contains the methods setRadius() and getRadius()).



Program: output
Code: Circle.java
ColoredCircle.java
TestCircle.java
TestColoredCircle.java
PART 4. ABSTRACT CLASSES AND INTERFACE CLASSES
Program 36. Abstract Shape Class for Geometric Shapes

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
Program 37. Interface Class for Farm Workers

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
PART 5. PACKAGES, JAR FILES, AND ANT
Program 38. Working with Packages and Jar Files.

A package is simply a group of classes. Packages are a convenient mechanism 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
Program 39. 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

REFERENCES

  1. Press W.H., Teukolsky S.A., Vetterling W.T., Flannerly B.P., Numerical Recipes: The Art of Scientific Computing (Third Edition), Cambridge University Press, 2007.
  2. .....


Developed in October 2011 by Mark Austin
Department of Civil and Environmental Engineering, University of Maryland