You are on page 1of 48

Object Oriented Engineering using Java

What is Java?

Java is an object-oriented language developed by Sun systems. Originally, it was developed for
microprocessor-empowered devices such as cable TV switchboxes, but it has expanded and
developed into an industrial-strength programming language.

It is especially useful in networked and internet-based environments. However, it should not be


confused with JavaScript, which is a scripting language for Web browsers.

Java is very similar in syntax to C, but tends to be more robust and simpler to use. It is easy to
port from one machine to another, since it uses byte code - a semi-compiled object code easily
translatable to machine code. This means that the byte code runner - or Java Virtual Machine -
must be installed on the computer that is to run the Java program.

The Java language provides a wealth of classes, or blueprints, from which programs can be built.
Class libraries exist for almost every type of programming problem. Available libraries include
GUI-based systems, client-server networking solutions, mathematics, graphics, Internet server
pages and many more.

What is Object Oriented Programming?

We will take a very brief look at object oriented programming. There are many good books
available on the subject for those who want an in-depth cover of the topic. Here, we will just
introduce a few key ideas and define some of the terms used.

Many of the things we use every day are built from a set of re-usable components. Cars,
televisions, and computers are all designed this way. This makes them cheaper to manufacture,
and easier to maintain, since a faulty component can just be replaced. Object oriented
programming is an attempt to use the same method to design and write computer systems

Key Terms in OOP

Some key terms used in Object Oriented Programming (OOP)

A blueprint or design from which an object, or component, is built. You can


Class
think of this as being like the mould in which a steering wheel for a car is made.
An actual component. This is like an actual steering wheel, built from the mould.
There may be several steering wheels made from the same mould. Each one may
Object
be different in some respects. For example, one may be painted black while
another is painted silver.
These are things that describe an individual object. For example, the steering
Properties wheel in the above example could have the property color. One object will have
a color of black; another a color of silver.
These are actions that can be carried out by an object, and are defined in the
Methods class. The steering wheel could have a method named turn, since this is
something that it can do.
Inheritance OOP allows for sub classes to be defined. A subclass inherits all the properties
and methods of the original class, and can add a few of its own. A steering wheel
that can lock could be a sub class of steering wheel. It has all of the original
properties and methods, such as color and turn,and adds in new methods
called lock and OOP allows for sub classes to be defined. A subclass inherits all
the properties and methods of the original class, and can add a few of its own. A
steering wheel that can lock could be a sub class of steering wheel. It has all of
the original properties and methods, such as color and turn, and adds in new
methods called lock and unlock..
When fitting a component such as a power supply into a computer, it's not
neccessary to know how it works or what goes on inside it. All you need to know
is what type of connections it has, and what voltage should be supplied to it.
Powers supplies are interchangeable provided that the connections and power
Encapsulation
requirements are the same. Encapsulation means that objects in a computer
system should behave the same way. They can only communicate with other
objects using predefined connections, and should be interchangeable with other
objects using the same connections

What do I need to begin developing in Java?

You need a Java Development Kit (JDK), which is downloadable for free
from www.java.sun.com. Some operating systems, such as certain versions of Linux and Unix,
come bundled with a copy of the JDK. Lots of people prefer to work via an IDE (Integrated
Development Environment) such as NetBeans or Eclipse, since this gives you a simple, menu-
driven environment for development. Eclipse and NetBeans are both available fro free on he
Internet. If you don't have an IDE, you can work from the Unix, Linux or DOS command
prompt, using any text editor to create your programs.

Creating, Compiling and Running a Java program

In this tutorial, I used the Eclipse Europa 2007 IDE for most of the programming examples. I'll
also take a quick look in this chapter at how to create, compile and run a program from the Unix,
Linux or DOS command prompt. If you have a different IDE, you should be able to find
corresponding menu choices quite easily.

Here's the code for a simple Java program that simply displays the text "I am a Java guru!" on
the screen.

public class Guru


{

public static void main(String[] args)


{
System.out.println("I am a Java guru!");
}

To create and run this program in Eclipse:


You should have the Eclipse Workbench open. The screen should look like this:
In Eclipse, Java programs are grouped together into projects. Before entering the first sample
program, we need to create a project called MyExamples. This will be used to store all the
examples from this tutorial. Choose File, then New, then Project from the menu. You will be
presented with a screen that looks like the one below. All you need to do is enter the name of the
project in the appropriate box, then click the Finish button to create the project.

Now you need to create the Java class Guru. Choose File then New then Class from the menu.
You will see a screen like the one below. Fill in the name of the class (Guru), and, under the
section 'Which methods would you like to create?', select the checkbox next to 'public static void
main'. Then click 'Finish'.

You will now see the new class appearing in the central window as below.
You will notice that it has generated most of the code for the program Guru.java. It has also
generated some comment lines. The comment lines enclosed between /** and */ form part of the
program documentation. You normally edit these to contain meaningful comments about the
class. Single-line comments begin with //. These are notes for the programmer. They are usually
used to explain the code so that anyone who has to work on it later knows what each section of
code is for.

You can now use the center window as a text editor, and add in the rest of the program. It is an
'intuitive' editor; in other words, it tries to anticipate what is likely to come next in a Java
program. It also highlights any errors with a wavy red line. This takes a bit of getting used to, but
is quite simple to use. Edit it so it looks like this:
Note that Java is case-sensitive, and punctuation symbols as semi-colons and brackets are
important. Save the text by selecting Save from the File menu, then choose Run from the Run
menu. If you made any mistakes, it will tell you that there were errors in the class, and highlight
them. If this happens, fix the errors and try again.

If there were no errors, the program will run, displaying its output in the Console window at the
bottom of the screen as below:
If you are working from the command prompt rather than through an IDE, you will need to carry
out the following steps instead. Assuming that Java has been correctly installed on your machine:

Use a text editor such as Notepad in Windows or vi in Unix or Linux to place the program text
shown below into a file named Guru.java. The name of the source file and the name of the public
class must always be the same. Names are case sensitive. If using Notepad, save as type 'All
files' rather than type 'Text Files'. If you don't, it will add an extension of .txt on the end, which
will confuse the Java compiler.

public class Guru


{

public static void main(String[] args)


{
System.out.println("I am a Java guru!");
}

Compile the program by typing

javac Guru.java

If you made any mistakes, error messages will be displayed on the screen. If this happens, go
back and fix your program so it looks exactly like the text shown above. Be careful of
puctuation, and remember that it's case sensitive.

Once it's compiled successfully, you can run it by typing:

java Guru

It should then display the message 'I am a Java guru' on the screen.
You have written, compiled and run your first Java program!

Let's use this simple program to learn a few things about Java. Don't worry if some things are a
bit confusing at present: it will all become clearer later.

1. In Java, everything is written as a class, and has a name. The first line of the program:

public class Guru

is used to introduce the class and give it a name, in this case Guru. The word 'public' is
a modifier - it gives more information about the class. publicmeans that it can be
accessed from other programs. This line is called a class header.

2. 2. Classes can contain methods. In this program, there is a method named main,
introduced with the method header:

public static void main(String[] args)

Method headers can also contain modifiers. public means that this method can be called
by other classes. We'll look at the meaning of static in a later chapter

Methods can sometimes pass an item of data back to the class that called them. The
method header must either specify what kind of data the method will return, or use the
word void to specify that it will not return any data. This is known as the return data
type of the method.

Each method must have a name. In this case, the method is called main. If a Java class is
to be run as a stand-alone program, it must have a method called main. This becomes the
starting point of the program.

Some methods will need to receive data from the class that calls them. The method
header must define the number and type of data items that it will expect, and give each
one a name. These data items are known as arguments to the method. This particular
method expects an array of strings, given the name args. For those of you who have not
done much programming, you can think of an array as being a collection of similar items.
A program's mainmethod should always expect an array of strings. These can be supplied
by the user on the command line when the program is run. Even if the program doesn't
use them, you should still define them.

3. Braces {} are used to enclose blocks of code. In this program we have an inner and an
outer block. The outer block consists of everything that makes up the class Guru. The
inner block encloses everything that belongs to the method main.

4. The following line:


System.out.println("I am a Java guru!");

defines an action to be taken. In later chapters, you'll learn more about how to code
actions (or commands). For now, just use this command as it is (Other than changing the
text between the quotes) every time you want to display something on the screen.

This program can be used as a skeleton for every stand-alone Java program that you write. Try
experimenting with it to create a program of your own that displays a different message, or
several messages.
Java Language Basics

A Java program consists of one or more classes. Classes can be defined by you, or they can be
predefined classes, either from the standard Java libraries, or from third-party Java libraries.

Classes consist of a class header and a class body. The body, enclosed in braces {}, can
contain data declarations and methods.

Methods could be described as named groups of actions. Each method in a class consists of a
method header, followed by a list of actions that make up the method. We've already had a brief
look at class and method headers. We'll look a bit more closely at actions shortly.

The data declarations define variables and constants that will be used by the program. For
those not familiar with programming terms, you can think of avariable as being a place where
you can store a piece of data. All variables must be declared - in other words, you must give
them names, and specify what type of data will be stored in them. Constants are similar to
variables, except that they are given a value when they are declared, and that value never
changes. You may, for example, define a variable to store the value of the mathematical constant
Pi.

Data declarations can also be included inside a method. If data is declared within a method, it
can only be used by that method. However, if data is declared within the class, but not within a
method, that data can be used by any method within the class. Variables declared outside
methods are known as class variables. They are also known as properties of the class, since they
store information belonging to the class. In fact, the rule is that variables can only be used within
the same block in which they are declared. A block, as I mentioned earlier, is a bunch of Java
statements surrounded by braces {}.

Data declarations give a name, a data type and optionally a value for each item of data that the
program needs.

Data names are given by you, the programmer. They are usually made up of letters, numbers and
underscores. They cannot contain spaces.

Java defines 8 primitive data types. More complex types of data can be used in Java, but must
be defined by a class. The primitive data types are:

Description Type Details

Integer data long Long integers occupy 8 bytes, and are capable of storing
types signed numbers 18-19 digits in length.

(No decimal
places allowed)

int These occupy 4 bytes, and store signed numbers 8-9 digits in
length.

short Short integers occupy 2 bytes, and store numbers in the range
32768 to +32767.

byte Byte variables occupy 1 byte and store numbers in the range
128 to +127

Floating point float Float variables occupy 4 bytes. They can be used to store
data types numbers with fractional parts.

However, since the fractional part is stored as a binary


fraction, and binary fractions do not always convert exactly
to decimal fractions, there may be some rounding errors This
makes them unsuitable for storing currency values for
accounting functions.

Float variables store 6 to 7 significant digits with a range of


approximately 3.4E+38

double This is a double precision floating point variable occupying 8


bytes. As with Float, it is stored as a binary fractions.
Doubles have 15 significant digits and can store numbers in
the range of approximately 1.8E+308

Character data char This stores a single Unicode character occupying two bytes.
Unlike C, character variables in Java cannot be used for
arithmetic. They can, however, be converted to and from the
integer data types to obtain a numeric Unicode value.
Unicode is a 2-byte extension of the Ascii character set
catering for multi-language characters.

Boolean data boolean This is used to store a boolean value of true or false, and can
types be used in Java statements to make program decisions. It
occupies 4 bytes. Unlike C, the boolean data type is not
compatible with the numeric data types, and cannot be
converted to or from them.

Additionally, there is a pseudo data type called String. Although String is actually a class, in
many ways it behaves like an ordinary data type. It is used to store and manipulate character
strings.

To be able to write a Java program, we now need to know how to code data declarations, and
also how to code the actions that make up a method.
Lets look at another sample program. This one calculates the average of all the numbers
between 1 and 4. Not terribly useful, but it serves to illustrate a few points.

public class Averages


{

public static void main(String[] args)


{
float total, average;
total=1+2+3+4;
average=total/4;
System.out.println(The average of the numbers 1 to 4 is:);
System.out.println(average);
}

Notes:

1. The line

float total, average;

is a data declaration. First of all, a data declaration must specify the data type of the variable.
In this case, the data type is float. Secondly, a data declaration must give a name to the
variable. If we have several data items of the same type, we can simply provide a list of
names of all all items of this type, separated by commas. So here we have two floating point
numbers that we will call total and average. Finally, the data declaration must be terminated
with a semi-colon.

2. The lines

total=1+2+3+4;
average=total/4;

are actions. This particular type of action is called an assignment, since it assigns a value to a
variable. This assignment consists of literals and arithmetic operators. A literal is an actual
supplied value in the first of these lines we have supplied the values 1,2,3 and 4. An
arithmetic operator causes arithmetic to be carried out on the supplied values. In this case, we
are using the plus sign (+). We can also use others, such as for subtraction, * for
multiplication and / for division.

So the first of these lines carries out the sum 1+2+3+4, and places the answer in the
variable total, which now contains 10. The second line takes the value held in total, divides it
by 4, and places the answer in the variable average, which will then contain 2.5. Note that
actions must also be terminated by semi-colons.

3. The lines:

System.out.println(The average of the numbers 1 to 4 is:);


System.out.println(average);

are also actions, but a different kind. This type of action is a method call. It invokes another
method in other words, it goes away and carries out all the actions that make up that
method, then comes back again. Methods can be called from the current class, or from a
different class. If they belong to another class, the name of the method must be prefixed by
either the name of the class, or the name of an object created from that class. (Well talk more
about creating objects a bit later.) Here we are calling a method called println that belongs to
the class System.out. System.out is one of the standard Java library classes, and
the println method displays the message supplied inside the brackets on the screen. The first
of these lines tells it to print the literal character string The average of the numbers 1 to 4
is: . Note that string literals must be enclosed in double quotes. Single character literals, by
the way, should be enclosed in single quotes. The second line tells it to print the contents of
the variable average.

Try typing in this program and running it. Then see if you can write a new program of your own
that will display the result of multiplying together all the numbers between 2 and 7.

Using Methods from the Java libraries

The Java libraries are what makes Java so powerful. There are library classes for almost every
conceivable programming task, from creating interactive Web pages down to mathematical and
scientific functions. Here well look at a program that makes use of a few methods from library
classes. As yet, we havent learnt how to create an object from a class. We learn that in the next
chapter. But some classes have methods that can be used, even when no object has been created
from the class. These are called static methods. Lets have a look at a simple program that
illustrates this.
This program calculates simple monthly interest on a loan rounded to the nearest dollar, given
the amount of the loan and the annual interest rate.

public class interest


{

public static void main(String[] args)


{
double loan, rate, mthlyInt;
loan=Double.parseDouble(args[0]); // First argument is the loan
rate=Double.parseDouble(args[1]); // Second argument is the rate
mthlyInt=
Math.round(loan*rate/1200);
System.out.println(Interest is +mthlyInt);
}

Notes:

1. The line

float total, average;

is a data declaration. First of all, a data declaration must specify the data type of the variable.
In this case, the data type is float. Secondly, a data declaration must give a name to the
variable. If we have several data items of the same type, we can simply provide a list of
names of all all items of this type, separated by commas. So here we have two floating point
numbers that we will call total and average. Finally, the data declaration must be terminated
with a semi-colon.

2. The lines

total=1+2+3+4;
average=total/4;

are actions. This particular type of action is called an assignment, since it assigns a value to a
variable. This assignment consists of literals and arithmetic operators. A literal is an actual
supplied value in the first of these lines we have supplied the values 1,2,3 and 4. An
arithmetic operator causes arithmetic to be carried out on the supplied values. In this case, we
are using the plus sign (+). We can also use others, such as for subtraction, * for
multiplication and / for division.

So the first of these lines carries out the sum 1+2+3+4, and places the answer in the
variable total, which now contains 10. The second line takes the value held in total, divides it
by 4, and places the answer in the variable average, which will then contain 2.5. Note that
actions must also be terminated by semi-colons.

3. The lines:

System.out.println(The average of the numbers 1 to 4 is:);


System.out.println(average);

are also actions, but a different kind. This type of action is a method call. It invokes another
method in other words, it goes away and carries out all the actions that make up that
method, then comes back again. Methods can be called from the current class, or from a
different class. If they belong to another class, the name of the method must be prefixed by
either the name of the class, or the name of an object created from that class. (Well talk more
about creating objects a bit later.) Here we are calling a method called println that belongs to
the class System.out. System.out is one of the standard Java library classes, and
the println method displays the message supplied inside the brackets on the screen. The first
of these lines tells it to print the literal character string The average of the numbers 1 to 4
is: . Note that string literals must be enclosed in double quotes. Single character literals, by
the way, should be enclosed in single quotes. The second line tells it to print the contents of
the variable average.

Try typing in this program and running it. Then see if you can write a new program of your own
that will display the result of multiplying together all the numbers between 2 and 7.

Using Methods from the Java libraries

The Java libraries are what makes Java so powerful. There are library classes for almost every
conceivable programming task, from creating interactive Web pages down to mathematical and
scientific functions. Here well look at a program that makes use of a few methods from library
classes. As yet, we havent learnt how to create an object from a class. We learn that in the next
chapter. But some classes have methods that can be used, even when no object has been created
from the class. These are called static methods. Lets have a look at a simple program that
illustrates this.

This program calculates simple monthly interest on a loan rounded to the nearest dollar, given
the amount of the loan and the annual interest rate.

public class interest


{

public static void main(String[] args)


{
double loan, rate, mthlyInt;
loan=Double.parseDouble(args[0]); // First argument is the loan
rate=Double.parseDouble(args[1]); // Second argument is the rate
mthlyInt=
Math.round(loan*rate/1200);
System.out.println(Interest is +mthlyInt);
}

The program allows the user to enter the loan amount and the annual interest rate as arguments in
the command line. Later, well look at other, and better, ways of allowing the user to enter data
into the program. But command line arguments are easy to deal with in Java, so well use these
in the next few examples. The program then calculates and displays the monthly interest.

Lets look at the main method line by line:

double loan, rate,mthlyInt;


This declares three variables needed by the program.

loan=Double.parseDouble(args[0]);
rate=Double.parseDouble(args[1]);
The command line arguments are received by the program in the array of strings named args that
are defined in the method header of the method main. The first of these, the loan amount, will be
found in args[0], and the second, the interest rate, in args[1]. Elements in an array are always
numbered starting from 0. To convert these strings to binary numbers compatible with the
primitive data type double, we use a method from one of the library classes, Double. The method
parseDouble checks that a string contains a valid number, and, if so, converts it to data
type double. So the variables loan and rate now contain the amount of the loan and the annual
interest rate.

mthlyInt=Math.round((loan*rate)/1200);
This uses the formula (loan*rate)/1200 to calculate the monthly interest. It then uses
the round method of the Math class to round it to the nearest dollar.

System.out.println(Interest is +mthlyInt);
This diplays the text Interest is followed by the contents of the variable mthlyInt.

When running the program, the loan amount and the interest rate must be entered as command
line arguments. To do this in Eclipse, after typing in and saving the program, choose Open Run
Dialog from the Run menu. Click on the Arguments tab, and enter the arguments as shown
below. Then click Run to run the program.

To enter command line arguments when running the Java program from the command prompt,
simply type the arguments after the program name, as shown below:

java interest 1500 8

Documentation on the various library classes and the methods available in each can be found on
the Java website at http://java.sun.com/javase/6/docs/api/.There are many hundreds of Java
classes. This short tutorial will look at using just a very few of them. To become an expert Java
programmer, you will need to learn to work with the Java documentation. Youll get some
practice at doing that in some of the later examples.

Making Program Decisions

As with most programming languages, the flow of Java programs can be controlled with
conditional statements, loops or switches. There is no GOTO in the Java language.z

Conditional statements are coded according to one of the following:


if (condition) statement;

or

if (condition) statement;
else statement;

or

if (condition) {block of statements)

or

if (condition) {block of statements}


else {block of statements}

The condition can be used to select either a single statement or a block of statements.
condition is any valid boolean expression. Boolean expressions are a way of expressing the
criteria for a program decision. Most conditions are expressed by comparing one thing to
another. For example, we can compare a variable containing the type of customer to the literal
value Dealer. If they are equal, we want to give the customer discount. Assume that the
customer type is stored in a variable named CustType and the discount is stored in a variable
named discount.

if (CustType==Dealer)
discount= (AmtDue * 0.1);
else
discount = 0;
Note the double equal sign used in the condition. Java uses a double equal sign for comparisons.
A single equals sign is used for assignments.

if (FinalMark < 50) Result = Fail;


else Result = Pass);
uses the value of the variable FinalMark to decide on the value to be placed in the variable
Result.

You can compare a variable to a literal, to another variable, to an arithmetic expression, or to the
value returned by a method. You can also use a variable of data type boolean to make a decision,
since these variable contain a value of either true or false.

You can also join two or more conditions together using boolean operators. && represents
and, || represents or, and ! represents not. The following code checks that there is enough
stock available and the customer has not exceeded his credit limit, in order to decide between
calling methods to either create an invoice, or reject the invoice.

if ((SaleQty <= StockQty) && (SaleValue <= CreditAvail))


{
StockQty = StockQty - SaleQty;
CreditAvail = CreditAvail - SaleValue;
Invoice.Write();
}
else Invoice.Reject();

This is probably a good time to include a summary of all the operators that can be used in
coding statements in a Java program. See the table below.
Comments
Comments in Java programs can take three forms:

// Indicates that the rest of the line should be treated as a


comment.

/* Indicates the beginning of a comment block which may


span more than one line.

*/ Indicates the end of a comment block begun with either /*


or /**

/** Indicates the beginning of a comment block which can be


used to form part of the program documentation. The
utility javadoccan be used to build program documentation
from these comment lines.

Operators
There are many different operators available in Java. These are
classified below.

Arithmetic
+ Addition. Note: the + sign can also be used for string
concatenation.

- Subtraction

* Multiplication

/ Division. If both of the operands are integer, integer


division with truncation is carried out; otherwise, the
answer will contain fractional parts.

% Modulus. This will give the remainder portion of an integer


division carried out on the two operands e.g. 15 % 6 would
give the answer 3.
Note that there is no exponential (to the power of) operator. A
method of the Math class can be used to achieve this, as detailed in
Chapter 4.

Increment and
Decrement var++ Where var indicates a variable name, var++ will increment
the contents of the variable by 1. This will be done after
the variable has been used in the expression, so that after
the following statements:

int n = 5;

int x;

x=3*n++

n would contain 6, since it has been incremented, and x


would contain 15, since it is calculated using the value of n
before incrementation.
var-- This works in the same way as var++, except that the
contents of var would be decremented by 1.

+ This increments the contents of var before var is evaluated


+var for the expression, so that after the following statements:

int n = 5;

int x;

x=3*++n

n would have the value of 6, and x would have the value of


18, since the incremented value is used in evaluating the
expression.

--var This works in the same way as ++var, except that var is
decremented by one.

Relational
and Boolean == This tests for equality. The double equals sign avoids
confusion with the single equals sign used for assignments.

!= Not equal to

> Greater than

< Less than

>= Greater than or equal to

<= Less than or equal to

! Not

&& And

|| Or

Bit
manipulation & Logical And
| Logical Or

^ Exclusive Or

~ Not

>> Bit shift right, extending sign bit

<< Bit shift left

>>> Bit shift right, extending with zeros

Condition
? This is used within an assignment to choose between two
possible values. Its usage is as illustrated in the following
example:

SalesTaxPercent=(TaxDue=='Y')? 20:0;

The condition TaxDue==Y is used to decide whether to


place the value 20 or the value 0 into SalesTaxPercent.

Shortcut
Programs often need to use the current value of a variable in
calculating its new value, for example

x=x+10

This can be shortened to

x=+=10

in Java. This produces the same result as the first example.

This shortcut can be used with most of the arithmetic and bit
manipulation operators, so that the following are valid:

+=; -=; *=; /=; %=; &=; |=; ^=; <<=; >>=; >>>=

Order of
evaluation Java assignments can become extremely long and complicated,
often using several operators in a single statement. It is therefore
important to understand the order of evaluation.
The table below lists the different levels in the order of evaluation
to which each operator belongs. Those at a higher level will always
be carried out before those at a lower level.
Method calls

Brackets, !, ~, ++, --, Unary plus and minus (ie sign associated with
a number), cast

*, /, %

+,-

<<,>>,>>>

<, <=, >, >=

==,!=

&

&&

||

=,+= and other equivalent shortcuts

Brackets may always be used to control the order of evaluation.

Making Program Decisions


The main advantage of computers is that they can carry out repetitive tasks very quickly. To do
this, we need to be able to repeat an action or group of actions many times. There are several
ways of doing this in Java.

The for .. loop is generally used when a statement or block of statements needs to be executed a
fixed number of times.

The syntax is:


for (InitiationStatement; Condition; IncrementationStatement)
statement;
or
for (InitiationStatement; Condition; IncrementationStatement)
{block}

The initiation statement is usually used to set a counter to an initial value; often 0. The condition
is checked before each cycle of the loop; when the condition becomes false, the loop terminates.

The incrementation statement is used to increment the counter after each cycle of the loop. A
simple increment (eg i++) can be used to increment the counter by 1, or any assignment
expression can be used to increment it by some other value.

The following example prints the square of all the numbers between 1 and 10.

public class Squares


{

public static void main(String[] args)


{
for (int i=1; i<11;i++)
System.out.println(+ i + " squared is " + i*i);
}

/* Note: The + operator is used in the println method to concatenate the items to be
printed. Since a string is expected here, and the first item to be printed is an integer, the
concatenation operator precedes it to convert it to a string. */

The variable i is used as a counter to step through all the values between 1 and 10.

Try typing this program in and running it. Then try modifying it to print the squares of all the
numbers between 20 and 30.

Additional Tip: The break statement can be used within a Java loop to break out of the loop
prematurely. It will cause execution to continue with the next statement after the loop.

The while loop is used to repeat a statement or group of statements while a condition remains
true. The condition is tested before any of the statements are executed, so that if the condition is
false at the outset, the loop will not be executed at all.

Example:
while (MoreEntries)
Entry.Process;

The do....while loop is similar to the previous type of loop, except that the condition is checked
after processing the statement or block of statements, so that it will always be executed at least
once, even if the condition is false at the outset
The following program illustrates the use of the do....while loop. It also illustrates using the
boolean data type, and the use of the break command.

Sample Program: Check for Prime Numbers

/* ******************************************
* This program will take a number *
* from the command line, and check *
* to see whether it is a prime number *
* **************************************************/

public class prime


{

public static void main(String[] args)


{
int NumIn, Counter;
double NumRoot;
NumIn = Integer.parseInt(args[0]);
/* ******************************************
* Factors between 2 and the square *
* root of the number entered will be *
* searched for *
* ******************************************/
NumRoot=Math.sqrt(NumIn);
Counter=2;
boolean Factorised=false;
String Result;

do
{

if (Counter > NumRoot) // Factors cannot be greater


break; // than the square root
if(NumIn % Counter == 0) // If dividing by the counter gives
Factorised=true; // remainder 0, a factor was found
Counter ++;
}
while (! Factorised);

if (Factorised)
System.out.println(+ NumIn + " is not a prime number");
else
System.out.println(+ NumIn + " is a prime number");
}
}
When running this program, enter the number to be checked as an argument. The program will
tell you whether it is a prime number.
Using the switch statement

The switch is used to select alternate program paths depending on the value of a variable. In
some cases, this is easier than using a lot of if statments to check the contents of the same
variable.

The general syntax is:

switch(variablename)
{
case value:
statement ..;
break;
case value:
statement ..;
break;
etc
default:
statement ..;
break;
}

The contents of variablename are tested against each of the case values listed. If a match is
found, the statements between the matching case and the next break are executed.

A case with its relevant statements would be coded for each value which is of interest to the
program. Optionally, a default can be included. The statements listed under the default will be
executed if there are no matches.

Sample program using switch:

// *****************************************************
// * This program will carry out a calculation *
// * entered on the command line. The calculation *
// * should be entered as a number, followed by a *
// * space, followed by an operand, followed by a *
// * space and a number. Valid operands are +,-,x *
// * and /. *
// *****************************************************
public class calc
{

public static void main(String[] args)


{
double Num1, Num2, Ans=0;
char Op;
Num1=Integer.parseInt(args[0]); //First argument is a number
Op=args[1].charAt(0); //First character of second
//argument is the operand
Num2=Integer.parseInt(args[2]); //Third argument is a number
// *********************************************************
// Decide on the correct calculation depending on *
// the operand entered *
// **********************************************************
switch(Op)
{

case '+':
Ans=Num1+Num2;
break;
case '-':
Ans=Num1-Num2;
break;
case 'x':
Ans=Num1*Num2;
break;
case '/':
Ans=Num1/Num2;
break;
default:
System.out.println ("Can't do that - I'm only a cheap calculator");
break;
}
System.out.println("Answer is " + Ans);
}
}

Notes:

The following lines may need some extra explanation:

Num1=Integer.parseInt(args[0]);

We have already used the parseDouble method of the Double class in a previous example. The
Integer class is similar to Double, except that it contains methods useful when dealing with data
type int (Whole numbers)

Op=args[1].charAt(0);

The String class defines several methods useful when dealing with strings. Because args[1] is
defined as an object of class String, we can use the methods of the String class to work with it.
The charAt method retrieves a single character at a given ppoint in the string. charAt(0) retrieves
the first character. Check out the Java documentation for the String class to see other useful
string handling methods. Go to http://java.sun.com/javase/6/docs/api/, then choose java.lang to
see the core Java language documentation. From there, choose the String class.

Working with Objects

When we looked briefly at object oriented programming at the beginning of this tutorial, we said
that programs should be built from a collection of objects. Classes are the blueprint, or mould,
from which objects are made. Up till now, we have looked at very simple programs that are
defined in a single class. Now we need to know how to make use of other objects in our
programs.

Well use the Java Library class BigDecimal to look at how to incorporate and use objects within
our program. Objects created from the BigDecimal class are used to store and work with decimal
fractions. As I mentioned earlier, the double and float data types store numbers as binary
fractions. These dont always convert exactly to decimal fractions, and tend to give rounding
errors. This can drive an accountant crazy, as they like things to balance right down to the last
cent!

To make use of an object in your program, you need to know a few things about the class from
which the object will be created. Firstly, you need to know whether it expects any data to be
supplied when it is created. Secondly, you need to know what methods it has, what type of data
they expect, and what type of data they will return.

Again, for the Java library classes, your source of information will be the Java documentation
on http://java.sun.com/javase/6/docs/api/ . Have a look at the documentation for
the BigDecimal class by choosing java.math, then choosing BigDecimal.

There are a few things that are worth noting from the documentation, before looking at how
a BigDecimal object can be used in a program.

At the top of the documentation, you will see the following:

java.math
Class BigDecimal

java.lang.Object
|
+--java.lang.Number
|
+--java.math.BigDecimal

java.math is the package to which the Bigdecimal class belongs. Packages are a way of grouping
classes together. The core java libraries contain several packages,
including java.lang, java.util (utility classes), java.math (mathematical classes), java.sql (classes
for working with databases) etc.

Underneath the class name is an inheritance hierarchy, showing that BigDecimal is a subclass of
the class Number, which again is a subclass of the class bject. This means that it inherits data and
methods from the Number class and also from the Object class.

Next, you will see a description of the BigDecimal class, followed by a field summary. The field
summary shows constants that are defined in the BigDecimalclass. Of interest to us is the
following:

static int ROUND_HALF_UP


Rounding mode to round towards "nearest neighbor" unless both neighbors are equidistant, in
which case round up

Many of the Java classes define constants that are codes understood by the class, and can be
used to control the way certain methods work. ROUND_HALF_UP is one of them. We will refer
back to this later.

Next we see a section headed Constructor Summary. This shows the data that will be required
when creating an object from this class. There are usually several different options. We will take
note of one of them, which we will use in the next example program.
BigDecimal(java.lang.String val)
Translates the String representation of a BigDecmal into a BigDecimal.

This tells us that a BigDecimal can be created by supplying the number that it will store, in
String format.

Next we see a Method summary. This gives a list of all the methods defined in the class, showing
the type of data to be supplied to them, and the type of data returned. For example, there is a
method for adding together two BigDecimal numbers as follows:

java.math.BigDecimal add(java.math.BigDecimal val)


Returns a BigDecimal whose value is (this + val), and whose scale
is max(this.scale(),val.scale())

This tells us that the method is named add; it needs to be supplied with an object of
class BigDecimal which it refers to as val; and it will return another object of
class BigDecimal containing the sum of the number stored in this object, and the number
supplied as val.

We will also make use of the multiply, divide and subtract methods. Have a closer look at the
definition of the divide method:

java.math.BigDecimal divide(java.math.BigDecimal val, int scale, int roundingMode)


Returns a BigDecimal whose value is (this / val), and whose scale is as specified.

Note that this method needs three arguments: the first is the divisor, the second defines the
number of decimal points to be held in the answer (the scale),and the third defines how to deal
with any rounding that will take place. This is where we would use the constant
ROUND_HALF_UP that we took a note of earlier.

Now that weve looked at the documentation for the BigDecimal class, lets learn how to create
an object from a class in our program. There are two steps in creating an object. Sometimes we
can shortcut and carry out both steps in one statement. At other times, we may need to carry out
the two steps separately.

The first step is to create a reference to the object. This is done by stating the classname from
which the object is to be created, and the name by which it will be known in your program. This
doesnt create an object: all it does is create a memory area that can store a pointer to the object.
For example, coding the following line in you program:

BigDecimal num1;

creates a pointer called num1 that will be used to point to an object of class BigDecimal.

To actually create the object, you need to call the constructor of the class, supplying te required
data. The BigDecimal class, as we saw from the documentation, needs to be supplied with a
number that will be stored in the new object. To create the object num1 containing the number
5.37, the coding is:

num1 = new BigDecimal(5.37);


This can, in fact, be done in a single step as follows:

BigDecimal num1 = new BigDecimal(5.37);

The following program is an amended version of the program calc that we saw in an earlier
example. This one uses BigDecimal objects instead of doubles to store the numbers and do the
calculations.

// *******************************************************
// * This program will carry out a calculation
// * entered on the command line. The calculation
// * should be entered as a number, followed by a
// * space, followed by an operand, followed by a
// * space and a number. Valid operands are +,-,x
// * and /.
// ******************************************************
//
// * Modified version - uses BigDecimal class to
// * store the numbers and perform the arithmetic
// ******************************************************
import java.math.*;
public class calcdec
{

public static void main(String[] args)


{

BigDecimal Num1, Num2, Ans;


char Op;
Num1=new BigDecimal(args[0]); //First argument is a number
Op=args[1].charAt(0); //First character of second
//argument is the operand
Num2=new BigDecimal(args[2]); //Third argument is a number

Ans=new BigDecimal(0);

// ******************************************************
// Decide on the correct calculation depending on
// the operand entered
// ******************************************************

switch(Op)
{

case '+':
Ans= Num1.add(Num2);
break;
case '-':
Ans= Num1.subtract(Num2);
break;
case 'x':
Ans= Num1.multiply(Num2);
break;
case '/':
Ans= Num1.divide(Num2,2,Num1.ROUND_HALF_UP);
break;
default:
System.out.println("Can't do that - I'm only a cheap calculator");
break;
}
System.out.println("Answer is " + Ans);
}
}

Notes:

Have a look at the following line that appears just before the class header:
import java.math.*;
This is needed to tell the compiler to look for classes in the java.math package. If there are no
import statements, the compiler will only look for classes in the package that holds the class you
are working on, and in the java.lang package.

When calling the methods add, multiply etc, they are prefixed with the object name (Num1)
rather than the class name (BigDecimal). The rule is that the method name must be prefixed with
the object name, if one has been created from the class, or the classname where no object has
been created.

Writing classes from which objects can be created

Up to now, we have created objects from library classes. If you write a class that is to be used to
create objects, there are a few things that need to be included in the class. Objects consist of data
and methods. The class from which the object is created defines what data will be stored, and
what methods will be available for use with the object. It can also define constructors, which are
special methods used when creating a new object from the class. These classes will usually not
contain a main method.

The Instance Variables define the data to be stored by the object. Instance Variables are not the
same as local variables used by an objects methods.They are defined outside of any method,
usually at the front of the class. Whereas the local variables of methods do not retain their value
outside of the method, the instance variables are retained throughout the lifetime of the object,
and can only be modified by the methods of the object. They cant be modified by other classes.

They can be of any valid data type, and can also be objects themselves. They should always be
given the modifier private to enforce the encapsulation rule of OOP.

The following is an example of the definition of instance variables for a class named Loan:

class Loan
{
// * Instance Variables
// *********************

private String Customer;


private double CurrentBalance;
private double Rate;

methods etc. would be defined here


}
If an object is to be created from a class, it needs one or more special methods known
as constructors.

The purpose of a constructor is to place initial values in the instance variables. The constructor
method will usually require parameters, in order to be able to get the initial values from the
process which created the object.

The constructor method must have the same name as the class. Unlike other methods, it does not
have a return data type.

Many classes provide more than one constructor, in order to allow flexibility in the number and
type of parameters supplied. For example, if one of the parameters is a date, two constructors can
be provided, one of which requires the date as a parameter, and one of which defaults to todays
date.

Again, if one of the instance variables is an integer, two constructors may be provided. The first
will expect this parameter in the form of an integer. The second will expect the parameter in the
form of a string, and will convert it to an integer.

Since all constructors have the same name, being that of the class, the run time environment
decides which of the constructors to invoke, depending on the number and type of arguments
supplied.

The following example shows the constructors for the Loan class described in the previous
example. The first constructor expects the amount of the loan and the rate as data type double;
the second expects them as strings, and converts them to doubles.

public Loan(String Cust, double Amt, double Rt)


{

Customer = Cust;
CurrentBalance = Amt;
Rate = Rt / 100;
}

public Loan(String Cust, String Amt, String Rt)


{

Customer = Cust;
CurrentBalance = Double.parseDouble(Amt);
Rate = Double.parseDouble(Rt) / 100;

Public methods in a class can be used by the process which created the object in order to initiate
an action. Typically, these will include accessormethods, which return data stored in the object,
and mutator methods, which change the values of data stored within the class.

The return expression statement is used to return a value to the process which invoked the
method, eg
return Balance;
This should be the last logical statement within the method.

Additionally, a class may have its own private methods which may be called from within other
methods of the class, but may not be called from outside the class.
The full coding for the sample Loan class is shown below.

As well as the two constructor methods, Loan contains the methods:


MthlyInterest : Calculates monthly interest on the loan, adds it to the balance, and returns the
amount of interest calculated
Payment: Retrieves a payment amount as a parameter, and subtracts this from the balance
getBalance: Returns the balance

Heres the full code for the class Loan:

public class Loan


{
// * Instance Variables
// *********************

private String Customer;


private double CurrentBalance;
private double Rate;

// Constructors
// ***********

public Loan(String Cust, double Amt, double Rt)


{

Customer = Cust;
CurrentBalance = Amt;
Rate = Rt / 100;
}

public Loan(String Cust, String Amt, String Rt)


{

Customer = Cust;
CurrentBalance = Double.parseDouble(Amt);
Rate = Double.parseDouble(Rt) / 100;
}

// Other public methods


// *******************
public double MthlyInterest()
{

double Interest;
Interest = CurrentBalance * Rate / 12;
CurrentBalance = CurrentBalance + Interest;
return Interest;
}

public void Payment(double Pay)


{

CurrentBalance = CurrentBalance - Pay;


DateLastTran=new GregorianCalendar();
}
public double getBalance()
{

return CurrentBalance;
}

If you write a class that will be used to create objects, you will also need to write another class
that uses the object, so that you can test that it works correctly. Here is a program that tests the
Loan class by creating objects from it with sample data, calling its methods, and displaying the
results.

// *************************************
// public class to test the Loan class
// *************************************

public class loancalc


{

public static void main(String[] args)


{
double Interest, Balance;
Loan CarLoan = new Loan("Fred", "120000", "25");
Interest=CarLoan.MthlyInterest();
CarLoan.Payment(3000);
Balance = CarLoan.getBalance();
System.out.println(+ Interest + " " + Balance);
}
}

Try this out as follows: First, type in and save the loan class. Then create a new class
called loancalc, type it in, save it and run it.

Subclasses: Implementing Inheritance

Inheritance is one of the basic principles of OOP. Inheritance is said to implement an is-a
relationship between objects. For example, in a bank, an investor is a customer, and so is a
borrower. A class Customer could be used as a base class, or superclass, to deal with both types
of customer.

Each of them will, however, have additional data and methods unique to the customer
type. Subclasses could therefore be built from Customer to cater for investors and borrowers.
Since they will both need to use the original data and methods from Customer, they will inherit
these. Additional data and methods will be defined in the subclasses for the specific needs of
each type. They are therefore said to extend the superclass.

Lets look at how we code a class that is to inherit data and methods from a superclass. The class
header for a subclass HouseLoan which is to extend the Loanclass in the previous lesson would
be coded:

class HouseLoan extends Loan {}

Since additional data will be need to be stored, for example the serial number of the title deeds,
these must be defined at the front of the subclass. The instance variables defined in the original
class will be inherited, and need not be defined.
Constructors must be provided which will initialise these new instance variables. These
constructors will usually call the constructors from the superclass once they have initialised their
own variables; this is done by the statement

super(argument list). For example, the HouseLoan class may begin like this:

class HouseLoan extends Loan


{

private String TitleDeeds;


public HouseLoan(String Cust, double Amt, double Rt, String Deeds)
{
super(Cust, Amt, Rt);
TitleDeeds=Deeds;
}

public HouseLoan(String Cust, String Amt, String Rt, String Deeds)


{
super(Cust, Amt, Rt);
TitleDeeds=Deeds;
}

..}

Methods will be inherited from the superclass, so that it is not necessary to redefine them in the
subclass. However, in some circumstances subclasses may need these methods to work in a
different way. In that case, they can be written in the subclass using the same name as the method
in the superclass. The new method in the subclass will override or hide the method in
the superclass.

Additional methods may be needed in the subclass. They can be coded as normal.

The methods defined in the subclass will not have access to the instance variables stored in
the superclass. They can only be accessed by invoking the relevant methods of the superclass.

The full coding for the class HouseLoan, including extra methods for getting and setting the title
deeds, could look like this:

class HouseLoan extends Loan


{

<="" b="" style="color: rgb(0, 0, 0); font-family: 'trebuchet MS', sans-serif; font-size: 13.6px;
font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; line-height:
normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; white-space:
normal; widows: 1; word-spacing: 0px; -webkit-text-stroke-width: 0px; margin-left: 30.3906px;
background-color: rgb(255, 255, 255);">private String TitleDeeds;
public HouseLoan(String Cust, double Amt, double Rt, String Deeds)
{
super(Cust, Amt, Rt);
TitleDeeds=Deeds;
}

public HouseLoan(String Cust, String Amt, String Rt, String Deeds)


{

super(Cust, Amt, Rt);


TitleDeeds=Deeds;
}

public void setTitleDeeds (String deeds)


{

TitleDeeds=Deeds;
}

public String getTitleDeeds ()


{

return TitleDeeds;
}

Inheritance can occur over as many levels as required, for example class b can be written as a
subclass of class a, and inherit from it. Class c can be written as a subclass of b, and inherit all
data and methods from b, including those which it inherited from a. Class d could then be written
as a subclass of c and so on.

Unlike some languages, Java does not allow multiple inheritance. In other words, a subclass can
only extend one class, not many (although there may be several classes above it in the hierarchy).
However, sometimes it may be necessary to ensure that a group of classes have certain methods
in place. This can be achieved by using interfaces.

In the real world, there are many examples of interfaces which allow different components to fit
together. For example, an electric drill made by one manufacturer may be able to make use of
attachments supplied by another manufacturer, because the interface between the drill and the
attachments is the same in both cases. Interfaces in Java therefore define what must be present
for one component to succussfully work with another.

For example, the class util.Arrays contains a method named sort that can be used to sort a group
of objects held in an array. However, this will only work if all the objects in the array implement
an interface named Comparable. Classes that implement this interface must have a method
named compareTo that compares itself with another object, and decides which order they should
be placed in when sorted. The compareTo method must expect an object of classObject as an
argument(in fact, all classes implicitly extend class Object in Java, so this applies to objects of all
classes). To quote the Java documentation for the Comparable class, this method Returns a
negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the
specified object.

A class can be made to implement an interface by adding the phrase


implements interface_name to the class header. The class must then define all the methods that
are required by the interface.

A class Product that is to implement the Comparable interface may look like this:

import java.math.*;
public class Product implements Comparable
{

int productCode;
String description;
BigDecimal price;
public Product(int code, String desc, BigDecimal pr)
{

productCode = code;
description = desc;
price = pr;
}

public int getProductCode()


{

return productCode;
}

public int compareTo(Object p)


{

if(!p instanceof Product)) // See Note 1


return 1;
Product prod = (Product)p; // See Note 2
if(productCode < prod.getProductCode())
return 1;
else if(productCode == prod.getProductCode())
return 0;
else
return 1;
}
}

Note 1: The instanceof operator checks whether an object belongs to a specific class. Here, we
check that the object supplied to this method actually is of class Product. If not, we return 1, so
that all objects that are not products end up at the back of the list.

Note 2: If we simply coded this as


Product prod = p;
the compiler would mark it as an error, since the compiler sees p as being an Object, not a
Product. By prefixing p with Product in brackets, we are telling the compiler to assume that it is
a Product. This technique is known as casting.

Handling Exceptions in Java

There are many reasons why programs can have errors at run time. In many cases, these could
have been avoided if the programmer built proper checks into the program in the first place.

For example, bad input typed in by the user can cause all kinds of errors. If the program checked
the users input to ensure that it is within an acceptable range before attempting to use it, this
need not happen.

In other cases, the error can be caused by circumstances which cannot be avoided by the
programmer. A file needed by the program may have been accidentally deleted by a user, or the
system may have run out of memory.

In all cases of run-time errors, it is important to either deal with the error if possible, or shut the
program down with a meaningful error message and minimum loss of data if the error cannot be
dealt with.
In Java, if a method cannot complete normally, it throws an exception. The exception is an
object containing details of the problem that occurred. The exception can then be caught by
some other part of the program, known as an exception handler. This exception handler can do
one of several things, for example:

Fix the problem, if possible.

Release resources, for example close files etc, and propagate the error back to the Java
runtime environment so that the program is closed

Display a meaningful error message, and allow program execution to continue.

The programmer must decide what type of action is appropriate for each type of exception.

If an exception is not caught within the method that threw it, it is propagated back to the
method that called it. If it is not caught there, it is propagated back up the hierarchy until an
exception handler is found, or, if none is provided, back to the Java runtime environment.

Java provides a hierarchy of exception classes, all of which originate from the
superclass Throwable. Some of these can be thrown by the built-in Java classes. Some examples
of the predefined exception classes are listed below. A full list is available in the Java
documentation.

ClassNotFoundException
IllegalAccessException
IOException
EOFException
FileNotFoundException
MalformedURLException
ProtocolException
SocketException
UnknownHostException
UnknownServiceException

These exception classes include data, such as an error message which can be set by the
programmer, and several useful methods such as:

printStackTrace(), which prints a trace of where the error occurred, and the methods through
which the program arrived at that point

getMessage(), which retrieves the error message contained in the exception object.

Many of the methods of the Java library classes throw exceptions if they encounter unexpected
situations. The compiler wont allow you to ignore these exceptions you must do one of two
things. You can either propagate the exception in other words, pass it on for another method to
deal with, or catch it, and deal with it yourself. Well look at how this can be coded.

Propagating an exception: if you know that your method can throw an exception that it will not
handle, the compiler must be informed by adding the clausethrows exceptiontype to the end of
the method header, where exceptiontype is the class of the exception object which is thrown.

For example, a method that processes a file is always prone to exceptions. The method header
may be coded:

public void GetCustInfo(String Custno) throws IOException

Many of the methods in library classes do this, especially those that deal with file handling.
Any method that calls the GetCustInfo method must either catch the error or propagate it to the
next level up. If it is to be propagated, then the calling method must also specify throws
IOException in its own header.

Catching an Exception: This is done by enclosing the statements that may cause an error in
a try catch block, as follows:

try
{

statements that may cause an error .


}
catch (exceptionclass objectname)
{

statements that deal with the error


}

The exception class in the catch block must be either the one thrown by the statements in the try
block, or a superclass of it.

The statements in the catch block can use the methods associated with the object caught in order
to retrieve information from it, for example:

catch(IOException badFile)
{

System.out.println(badFile.getMessage());
badFile.printStackTrace;
etc
}

When an error is detected in the try block, control is passed directly to the catch block, and all
later statements in the try block are ignored.

The following example shows the Calculator program from a previous example modified to
include exception handling, so that if an invalid number is entered on the command line, a user-
friendly error message is displayed.

// ********************************************************
// * This program will carry out a calculation
// * entered on the command line. The calculation
// * should be entered as a number, followed by a
// * space, followed by an operand, followed by a
// * space and a number. Valid operands are +,-,x
// * and /.
// *********************************************************

public class calc


{

public static void main(String[] args)


{

double Num1=0, Num2=0, Ans=0;


char Op;
// *******************************************************
// Number format checking has now been included here
// *******************************************************
try
{
Num1=Integer.parseInt(args[0]); //First argument is a number
}
catch (NumberFormatException ex)
{
System.out.println (First No. was not entered in the correct format please try again);
System.exit(0);
}

Op=args[1].charAt(0); //First character of second


//argument is the operand
try
{

Num2=Integer.parseInt(args[2]); //Third argument is a number


}
catch (NumberFormatException ex)
{
System.out.println (Second No. was not entered in the correct format please try again);
System.exit(0);
}

// *********************************************************
// Decide on the correct calculation depending on
// the operand entered
// **********************************************************

switch(Op)
{

case '+':
Ans=Num1+Num2;
break;
case '-':
Ans=Num1-Num2;
break;
case 'x':
Ans=Num1*Num2;
break;
case '/':
Ans=Num1/Num2;
break;
default:
System.out.println ("Can't do that - I'm only a cheap calculator");
break;
}
System.out.println("Answer is " + Ans);
}

Congratulations! Youve now learned nearly all that you need to know to use the Java language.
However, Java programmers never stop learning. This is because there are so many Java classes
available for you to use in your programs.
You will need to get used to working with the Java documentation to find out how to use new
classes. You can also find a lot of useful demonstation programs in the demo directory that is
found underneath the directory in which Java was installed (In Windows, this is usually under
c:\Program Files\java). You can also visit the tutorials at www.java.sun.com to learn more.

For the rest of this tutorial, well have a quick look at some sample programs that use Java
library classes for different types of applications.
Creating a Graphic User Interface (GUI) for your program

Java provides a hierarchy of classes useful in creating GUIs. Its useful to have an idea of how
this hierarchy fits together, since classes inherit objects and methods from the classes above them
in the hierarchy.

The diagram below illustrates this hierarchy:

As you can see, everything in the hierarchy descends from the class Component. Component
has lots of useful methods, such as setBackgroundColor, setFont etc. Container, the next
class in the hierarchy, defines methods that are useful for maintaining a list of components
that the container stores. For example, a panel can contain text boxes, labels etc. The
Container class has methods such as add and remove.

The Window branch of the hierarchy contains classes that are useful in creating windows
(known as Frames), and the JComponent branch contains classes that can be used to create
the GUI components used in the window. These include buttons, labels, text boxes, scroll
bars etc.

The original version of the Java language used the package java.awt to work with GUIs.
However, this was revised later, and newer programs make use of the javax.swing package.
All of the classes beginning with J (Eg JFrame, JButton etc) belong to javax.swing. Many of
them extend classes defined under java.awt. Gui programs often have to import both
packages, as they may use classes from each.

There are many GUI classes which do not fit into this hierarchy, but which are used in
conjunction with screen components. These include:

Event objects e.g. ActionEvent. These are used to store information about a GUI event that
has occurred, for example, the user has clicked a button.

Clipboard is an object used to hold information that the user has copied to the clipboard.

Color stores the definition of a color.


Font stores the definition of a font.

Graphics stores the graphics context of a component, and has methods that can be used for
drawing on the component.

Image can be used to store an image in JPG or GIF format

Toolkit is used to interface with the users environment. It can be used for many things,
including loading images from a file.

Lets have a look at a simple GUI program that displays an empty window.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//
//* This is the public class, where program execution begins
//* ************************************************
public class GuiExample
{

public static void main(String[] args)


{
JFrame win = new EgWindow(); //Create a window
win.show(); //Display it
}
}
// //* This is the definition of the window, which extends JFrame
//* **************************************************
class EgWindow extends JFrame
{
//
//* The constructor for EgWindow
//* ***************************
public EgWindow()
{
setTitle("Example1");
setSize(400,300);
//
//* An inner class is defined as the window Listener
//* It is only interested in the windowClosing event,
//* which will shut down the program
//* *****************************************
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
} // Terminate the program
});
}
}

Notes:

Import statements are included for the AWT, AWT Events and Swing libraries

The public class creates an instance of the window,and shows it


The EgWindow class extends JFrame

Windows are affected by user-driven events, such as the window being closed or
minimized. If your program doesnt check whether the window has been closed, it
will simply hang. The addWindowListener method below registers an inner class as
a listener for window events.You can pretty much cut and paste this code into any
class that you write to work with JFrames.
addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e)


{

System.exit(0);

} // Terminate the program

});

When the window is closed, the program will terminate using the exit method of the
Java library class System.

This program produces a standard window as shown below. The user can move,
resize, maximize, minimize and close the window in the standard way.

Try it!

The next example shows how you can add another component into the window.
Building on this example, you can write your own GUI programs that use text boxes,
buttons, scrollbars and other things. This one just uses a simple JLabel to display
some text.

Components are never added directly to the window. The window has a Content
Pane that is used to store components. So this program first gets a pointer to the
content pane, then adds the label to it.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

//
//* This is the public class, where program execution begins
//* ************************************************

public class example2


{
public static void main(String[] args)
{
JFrame Example2 = new EgWindow2(); //Create a window
Example2.show(); //Display it
}

//
//* This is the definition of the window, which extends JFrame
//* **************************************************
class EgWindow2 extends JFrame
{

//
//* The constructor for EgWindow2
//* ***************************
public EgWindow2()
{
setTitle("Example 2");
setSize(150,120);
//
//* Get a pointer to the content pane, create a label
//* and add it to the content pane
//* *****************************************
Container MyContentFrame = getContentPane();
JLabel NiceDay=new JLabel(" Have a nice day!");
MyContentFrame.add(NiceDay);
//
//* An inner class is defined as the window listener
//* It is only interested in the windowClosing event,
//* which will shut down the program
//* *****************************************
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}

Well finish off on GUIs by having a quick look at how we can use the JPanel class
to play with drawing and graphics.

In order to do this, it is necessary to write a new class which extends JPanel, and
overwrite its paintComponent method. This method is called automatically by the
system whenever the component is drawn on the screen, either initially or after the
window has been minimised or hidden by the user.
The new paintComponent method receives the graphics context of the component
as an argument. This is as an object of class Graphics. This Graphics object can then
be used to draw the graphics. The first step in the method should be to
call paintComponent from the superclass in order to draw the rest of the object.

This is demonstrated in the following sample program.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
//
//* This is the public class, where program execution begins
//* ************************************************
public class example3
{

public static void main(String[] args)


{
JFrame Example3 = new EgWindow3(); //Create a window
Example3.show(); //Display it
}
}
//
//* This is the definition of the window, which extends JFrame
//* **************************************************
class EgWindow3 extends JFrame
{
//
//* The constructor for EgWindow
//* ***************************
public EgWindow()
{
setTitle("Example 4");
setSize(150,100);
Container Contents=getContentPane();
JPanel Panel = new PicturePanel();
Contents.add(Panel);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
}
}
//*
//* This class extends JPanel and includes some drawing
//* objects in the paintComponent method
// ***********************************************
class PicturePanel extends JPanel
{
public void paintComponent(Graphics Gr)
{
super.paintComponent(Gr);
Gr.setColor(Color.yellow);
Gr.fillOval(55,10,30,30);
Gr.setFont(new Font("Serif",Font.ITALIC,20));
Gr.drawString("Sunshine City",12,55);
}
}
The program output should look like this: