Vous êtes sur la page 1sur 104

Attribution-ShareAlike 2.

0 England & Wales

You are free:

• to copy, distribute, display, and perform the work


• to make derivative works
• to make commercial use of the work

Under the following conditions:

Attribution. You must attribute the work in the manner


specified by the author or licensor.

Share Alike. If you alter, transform, or build upon this


work, you may distribute the resulting work only under a
license identical to this one.
• For any reuse or distribution, you must make clear to others the license
terms of this work.
• Any of these conditions can be waived if you get permission from the
copyright holder.

Your fair use and other rights are in no way affected by the above.
This is a human-readable summary of the Legal Code (the full license).

At http://creativecommons.org/licenses/by-sa/2.0/uk/legalcode

Page 1
10 Aug 2005

Table of Contents
Chapter 01 Introduction........................................................................................................ 5
Who created this course ?............................................................................................... 5
This course.................................................................................................................. 5
Additional resources.................................................................................................... 5
What is Java?.................................................................................................................. 6
Where did Java come from? ........................................................................................... 6
Java is not JavaScript ..................................................................................................... 8
Quiz.................................................................................................................................. 8
Answers........................................................................................................................... 9
What is Java used for?.................................................................................................... 9
Why Choose Java?........................................................................................................ 10
The Java Development Kit............................................................................................. 10
Graphical Development Tools ....................................................................................... 11
Getting started................................................................................................................ 13
What do you get with the JDK?................................................................................. 14
What is a debugger?.................................................................................................. 15
Java: Compiler or Interpreter?....................................................................................... 15
Object Orientation.......................................................................................................... 16
Classes...................................................................................................................... 16
Methods .................................................................................................................... 17
Parameters............................................................................................................ 17
Return types.......................................................................................................... 17
Method signatures................................................................................................. 17
Inheritance .................................................................................................................... 17
An example of inheritance......................................................................................... 18
Illustration of inheritance with canines and felines..................................................... 19
Writing your first program............................................................................................... 19
Java is thoroughly case sensitive .................................................................................. 21
The error output under JDK 1.4................................................................................. 21
Line by line analysis of HelloWorld ............................................................................... 21
Why was that program so ugly? ................................................................................ 23
A Graphical HelloWorld ................................................................................................. 24
Line by line analysis of the graphical HelloWorld........................................................... 25
Quiz................................................................................................................................ 27
Answers......................................................................................................................... 27
Chapter 2 Syntax and Data Types.................................................................................... 29
Flow Control................................................................................................................... 29
if/else.............................................................................................................................. 30
Example of how if can be used.................................................................................. 30
The assignment operator............................................................................................... 32
While/do while................................................................................................................ 32
The for loop ................................................................................................................... 33
The break and continue statements? ....................................................................... 34
Data Types and variables.......................................................................................... 35
Method and class variables............................................................................................ 36

Page 2
Primitive Types......................................................................................................... 36
Size of Primitives. .......................................................................................................... 37
Character Data .............................................................................................................. 37
The String Class ............................................................................................................ 38
Java Keywords .............................................................................................................. 38
Swing AWT and SWT.................................................................................................... 39
The Metal (Java) Look and feel................................................................................. 40
The Windows Look and feel...................................................................................... 40
The Motif (Unix) Look and feel................................................................................... 41
SWT........................................................................................................................... 41
Java Applets and web browsers ................................................................................... 41
The Java Plugin......................................................................................................... 42
The Plugin Tray icon.................................................................................................. 42
Java Event Handling...................................................................................................... 42
Creating Events using Adapter classes......................................................................... 43
Quiz................................................................................................................................ 45
Answers......................................................................................................................... 46
Chapter 3 Layout Managers............................................................................................... 48
FlowLayout..................................................................................................................... 48
Flow, Border and Gridlayouts compared ....................................................................... 50
BorderLayout.................................................................................................................. 50
GridLayout...................................................................................................................... 51
Using multiple Layout managers in an application ........................................................ 53
Quiz................................................................................................................................ 54
Answers......................................................................................................................... 55
Chapter 4 Arrays and collections ..................................................................................... 57
Creating your own arrays .............................................................................................. 58
Assigning array values on creation ........................................................................... 59
The new for loop........................................................................................................ 60
The Limitations of Arrays .............................................................................................. 60
Collections...................................................................................................................... 60
Vectors....................................................................................................................... 61
HashMap.................................................................................................................... 62
TreeSet...................................................................................................................... 62
I/O and exceptions ........................................................................................................ 63
Exceptions ..................................................................................................................... 63
Using the throws keyword.......................................................................................... 66
Chapter 5 Applets and components................................................................................... 68
Swingset Screenshot................................................................................................. 68
Browser wars ................................................................................................................ 69
Applications vs Applets.................................................................................................. 70
Hello World ................................................................................................................... 71
Applet Lifecycle.............................................................................................................. 72
The applet console......................................................................................................... 72
Data Entry Fields and menus..................................................................................... 73
Menus........................................................................................................................ 74
Installing the Java Plugin .............................................................................................. 76
Java WebStart........................................................................................................... 76
Jar files...................................................................................................................... 77
Packing a Jar ............................................................................................................ 77
Unpacking a Jar ........................................................................................................ 77
Quiz............................................................................................................................ 77

Page 3
10 Aug 2005

Answers......................................................................................................................... 78
Chapter 06 More Objects................................................................................................... 80
OO Principles............................................................................................................. 80
A brief history of objects........................................................................................ 80
What is an object?................................................................................................. 81
Inheritance................................................................................................................. 82
Polymorphism............................................................................................................ 83
Example PolyUpdate............................................................................................. 84
Constructors............................................................................................................... 85
Overloading Constructors.......................................................................................... 85
Overriding and overloading........................................................................................ 86
Why Interfaces?......................................................................................................... 87
Using Interfaces......................................................................................................... 87
Abstract Classes ....................................................................................................... 88
Encapsulation............................................................................................................ 89
Objects and references ............................................................................................. 90
Quiz................................................................................................................................ 91
Answers................................................................................................................. 92
Question 3........................................................................................................................92
Question 4........................................................................................................................92
Additional Reading..........................................................................................................92
What is an Object (Sun Java Tutorial).............................................................................92
Appendix........................................................................................................................ 93
Topics Not Covered in this book.................................................................................... 93
Threading................................................................................................................... 93
JDBC.......................................................................................................................... 93
Servlets and JSP....................................................................................................... 93
Enterprise Java Beans............................................................................................... 93
J2ME/Mobile Phone Java.......................................................................................... 94
Book Recommendations................................................................................................ 94
Headfirst Java ........................................................................................................... 94
Just Java ................................................................................................................... 94
Mughal and Rasmussen ........................................................................................... 94
Thinking in Java (3rd Edition).................................................................................... 94
Website Recommendations........................................................................................... 95
How this book was created............................................................................................ 95

Page 4
Chapter 01 Introduction
10 Aug 2005

Chapter 01 Introduction
Who created this course ?
This course was created by me Marcus Green.

I have been involved with Java since around 1998, when I put together what
became http://www.jchq.net one of the most popular web sites aimed at people
studying for the Sun Certified Java Programmers exam. I have been a programmer
since around 1990 and have used C/C++, Visual Basic, Perl, Java and various
other programming tools. I am a qualified teacher with a Post Graduate Certificate
in Education (PGCE) specialising in adult education. At the time of writing I teach
at York College of Further Education in Yorkshire UK

This course
This course is for people who want to learn about Java but have little previous
programming experience. It is not aimed at the Sun Certified Programmers Exam,
which is for people who already know how to program in Java.

If you have ever modified an Excel Macro by hand or done a little Visual Basic
programming or even a little JavaScript then this course could be for you. If you
have absolutely no previous programming experience you can probably still do the
course but it might be more of a challenge.

Additional resources

There are several freely available tutorials on learning Java. I have included several
links to the tutorial from Sun, and you can see the main page at
http://java.sun.com/docs/books/tutorial. Bruce Eckel has written a good, if quite
dense book on Java which you can either purchase a printed copy, or download an
electronic version from http://www.mindview.net/Books/TIJ. Dick Baldwin has some
excellent Java material available at http://www.dickbaldwin.com/tocint.htm.

Page 5
Chapter 01 Introduction
10 Aug 2005

What is Java?
Everything that runs on a computer starts out as code for in a programming
language, a sequence of text and numbers that tell the computer what to do. Java
is a programming language created by Sun Microsystems
(http://www.java.sun.com) and available for free download over the Internet. It has
been available since the beginning of 1996 and has aroused huge interest both as
a general programming language and for its Internet capabilities. It is one of the
most highly sought after skills, both in industry and universities. Programs
developed with Java can be sold (or given away) without paying anything to Sun
Microsystems.

Java is one of the most sought after skills, both in business


and in universities.

One of its exciting features is that programs written in Java can run on many types
of computer without modification. Thus a program written on a Windows computer
can be run on a Apple Macintosh a Linux or a Unix computer. Sun created the
slogan “Write once, run anywhere” to describe this ability. As well as general
purpose programs Java is used extensively for "Server Side" web programming,
where the programs run on the web server and the user just sees the pages using
any web browser. Versions of Java are also available from other organisations,
notably from IBM, and Java has become the de-facto standard for downloadable
games for mobile phones.

Where did Java come from?


The origins of Java can be traced back mainly through the C and C++ languages.
The C programming language was one of the first "Portable" languages, meaning
that it could run on many different types of computer. The C++ language was like C
but included the ability to create classes, one of the central ideas behind Object
Orientation. The designers of Java decided to take advantage of the number of
users who understood C++ and designed the language to be easy for C++
programmers to use.

Java was designed to be easy for C/C++ programmers to learn

Although C and C++ programs could be portable, they needed to be re-compiled for
each system that they were to run on. Thus the executable program created for a

Page 6
Chapter 01 Introduction
10 Aug 2005

Linux computer could not run directly on a MS Windows computer. Although it may
sometimes seem that “everyone runs windows”, if you consider that a modern
smart mobile phone is a sophisticated computers there are probably more mobile
phones than desktop computers and the increase in the number of “embedded
devices” such as Personal Digital Assistants is faster than that of desktop
computers.

To be able to run on a different machine such programs needed to be re-compiled


for the target machine. This could often be a complex and error prone process. By
contrast, Java programs are what is called binary portable.

Java programs are binary portable, they run on different


platforms without re-compilation.

Thus the output of the compilation process can be run directly on target machines
with no further intervention.

Page 7
Chapter 01 Introduction
10 Aug 2005

Java is not JavaScript


Javascript was originally developed by Netscape under a different name as a
lightweight scripting language embedded in the browser. Unfortunately it was
decided to rename this technology as JavaScript which has caused huge amounts
of confusion. JavaScript is embedded within web pages as plain text and is
generally visible to anyone who knows how to look at the page source code. When
used with web pages Java is used in the form of applets, and the source code is
not visible to people browsing a web page.

Quiz
1) Which of the following statements are true?

a. IBM produces its own version of Java


b. Java programs can run on any platform that supports Java without re-compilation
c. Java is only available from Sun Microsystems
d. Java programs can run on any platform once that have been re-compiled

2) Which of the following statements are true?

a. Java is used to create games on mobile phones

Page 8
Chapter 01 Introduction
10 Aug 2005

b. Java is only available for client programming, not web server programming
c. Java was designed to be easy for C and C++ programmers to learn
d. Java is a more fully featured version of the JavaScript language

Answers
Question 1

a. IBM produces its own version of Java


b. Java programs can run on any platform that supports Java without re-compilation

Question 2

b. Java is used to create games on mobile phones


c. Java was designed to be easy for C and C++ programmers to learn

What is Java used for?


In the early days of Java it was assumed that the main use of Java would be as
applets, small Java programs embedded in web pages. Applets offered the benefit
of a fully fledged programming language allowing developers to embed just about
any functionality. A combination of performance issues and lack of standardisation
has hampered the widespread adoption of Applets in web pages, yet Java has had
enormous take up as a programming languages in other areas.

One of the most significant (and not widely predicted) uses of Java is for Server
Side web programming, or the creation of Web applications.

One of the most significant uses of Java is for Server Side Web
programming, with Servlets, JSP and EJB technologies

This is very different from the original focus on applets as the resultant applications
generally run exclusively on the server and thus (within reason) will run on any
browser. The web browser (Netscape, IE, or Opera for example) sees a series of
standard HTML forms and is unaware of what programming language is running on
the server.

This is in significant contrast to Applets where the web browser needed to be


configured up to run the right version of Java. Web applications are a huge area of
growth with such Java technologies as Servlets, JSP and Enterprise Java Beans
(EJB). Servlets and JSP are usually compared with Microsoft ASP and the Open
Source PHP technology.

The database vendors have a huge need for portable software. Imagine you are

Page 9
Chapter 01 Introduction
10 Aug 2005

running Oracle or Informix corporations and you need to develop for Windows XP
plus heaven knows how many flavours of UNIX. This is probably why several of the
Database Vendors (Oracle and Sybase to name two) have decided to embed Java
virtual machines into the heart of their Database systems. Since the release of
version 8.1 of Oracle a Java programmer has suddenly come a long way to being
an Oracle programmer.

Why Choose Java?


Java is suited to creating general business programs rather than low level drivers,
performance critical or operating system code. Typically it is used for accessing
databases or writing networking systems. Some of the main alternative languages
to Java are C++, Visual Basic and the new language from Microsoft called C#. You
will sometimes see a description of a language as C/C++ because C and C++ are
closely related. C++ compilers will generally compile any valid C language but most
developers take advantage of the Object Oriented nature of C++.

C++ has a reputation for being able to create lower level programs than Java or
Visual Basic and so is a natural choice if you are programming drivers or anything
that involves getting "close to the metal" where performance is at a premium. Most
programming is not of this type however and C++ does not come with a standard
set of libraries for creating graphical programs. The main libraries for creating
graphical programs are the Microsoft Foundation Classes (MFC), but selecting
MFC will restrict portability. C++ and MFC are generally considered much harder to
learn than either Java or Visual Basic.

There are two very different versions of Visual Basic, VB classic, i.e. Any version
before VB6 and VB.NET. VB.NET shares some of the object oriented concepts of
Java, whereas VB classic is far more like “traditional” programming languages like
Pascal and C. VB is probably slightly easier to learn than Java and although it is
strictly a Windows platform it comes with tools for most of the popular business
requirements. It can can connect to most databases, and can create most types of
graphical widget required for standard business applications. VB classic suffers
from its heritage as a descendent of the original BASIC programming language in
that the primary purpose of the original language was that it should be easy to use,
rather than being optimised for software engineering.

The C# language is the joker in the pack when selecting a language because
Microsoft recognised that Java included some very good ideas and "borrowed"
many of the concepts to produce a new language that blended many of the virtues
of C++ and Java. Although there are projects to make C# available (notable the
Mono project) on platforms other than Windows, the main platform at the moment
is Windows and for commercial purposes it should probably be considered non
portable. The good news is that C# is sufficiently like Java that if you learn the one
it will not be hard to learn the other. By contrast Visual Basic has very little in
common with C/C++ or C#.

Page 10
Chapter 01 Introduction
10 Aug 2005

The Java Development Kit


The standard tool for developing Java programs is Suns Java Development Kit or
JDK. This is freely downloadable from the Sun website and is updated according to
the current version. So for example at the time of writing the current version is
JDK1.5 The current version number is often represented as a point release, i.e.
JDK1.5.0.1. The JDK is under constant development and each new release brings
new features, performance and bug fixes, so it is generally a good idea to download
the latest version.

The JDK is a a very "bare bones" tool that expects you to work from the command
prompt, i.e. That black box under Windows that runs cmd.exe or possibly
command.com.

There are several more friendly development tools with the sort of menus, windows
and prompts that you expect from a modern program. These types of tools are
sometimes called Integrated Development Environments or IDE, and they can
include debuggers and visual design tools that allow programs to be created using
"drag and drop". One of the problems with this type of graphical tool is that the
interface can "get in the way" of understanding what is happening. To start off with
the examples will assume you are using the JDK from the prompt and using a plain
text editor such as notepad under windows or vi under Linux/Unix.

Graphical Development Tools


If the thought of using the command prompt really does sound too troubling for you,
don't worry, you can download a free graphical tool with the kind of menus, help
and prompts you would expect from a modern system. There is more than one of
these type of tools available, but I am going to recommend NetBeans from
http://www.netbeans.org . Netbeans itself is a Java program and so will run on
many different types of computer from an Apple Macintosh, a Windows machine to

Page 11
Chapter 01 Introduction
10 Aug 2005

a Linux or Unix machine.

Other graphical development tool are the free eclipse IDE from
http://www.eclipse.org and in the commercial region there is Jbuilder from Borland
http://www.borland.com

One of the features I expect from a good development environment is “code


completion”. This is where the editor has a built in knowledge of the supporting
classes and offers suggestions to help you complete each line of code. The
following screen shot illustrates how NetBeans pops up a list of the possible
methods that are available to the System.out. Class.

Page 12
Chapter 01 Introduction
10 Aug 2005

Since I started writing this course I have discovered a very nice looking minimal
development environment called Dr Java. It combines the virtue of simplicity and
the essential functionality for learning Java, the ability to compile, debug and syntax
highlighting, you can find out more at http://drjava.sourceforge.net/

Getting started
Summary

Go to java.sun.com and download the latest version of the JDK for your operating
system.

For the purpose of this book the version of Java you need is called Java2 Standard
Edition (J2EE). The naming convention for Java is very confusing, because the
names used seem to vary according to who is writing about it within Sun. Thus the
version at the time of writing is called both Java 5 and Java2, but the development
kit is called JDK1.5. Because the JDK naming convention seems to have been
most consistent I'll refer to that.

The home page for J2SE is

http://java.sun.com/j2se/

Unfortunately Sun seems to change the pages quite a bit for downloading Java but
the J2SE homepage has a popular downloads section on the right hand side that
will usually indicate the latest greatest and most popular version. Once you select
this option itcan still be slightly confusing as the most prominent link tends to be the
bundled combination of the NetBeans IDE and the JDK. I am recommending you
go for the plain JDK, as working with NetBeans is a whole additional set of learning,

Page 13
Chapter 01 Introduction
10 Aug 2005

even though it is a very powerful and impressive tool.

The JDK download is available in either an online or offline version. I recommend


the offline version as this downloads all required files and can easily be transferred
to another machine. The online version is simply a small “stub” program that
performs the download. The actual JDK download for Windows is a standard
executable (i.e. An .exe program). You will need either a good Internet connection
or plenty of patience as the JDK is over 50 megabytes. Once installed the JDK
expands significantly. The version I installed at the time of writing occupied around
180MB of disk space.

I also recommend you download the API documentation, which is a separate


download to the JDK. The API documentation is in the form of HTML files and is an
excellent technical guide to how to use the code and classes in the language, but
again it does occupy a reasonably significant amount of disk space. You can also
view the contents over the web at

http://java.sun.com/j2se/1.5.0/docs/api/

Java API Documentation

Page 14
Chapter 01 Introduction
10 Aug 2005

What do you get with the JDK?

As you can tell from the amount of disk space it occupies the JDK contains a lot of
files. From a user perspective the two most important programs in the JDK are

javac.exe (the java compiler)

and

Java.exe (starts the jre)

The Java compiler is the program that converts source code (the text you write
when you create a program), into the bytecode that runs through the Java runtime
environment. The output of the compilation process is a file with the extension
*.class. Once you have a *.class file you no longer need the source code (*.java)
file.

Before it generates the bytecode the compiler checks that the code is correct. For
example it checks that every opening brace { is matched with a closing brace }.
Once your operating system has associated files with the extension *.class it should
be possible to click on them to start running.

The JDK also supplies a program called jar.exe which will wrap up multiple *.class
files into a single file with the extension *.jar, which the java.exe program will run in
the same way as a *.class file.

In addition to the compiler the JDK includes 35 other executables including a


debugger and decompiler, but in over five years of intense use I have hardly ever
used any of those programs. Debuggers are very useful tools to programmers as
they allow you to track down errors in the logic of your program. Unfortunatly the
debugger has the interface from hell, and there are many alternative and useable
alternative debuggers, notably the one that ships with the NetBeans IDE, and the
Dr Java development system. It seems unfortunate that they did not make the
debugger in the JDK a little easier to use, as installing NetBeans seems an
excessive amount of time trouble and effort to get this ease and functionality.

What is a debugger?

A debugger doesn't magically remove the bugs from a program, but it is very useful
in tracking them down. A debugger is a program that allows you to run a program
“in slow motion” and to step through the source code line by line to see what effect
each line has on the program. Debuggers are available for most programming
languages. I have used Java debuggers in many different development
environments, some free and some paid for. Out of these the one in NetBeans is
easily my favourite, partly because of its easy to understand graphical interface.

Page 15
Chapter 01 Introduction
10 Aug 2005

The NetBeans debugger allows you to set a breakpoint, this is where the debugger
stops the program when a certain condition is met. For example if you were looping
through several thousand records in a database you might want the program to
stop after one thousand records or where the first surname called “smith” was read
from the database. Because a production program may have large numbers of
variables the debugger allows you to specify what variables you want to watch.

Java: Compiler or Interpreter?


This is somewhat non essential background information, but it does put into
perspective some of the design and performance considerations. An interpreted
language is one where another program reads in the source code each time the
program runs. That other program is the interpreter. The process of reading the
source code inevitably places an additional performance overhead and as a result
very few commercial programming languages are interpreted.

A true compiler generates code that can be natively executed by the computer (or
at least the operating system). In the windows environment the output of a compiler
will have the extension *.exe (think executable). Java is a byte code compiler, the
output is an executable that can be understood by a “virtual machine” that runs as a
separate process on the target computer. This approach gets rid of the overhead of
reading and interpreting the source code each time the program runs, but it still has
the overhead that it needs the runtime environment to allow the program to run.
The biggest overhead is the start up of the runtime environment, which means a
Java program will generally be slightly slower than the equivalent compiled
program.

Object Orientation
Java is an Object Orientated (OO) programming language. Part of the philosophy
behind Object Orientation is that programmers should be able to use off-the shelf
components in the same way that engineers do in the real world. Thus when an
electronics designer decides to create a new graphics card, or washing machine
controller they don't create every integrated circuit from scratch. They generally use
off the shelf components with some custom configuration.

In the world of software design there has been a long and rather unfortunate history
of constantly "re-inventing" the wheel. It seems that there are a million ways of
performing common programming tasks such as searching, and sorting. If
programmers could re-use off-the shelf components they could get on with the real
creative part of software creation rather than getting bogged in the low level details.

Classes

Object Orientation in Java (and most language) is performed using the concept of
classes, self contained bundles of code and data that have their own “behaviour”. A
class is a template for creating an "instance" or Object based on that template. You

Page 16
Chapter 01 Introduction
10 Aug 2005

can think of classes as a way of creating your own data types. In older languages
such as C or Pascal you had pre-defined types such as int or float. In Java you can
define your own types that wrap up both data and code, and you can use classes
that come with the Java language or those provided by other programmers. For
example when you are creating a graphical interface and you needed to create a
button you you could create an instance of the JButton class and take advantage of
the data and functionality that comes with it. It is important to understand the
difference between a class and an instance of a class.

If you consider a class as the blueprint or plan for an computer, you may see how
that plan can be used to create multiple instances of the computer. The details of
each instance may vary, for example you might create a version with different
amounts of ram and different operating systems but each instance is created from
the same plan. In the same way a Java class can be used to create multiple
instances, each instance may have different attributes at runtime.

Methods

The "behaviour" of an object is set up in its methods which are callable chunks of
code in a similar way to subroutines in structured programming languages such as
C or Pascal. The difference between a method in Java and a function in C is that in
Java the method belongs to the instance of a class, whereas in C a function
belongs to the currently running program. If you are new to Object Orientation the
terminology can be a little confusing at first but it soon becomes second nature. In
Java every object is a descendent of a great grandparent class called Object. The
use of methods is sometimes referred to as “sending a message to an object”, a
terminology I do not find particularly helpful, but it is widely used.

Parameters

If a method is the means of sending a message, then the contents of the message
are the parameters sent to a message. When defining a method the possible
parameters are called the arguments. The terms arguments and parameters are
easily confused, but parameters are the actual values sent, whilst the arguments
are the possible values. When defining a method each argument must be given a
data type and a name. The purpose of giving a data type is to ensure that only the
right type of parameter is passed at runtime. Thus if a method is defined as
expecting a String it cannot be passed a number by mistake.

Return types

The return type of an object is the way a method brings information back to a
calling object. Every method definition mus also have a return type. If no data is to
be returned from a method then it must be marked as having a void return data
type. A method can only have one return type.

Page 17
Chapter 01 Introduction
10 Aug 2005

Method signatures

The combination of method name, parameters and return types are known as the
method signature. The following are some examples of method signatures.

Void amethod(int iage){}

int amethod(int iage, String name){}

Objects as defined by sun


http://java.sun.com/docs/books/tutorial/java/concepts/object.html

Inheritance
The use of inheritance in Object Oriented languages allows you to take an object
and create a new version of it that inherits its functionality, and then add your own
modifications. The programmer does not need to understand, or even have access
to the source code of the object that is being inherited. An analogy might be a
custom car designer who uses a circuit board for controlling some aspect of the
engine performance. The component can be added in like a "black box" with its
external functionality understood, but with no knowledge necessary of exactly how it
implements the functionality within the box.

In addition to being able to re-use existing component in your source code, Java
development tools allow you to re-use visual components. If you have ever seen a
development environment like Visual Basic or NetBeans you will be familiar with
idea of a "palette" of tools that can be dragged and dropped onto a form and then
the programmer changes properties to suit the current use.
Text 1: NetBeans Tool Palette

Illustration 1:

Sun invented a technology it calls JavaBeans to allow this to happen, so


programmers can drop a control such as a button or text box onto a form and then
modify features such as the size or color without having to look at the underlying
code of the Object.

Page 18
Chapter 01 Introduction
10 Aug 2005

An example of inheritance

The following diagram illustrates the idea of inheritance. Both Canine and Feline
are sub classes of Animal. They share common characteristics. Tiger and Lion are
sub classes of the class Feline. This style of diagram with an arrow going from the
sub class to the parent class is based on UML or Unified Modelling Language. UML
is an entire subject of its own, and I will not be going into any more detail than to
occasionally using the diagramming conventions. You can find out more about UML
at http://uml.tutorials.trireme.com/

Illustration of inheritance with canines and felines

Writing your first program


The traditional way to start learning a programming language is by creating a small
program that simply sends the string "Hello World" to the console (the command
line, or DOS window in Windows 98/ME/2000 or XP. I will be assuming that you are
using the naked JDK with a simple editor such as notepad.exe, that comes with
Windows. If notepad is a little unexceptional you might like to consider notepad2
from www.flos-freeware.ch which is a “drop in replacement” for windows notepad
but also includes some programmer specific features such as color syntax
highlighting. The editor has a built in knowledge of the syntax of Java and colors
the keywords accordingly. Whatever editor you use it must be able to save files with
the extension .java.

If you are running a version of Windows and are not familiar with the console,
chose the start menu, chose run and if you are on Windows 2000 or XP type cmd,

Page 19
Chapter 01 Introduction
10 Aug 2005

if you are on Windows 95/98/ME type in "command". You will then see the black
window of mystery that is the command prompt, or console. If you type in notepad
you will see a real windows program start which is the minimal editor that ships with
just about all versions of windows.

Create a file called HelloWorld.java. and enter the following code.

public class HelloWorld{


public static void main(String argv[]){
System.out.println("Hello World");
}
}

Note that the body of the main method is indented, i.e. Is set further to the right
than the rest of the text. Indenting code makes no difference at all to the Java
compiler or to the final program, but it can make code much easier for a
programmer to understand. By indenting code it is possible to see where a block of
code, a method or a loop begins and ends.

Now compile the code by typing

javac HelloWorld.java

If there are no problems you should return to the prompt without seeing any
confirmation message. You may get an error message saying something like

public class Helloworld must be defined in a file called "Helloworld.java"

This indicates that the name of the class in the file does not exactly match the
name of the file containing the code. This is because Java checks that the case of
the letters in the file name matches the case of the letters in the class name. This
can seem a little odd if (like me) you are used to the DOS/Windows platform where
the case of a file name has almost no significance. Checking the case of letters is
the first thing to examine when you have an error, particularly when you are first
starting to work with Java. Make sure you have the semi colon at the end of the
System.out... line.

If you get an error indicating that the system knows nothing about Javac then you
may have to investigate the path setting in your system. This should be set to
include the location of the Java binaries (the programs that actually make it go). On
a Windows system these files are typically kept in a directory called something like

c:\jdk1.5\bin

If you have managed to compile up the program without error, do the DOS dir
command to see what files have been produced.

You should see a new file has been created called

Page 20
Chapter 01 Introduction
10 Aug 2005

HelloWorld.class

The class file is what will actually be run. To run it you type

java HelloWorld

More information on creating your first program can be found at

http://java.sun.com/docs/books/tutorial/getStarted/cupojava/win32.html

Java is thoroughly case sensitive


This program should now output the string "HelloWorld" to the console. Note that
you only typed the name of the class file and did not give the .class extension, even
though you had to give the .java extension when you compiled the program. If the
code in your class says

public class HelloWorld

But you typed

java Helloworld

On the command line, you will get an error. I can't emphasise enough that Java is
thoroughly case sensitive.

Page 21
Chapter 01 Introduction
10 Aug 2005

The error output under JDK 1.4

Line by line analysis of HelloWorld


If you recall the code for the HelloWorld program was

public class HelloWorld{


public static void main(String argv[]){
System.out.println("Hello World");
}
}

To take the first line of the program

public class HelloWorld{

The keyword public indicates that this class will be visible from anywhere. This is
known as an access modifier. Later you will learn about the modifiers private and
protected. The keyword class indicates that this is the start of the most basic
building block of Java. Classes are sometimes defined as

an aggregate of data and executable code

The executable code that in other languages might be called functions or


subroutines are called methods in Java. The next line is an example of a method.

public static void main(String argv[]){

Page 22
Chapter 01 Introduction
10 Aug 2005

There is a certain "magic" about the main method in Java in that it is the place
where execution of any application starts. The main method must always have the
same format or signature as in this example.

The keyword public has a similar meaning for a method as for a class. It indicates
that the method can be called from anywhere. The keyword static indicates that this
method can be called without creating an instance of the class. If that means
nothing to you, don't worry about it as it will be explained later. The keyword void
indicates that this method will return no value. The name of the method is main. A
method can be given any any name so long as it begins with a non-numeric
character and does not contain spaces. You can start a method name with a dollar
sign, but I wouldn't recommend it.

The parameters for the method are contained within the parenthesis, in this case

(String argv[])

This indicates that when the method is called it must be passed a String array. An
array is a collection of elements all of the same data type. In this case we have an
array of the type String. The Java Virtual Machine fills this array with any
parameters passed to the program on the command line. This is often how
programs are started in the world of Unix and older DOS programs but is not so
common with GUI based programs. If you were to start the program with the
command line

java HelloWorld one two three

The argv array would contain the Strings

"one" "two" "three"

which the program could then access, you could print out the first argument to the
program (the first text after the program name) with a line as follows.

System.out.println(argv[0]);

See how the first element is zero and not one.

Note that the data type String begins with an upper case letter S. Note that the
parameter name argv[] is just a convention, it would be just as correct to create a
main method as

public static void main(String foo[])

However it is a good idea to stick to the convention of calling the parameter argv[]
to make your code easily understandable.

System.out.println("Hello World");

Page 23
Chapter 01 Introduction
10 Aug 2005

This is a call to the static method

System.out.println.

Note the use of the dot notation. This means that println is a method of the class
out that is a child of the class System. The System class is a low level class that
any program can have access to at any time. The println method expects to receive
a string for a parameter and in this case I have obliged by passing the "Hello World"
string I want to send to the console. Note how the line is terminated by a semi colon
as you would do in C/C++.

The next two lines simply consist of closing curly braces. The first one indicates the
closure of the main method and the next indicates the end of the class. Note how
the end of the class does not require a semi-colon.

Note that you can insert blank lines, tabs or space characters just about anywhere
on a Java program, and it is a good idea to use them to make your code readable.
Although the readability of your code may not seem important when you are first
learning to program, it is a very good idea to get in the habit of creating readable
code right from the start. Sooner or later every programmer reads code that makes
them ask the question “what fool wrote this”. Sooner or later it will turn out that the
answer is “oh dear I wrote it myself only six months ago, I wish I had made

Why was that program so ugly?

You did not decide to learn Java so you could write strings
to the console like some 1960's science fiction drama.
Where are the web based graphics and GUI windows and
menus you have come to expect?

From the very first release Java came with a standard set
of libraries for creating graphical applications that have an
appearance similar to modern GUI style programs that
you would expect in an environment like the Macintosh or
MS Windows.

This is a significant contrast to older programming languages where the "out of the
box" experience was the text interface with various non standardised libraries
available for creating graphical applications. Delightful though it is to create
windows, buttons and components the things that make the programs actually go
can be developed and tested in a purely text environment. It is also useful to keep
the graphical interface and the "back end" functionality separate.

But to fast forward from an era of kipper ties and excess facial hair we need to get
a demonstration of a better looking program than the text version of HelloWorld.

Page 24
Chapter 01 Introduction
10 Aug 2005

The simplest way to demonstrate a graphical Java application is to create a simple


Frame and then add a button to it.

A Graphical HelloWorld
Fire up your favourite editor and create the following code in a file called
HelloAp.java Remember as ever, Java is utterly case sensitive.

/* HelloAp */
// A Single line comment
import javax.swing.*;

public class HelloAp extends JFrame{


public static void main(String argv[]){
HelloAp helloap = new HelloAp();
helloap.go();
}
public void go(){
JButton button = new JButton("Hello");
getContentPane().add(button);
setSize(100,100);

setVisible(true);

}
}

Compile this code by typing

javac HelloAp.java

You are now ready to test your first graphical Java program. From the command
prompt type

java HelloAp

This is a screen shot from this code running under Linux, the result under Windows
should be similar.

Page 25
Chapter 01 Introduction
10 Aug 2005

Line by line analysis of the graphical


HelloWorld
/* HelloAp */
// A Single line comment

These two lines are comments, text put into the program to explain the code not to
actually change how the program works. The first line using the /* version of
comments means the comment will continue until it is closed by a matching */ set of
characters. The second version // is a comment that stops at the end of the line.

import javax.swing.*;

These lines tell the compiler that you will be using these classes. Although this can
seem a bit like the use of the

#include

pre-processor directive in C/C++, it is actually more like the DOS path statement. If
that doesn't mean anything to you don't worry right now. The import directive
statement is used to integrate Java classes already in existence. In this case

javax.swing.*;

is a reference to the Swing classes. This contains the basic Graphic components
such as buttons, frames, labels, etc. etc.

public class HelloAp extends JFrame{

This line is similar to the line in the stand alone code that declared the HelloWorld
class. The important difference is the part that states

extends JFrame

The keyword extends means that this class will extend an already existing class.
This actually means

extends javax.swing.JFrame

But because of the import statement at the start of the program you do not need to
specify the javax.swing part of the JFrame class name. This is part of the Java
inheritance mechanism. By extending the Frame class this new class will obtain
the functionality of the Frame class such as the ability to add components and
repaint itself.

The main method has a line to create a new instance of the HelloAp class, this is
because the main method is static and we need a new instance from which to call
instance methods. Once an instance has been created the go method is called to

Page 26
Chapter 01 Introduction
10 Aug 2005

start the program running. The choice of the method name go is entirely arbitrary.

The go method starts by creating an instance of the JButton class, which as you
can guess from its name acts like a button, i.e. it can be clicked and can have a
label indicating what it is to be used for. In this example we don't actually program
the button to do anything.

JButton button = new JButton("Hello");

This line is to create a new instance of the Button class. Note that the program
knows about the Button class because of the line

import javax.swing.*;

at the start of the code. The asterisk (*) means make all of the classes from the
Swing classes available. For the purposes of this program it would also be
acceptable to have the import declarations as

import javax.swing.JFrame;
import javax.swing.JButton;

The JButton has been sent the String "Hello World" as part of its constructor
(initialisation code).

The next line reads

getContentPane().add(button);

The important bit of this line is the call to the add method. This adds the button to
the current class instance. The last two lines set the size of the frame and then ask
it to display itself. Note that the final closing brace is not terminated with a semi
colon.

This graphical HelloAp is the basic structure of most Java graphical applications.
Most applications involve creating a Frame, adding components such as menus,
buttons, labels and text entry fields and then processing the events that happen
when the user uses the mouse or enters data.

Quiz
1) Which of the following statements are true?

a. Java was invented by researchers at IBM


b. Java is only available for MS Windows
c. The first version of Java was released in 1985
d. Java was invented by researchers at Sun Microsystems

2) Which of the following statements are true?

Page 27
Chapter 01 Introduction
10 Aug 2005

a. Java is the implementation of JavaScript from Sun Microsystems


b. Java can only be used to create applets within a web browser
c. The source to Java applets can be viewed within the code of a web page
d. JavaScript is another name for Java
e. Not all browsers can display Java Applets by default

3) Which of the following statements are true?

a. Java uses inheritance as part of its implementation of Object Orientation


b. To extend a class a programmer must have access to the source code
c. Java is particularly suited to low level programming such as device drivers
d. Java is suitable for general business applications such as accessing databases.

4) Which of the following statements are true?

a. Java is a derivative of the BASIC programming language


b. Java programs can be run on multiple platforms without re-compiling
c. Java was designed to be easy for C++ programmers to learn and use
d. Java programs need to be re-compiled for each platform they will run on.

5) Which of the following statements are true?

a. The Java tools from Sun are called the Developers Kit for Java (DKJ)
b. The Java tools from Sun are called the Java Developers Kit (JDK)
c. The NetBeans tools offer a graphical development toolkit
d. Javabeans can be used to create pallets of re-usable visual components.

Answers
Question 1

d) Java was invented by researchers at Sun Microsystems


But IBM have a very large commitment to Java

Question 2

e. Not all browsers can display Java Applets by default


Some browsers offer it as one of the options (e.g. Opera) but most require the
installation of the Java Plugin

Question 3

a. Java uses inheritance as part of its implementation of Object Orientation


d. Java is suitable for general business applications such as accessing databases.

Question 4

Page 28
Chapter 01 Introduction
10 Aug 2005

b. Java programs can be run on multiple platforms without re-compiling


c. Java was designed to be easy for C++ programmers to learn and use

Question 5

b. The Java tools from Sun are called the Java Developers Kit (JDK)
c. The NetBeans tools offer a graphical development toolkit
d. Javabeans can be used to create pallets of re-usable visual components.

Page 29
Chapter 2 Syntax and Data Types
10 Aug 2005

Chapter 2 Syntax and Data Types

The word syntax means the rules that are used to construct a language. The syntax
of Java is strongly based on that of C++. This was partly because there were so
many C and C++ programmers in the world that Sun thought the language would
be more likely to become popular if plenty of existing programmers found it easy to
learn. However, it does not have the sort of backwards compatibility between C++
and C (any legal C program should be compilable in a C++ compiler). One of the
problems with C/C++ is that many important details are "vendor implemented". This
means that a feature that will work in one version of a compiler will break in
another. This has resulted in situations where MFC (Microsoft Foundation Class),
although built on C++ is effectively a whole new language to learn.

One of the goals of Java was that it should make it less likely to write buggy code.
No amount of language design will entirely eliminate bugs, but a good design can
make bugs less likely. It removes some of the burden from the programmer onto
the compiler writers. To this end Java was designed to be simpler than C or C++.
Two of the ways that Sun produced a simplified language is the removal of the
direct manipulation of pointers and only allowing single inheritance. Direct
manipulation of pointer as in the use of the * operator in C/C++ is a major source of
bugs in programs. Java does use pointers, but they are hidden behind references
and cannot be directly manipulated. If you are from a Visual Basic background this
may be meaningless, but for C/C++ programmers it is an interesting departure.

The definitive guide to the syntax of the Java language is the Java Language
Specification, which can be browsed at

http://java.sun.com/docs/books/jls/second_edition/html/jTOC.doc.html

Flow Control
Flow control is the ability to dynamically change the path of execution a program
takes. Thus when you start a program you might give it a file name to process. If
the file exists it will open the file, if it cannot find the program it might put up a dialog
asking you to type in the file name. As well as making a decision about what line of
code to run after a decision, flow control means you can branch to an entirely
different chunk of code by calling a method, depending on the result of some test.

In addition to simple branching a vital part of flow control is looping, sometimes


called “iteration”. Iteration means to repeatedly re-run a piece of code until some
condition is satisfied. Although I used the word “looping” describe iteration and
many languages support the word “loop” there are several other constructs that
support iteration.

Page 30
Chapter 2 Syntax and Data Types
10 Aug 2005

There are several standard types of flow control common to most programming
languages that only vary in the details of syntax. Thus in the past I have had
familiarity with C/C++, Pascal, Perl. Visual Basic and now Java and all of those
languages have more in common in their flow control statements than they differ.
For example most languages support variations on the theme of if/else while and
do loops.

if/else
The control structure that is probably most common between languages is the if
and the if/else construct.

Example of how if can be used

As you might expect the if statement tests if something is true. Although what Java
considers to be "true" can be subtly different from some other languages. For Java
true is always a boolean test. It does not have any concept of true being zero, one
or minus one, it is always a boolean comparison.

An if test must always evaluate to a boolean value, you cannot test if it returns 1,
zero or -1 or anything but a boolean

If the test is true the lines of code immediately afterwards are executed, otherwise
different lines get run.

To give a typical example

int i=0;

Page 31
Chapter 2 Syntax and Data Types
10 Aug 2005

if (i==1){
System.out.println("Good morning");
}

The curly braces create a block of code, which means if the test is true it will
execute multiple lines of code. You can use the if statement without the braces so it
is only the next line that is executed conditionally, using this format the previous
example would appear as

int i=0;
if (i==1)
System.out.println(" Good morning");

However, many people consider this to be bad style as it is too easy to get
confused as to where the impact of the if statement starts and stops.

The if/else construct is a close relation of the lone if statement. It adds a block of
code that will execute only if the test of the if statement was false. Thus

int i=0;
if (i==1){
System.out.println("Good morning");
}else{
System.out.println("Good afternoon");

This is an either/or construct. If the value of i is equal to one then "Good morning" is
output, if it is not then "Good afternoon" is output.

The final variation on the if construct is else/if. If you have a situation with more
than two alternatives you can have an arbitrary number of else ifs before the final
else.

if(i==0){
System.out.println("Good morning");
}else if (i==1){
System.out.println("Good afternoon");
}else{
System.out.println("Good night");
}

This is really just an extension of the if/else construct with additional if statements
after the else.

Note that whatever is tested between the parenthesis must evaluate to a boolean
value. Thus the test in the example if(i==0) is either true or false, it is not a number.
This is in contrast to the C/C++ languages (and possibly some others) where there
is a convention that an evaluation that returns zero is false and any other value is
true.

Page 32
Chapter 2 Syntax and Data Types
10 Aug 2005

In C/C++ you can test with syntax such as

int i=1;

if(i){
//do something
}

In Java an if clause must be a boolean test. Thus you can re-state that example as

if(i==1){
//do something
}

Also note that the test is performed with the == operator and not the assignment
operator =. Sooner or later everyone tries to compile code with a test like this

if(i=1){
//do something
}

This simply assigns the value of 1 to the variable i, rather than testing the condition.
Luckily Java will flag this type of error at compile time.

The assignment operator


Note that the test in that last code example is performed with the == operator and
not the assignment operator =. Sooner or later everyone tries to compile code with
a test like this

if(i=1){
//do something
}

This simply assigns the value of 1 to the variable i, rather than testing the condition.
Luckily Java will flag this type of error at compile time. Some languages (notably
Visual Basic) use the = operator for both assignment and for testing equality. As
these are quite different acts it seems reasonable to use different operators. Note
that assignment works from right to left. You cannot assign in the way you might in
algebra as

int x=2;
int y=0;
/* incorrect, will generate a compile time error!*/
x * 2 = y;

While/do while
The while construct allows a program to loop for a number of times depending on
some test.

Page 33
Chapter 2 Syntax and Data Types
10 Aug 2005

The general format for a while loop is

while(booleantest){
/*body of loop*/
}

The while loop will continue to iterate until booleantest returns false. Because a
while loop begins with a test, if that test returns false the code may never actually
enter the body of the loop. This is by contrast with a do-while loop where you are
guaranteed that the body of the loop will execute at least once.

Essentially a will execute zero or more times and a do-while loop will execute one
or more times. If you think of the implicit logic the words do-while imply

"do this while something is true", indicating that the test will come after the loop has
executed at least once. A while construct by contrast does the test before
performing the first loop.

In actual Java code a while code looks like this

int i=1;
while(i <1){
System.out.println(i);
}

The line i++ will add one to the variable i (also known as incrementing). This loop
will execute zero times. The while test (i <1) will return false as 1 is not smaller than
1. The code will then continue executing after the closing brace.

The following code will however loop once and output the value of i to the console.

int i=1;
do{
System.out.println(i);
}while(i<1);

The for loop


The for loop is very popular with programmers as it combines the creation of
counting variables and performing a test on a value all in one neat package. The
general structure of the for loop is

for(Create counter variable; test counter; modify counter){


Body of for loop
}

You can think of these three parts separated by the semi colon as initialise, test and
modify.

In actual Java code this typically translates to

Page 34
Chapter 2 Syntax and Data Types
10 Aug 2005

for(int i=0; i <3; i ++){


//Do something in the body of the code
}

In this example the counter variable i was created within the body of the for loop
with the statement

int i=0;

The test part simply matches against the number 3, in a real program you would
probably testing against some other variable. The modify counter adds one to value
of i on each loop around.

The break and continue statements?


Several programming languages including Visual Basic support the goto statement.
This allows code to jump to any other location in a program. Although this seems
useful, indiscriminate use of goto statements can result in hard to maintain
spaghetti code. The name spaghetti code comes from the idea of spaghetti pasta
on a plate where you cannot see where one strand begins and another ends.

The designers of Java decided that they agreed with programming guru Edsger
Dijkstra who wrote a famous article titled "Goto considered harmful". it has fallen
out of use and considered bad programming style. The goto statement is
sometimes known as an "unconditional jump", ie it is possible to write code that
jumps from one part of a program to another without even performing a test. There
are situations when it would be useful and to help in those situations Java offers the
labelled and unlabelled versions of the break and continue keywords.

The following code demonstrates how these two statements work.

public class BreakContinue{


public static void main(String argv[]){
System.out.println("Break");
for(int i=1; i < 4; i++){
System.out.println(i);
if(i > 1) break;
}
System.out.println("Continue");
for(int i=1; i < 4; i++){
System.out.println(i);
if(i > 1) continue;
}
}
}

This code will output Break 1 2 followed by Continue 123. This is because the
break continue entirely stops the execution of the for loop whereas the continue
statement only stops the current iteration.

Page 35
Chapter 2 Syntax and Data Types
10 Aug 2005

Data Types and variables

Like all programming languages Java allows data to be stored in variables. The
term variable has its origins in the idea that the contents may vary, i.e. At the start
of a program variable may contain 10 and later it might contain 99.

Behind the scene a variable is a name or label given to a piece of memory. That
name can be used to refer to whatever value is currently stored in the memory
location. It is a little like the use of symbols such as X or Y in algebraic equations.

There are rules for what names can be given to variables, but you are generally
safe if you stick to names containing all letters, and preferably a name that means
something to you. Thus if you are storing the height of an image you are better off
calling it Height rather than z or p. There is a convention amongst some
programmers to add letters to variables to indicate the data type. Thus if the height
of an image is being stored in an integer you might call a variable iHeight.

All variables must be given a data type when they are created. There are some
languages sometimes called “weakly typed” languages that do not require this. For
example in the PHP language used to create web pages there is no concept of
assigning a type to a variable. Although this can seem very convenient it can
cause problems where people misspell a variable name and the language assumes
it is an attempt to create a new variable and so the programmer is not warned. The
requirement to give a type to all variables is considered to be a feature that makes
Java "safer", i.e. It is not so easy to create bugs.

You can create a variable ready for use elsewhere or you can assign a value to it at
the same time you create it. Here is an example of creating an integer (int) variable
without assigning a value.

int i;

This tells Java to create a variable called i with the type int. An int is a type that can
store the values between approximately plus or minus 2 billion and has no
fractional part (decimal point values).

The other form of creating a variable is

int iHeight=10;

This does the same as the previous example, except that it assigns a value to the
variable at the same time as it creates it. Note that in both examples the line ends
with a semi colon. This indicates the end of the statement to the compiler. Sooner
or later everyone misses off the semi colon or places a colon or similar character by
mistake. Luckily the error messages from Java give a good indication what the error
is.

Page 36
Chapter 2 Syntax and Data Types
10 Aug 2005

Method and class variables


A variable can be created either at class level or method level. A class level
variable is also known as a field and is visible from within any method in that class.
By contrast a method level variable is only visible within that method. Another
important property of a method level variable is that it comes into existence when
the code enters the class and does not persist between calls to the class. Thus if
you take the example of the following code.

Void amethod(){
int i = 1;
}

The variable i will be re-initialised each time amethod is called. Method variables
are not given default values and if you attempt to use them without assigning a
value it will generate a compile time error. The following code demonstrates this.

public class MetVar{


public static void main(String argv[]){
MetVar mv = new MetVar();
mv.amethod();
}
public void amethod(){
int i;
System.out.println(i);
}
}

If you attempt to compile this code it will generate the error

MetVar.java:8: variable i might not have been initialized


System.out.println(i);
^
1 error

Primitive Types
Primitive types are the basic building blocks of programming, and are present in
almost all languages. Primitives cannot have methods, and cannot be inherited
from or redefined. They can be directly manipulated with the math operators such
as +, - and *.

For much of your time programming you will not care much about the size of the
primitives you use. Indeed in some languages such as PHP there is no concept of
assigning a type to a variable, and millions of lines of PHP code are written and
many people love the languages.

Java was designed to allow large scale software engineering however and being
able to control data types gives the programmer a fine control over resource usage.

Page 37
Chapter 2 Syntax and Data Types
10 Aug 2005

Thus for many (most?) simple counting operations the data type called int will do
just fine, as it will store numbers up to 2 billion odd and if you are counting the
numbers of windows your program has open or the number of CD's in your
collection an int will probably do just fine.

However of Bill Gates, is calculating his net worth he might need to pay more
attention to his choice of data type (OK so he wouldn't admit in public that he was
using Java, but he is a smart technologist under all that marketing).

Unlike C/C++ the size of Java primitives are fixed no matter what platform it is used
on. In C/C++ you can often see code that uses the sizeof operator to try to ensure
that code is platform neutral by determining the size of a data type on the current
platform. Because this is not mandatory the move from one platform to another can
often break C/C++ code in a subtle manner.

Primitive data types can broadly be divided into integral types and floating point
types. Floating point types can store vast, huge, enormous numbers but they bring
with them a certain imprecision. For many purposes one of the integral types such
as int or long will do just nicely.

Size of Primitives.
The size of Primitives
Name Size Range
byte 8 bit -27 to 27-1
short 16 bit -215 to 215-1
int 32 bit -231 to 231-1
long 64 bit -263 to 2 63-1

Character Data
Character data is stuff like car licence plates, phone numbers and social security
numbers, data that might consist of numbers but that you don't normally perform
math on. The two main ways of storing character data is via the char primitive or the
String class. The String class is generally preferable as it has a whole swag of
methods for slicing, dicing and generally manipulating the characters. The char
primitive data type is actually a 16 bit integer that can store characters from the
Unicode character set. You generally don't need to know much about Unicode
unless you are involved in internationalisation (apologies if that is horribly English
centred, but I am horribly English centred). Unicode is a way of storing almost any
of the worlds character sets, so you can represent the accents in European
languages or even Vietnamese, Chinese and Japanese that do not even use the
European style character sets.

Page 38
Chapter 2 Syntax and Data Types
10 Aug 2005

An important difference between the String class and the char data type is that
when you put a character into a char variable you use single quotes and when you
put a character into a String you use double quotes.

Thus

String s = new String("a");


char a = 'a';

Note that a char only stores one character, do not try to store a string thus

char a='error';

Will not compile.

The String Class


So many programming tasks require the manipulation of String data that Java has a
built in String class. String is a class rather than a primitive type so note that the
name begins with an upper case S, it is NOT string, it is String. It is a general
convention in Java that the names of classes begin with upper case letters. The
sequence of letters assigned to an instance of a class are surrounded by double
quotes. Thus you can create a String variable thus

String sName = "Hello java";

If you have ever used the C programming language you may have become used to
storing Strings as arrays of character primitives. An instance of the Java String
class is not the same as an array of char primitives. If you need to perform large
amounts of String handling, such as importing and manipulating multiple
megabytes of text, Java has a StringBuffer class that offers better performance
than the String class.

Java Keywords
Keywords are words that cannot be used to name variables. If you attempt to use
one of these names for a variable you will get a compile time error.

Java Keywords
abstract boolean break byte case catch
char class const * continue default do
double else extends final finally float
for goto * if implements import instanceof
int interface long native new null
package private protected public return short

Page 39
Chapter 2 Syntax and Data Types
10 Aug 2005

static super switch synchronized this throw


throws transient try void volatile while

The words with asterisks are reserved and not currently used. Note that all of the
keywords are in lower-case, thus null is a keyword but NULL is not.

Swing AWT and SWT


In early versions of Java the graphical interface was implemented using a set of
libraries called the AWT. AWT was designed to use the “native” widgets or controls
on each supported operating system. The problem with this is that it meant that a
widget could only be supported if it was present on all platforms. So if one operating
system did not support a combo box (a combination of text box and list box) none
of them could. In addition this “lowest common denominator” meant that AWT
applications looked equally bad on every supported platforms. So whilst users of
the Apple Macintosh were used to using very visually appealing programs, perhaps
verging on the beautiful. As soon as they ran a Java AWT application they were
looking at an interface that was one step up from a text based screen.

To get around some of these limitations Sun developed a replacement for AWT
called Swing. The Swing system has more controls, a better appearance and what
is known as as a Pluggable Look and Feel (or PLAF). By virtue of this, a program
on the Macintosh actually looks like a Macintosh program, and a Windows program
looks like a Windows program. With a single change in a line of code you can turn
a program from one Look and Feel to another.

UIManager.setLookAndFeel(new
com.sun.java.swing.plaf.windows.WindowsLookAndFeel());

//UIManager.setLookAndFeel(new
com.sun.java.swing.plaf.motif.MotifLookAndFeel());
//UIManager.setLookAndFeel(new
com.sun.java.swing.plaf.metal.MetalLookAndFeel());

The Pluggable Look and Feel of Swing allows a Java


application to have the appearance of the native Operating
System
Whichever line is uncommented, the program will take on the Look and Feel. Thus
the following to images are the same code except one is using the Motif, one the
Windows look and one the Metal. (You can only run the Macintosh look and feel on
Macintosh hardware due to the litigious nature of the Apple Computer company).

Page 40
Chapter 2 Syntax and Data Types
10 Aug 2005

The Metal (Java) Look and feel

Page 41
Chapter 2 Syntax and Data Types
10 Aug 2005

The Windows Look and feel

Page 42
Chapter 2 Syntax and Data Types
10 Aug 2005

The Motif (Unix) Look and feel

SWT
I will only mention SWT in passing so you know what it is, rather than explain how
to use it. Although Swing is generally a big improvement on AWT it has been
criticised for performance issues. Engineers at IBM decided that they could do
better than this and came up with the Standard Widget Toolkit, which like AWT
used the widgets in the underlying platform. Unlike AWT however rather than take a
“lowest common denominator” approach and give an interface that looks the same
on each platform, SWT adopts the look of the native platform, and offers good
performance. You can see SWT in action in the eclipse project
(http://www.eclipse.org). In my view SWT is interesting but is not the standard in
Java programming and unlikely to become the standard, so unless I have a very
compelling reason to look further into it I am happy to leave it to the engineers
behind the excellent eclipse development tool.

Java Applets and web browsers


In the early days of Java it was assumed that its main area of success would be in
Applets, small programs that get executed within the browser rather than on the
web server. For various reasons applets have turned out to be a minority sport on
the web. They suffered from performance and compatibility problems. Much of the
compatibility issues stem from the different implementations from Microsoft,

Page 43
Chapter 2 Syntax and Data Types
10 Aug 2005

Netscape and Sun.

Microsoft has never supported the Swing libraries and Netscape was late to support
them. It was also found that few web sites actually needed to have code execute
within the browser and where it was needed the needs were fairly trivial and would
execute more quickly using a scripting language such as JavaScript (almost no
relation to Java at all). It is hard to persuade inexperienced users to download a 5
megabyte install program simply to get some feature working on your website
unless they have a very pressing need for that feature. Many website designers
have decided that Flash offers most of the programming features of applets but
with better performance and wildly better control over appearance.

The Java Plugin

There are areas where nothing but an Applet will address the problem and the lack
of compatibility across browsers was a thorny problem. As a result there was a
minor industry in programming AWT applets that took account of the quirks
between the Netscape/Microsoft/Sun implementations of Java. This ridiculous lack
of standards was significantly addressed by Suns Java plugin. This is a kind of
bridging technology that allows Applets to run using the standard Java runtime
shipped by Sun in almost any browser.

The Java plugin gives a standard JVM target across


all the major browsers.

The Plugin Tray icon


Under windows, when you access an applet the Java Plugin icon will appear in your
system tray in a similar way to the following screen shot (the arrow points to the
icon)

The plugin will run in both the Netscape and Microsoft browsers and gives
programmers a single platform as a target for their programs. I recommend the
plugin as the preferred way to execute Applets as you can avoid many
incompatibility problems between versions of Java.

Page 44
Chapter 2 Syntax and Data Types
10 Aug 2005

Java Event Handling


The idea of event handling is most commonly seen when a user clicks on
something in a graphical application or hits a key. Java Event handling is based
around the concept of event Listeners. A listener is created and attached to a
component. The two main methods of creating listeners are

• interfaces
• adapter classes

Using interfaces are sometimes known as "Programming by contract". When a


class implements an interface it is contracting to implement the body in every
method in the interface. So if you wanted to manage a window and used the
WindowListener interface you would have to create a body for all 7 of the methods
in that interface. If you were simply creating some test programs you might only
want to actually process one of the events, that match the methods, and thus only
need to create useful code for that methods. Despite only wanting to process one
method, you would have to create an empty body for the other 6 methods. The
adapter class helps get around this problem by supplying empty bodies for all the
methods, and you then override the method that matches the action you want to
process. If that explanation seems a little complicated, it is safe not to worry about it
for the moment, and come back to it later.

Creating Events using Adapter classes


The adapter class approach is slightly simpler than the interface approach so I will
only cover that for the moment. Here is a modified version of HelloWorld that
includes an adapter class that allows you to close down the Frame gracefully
without resorting to the two finger salute, or Ctrl-c.

/* ShutHello */
// A Single line comment
import javax.swing.*;
import java.awt.event.*;//Note that handling is an awt class
public class ShutHello extends JFrame{
public static void main(String argv[]){
ShutHello shuthello = new ShutHello();
shuthello.go();
}
public void go(){
//Create an instance of the Adapter class
WindowCloser wc = new WindowCloser();
//attach that class to the current class
addWindowListener(wc);
JButton button = new JButton("Hello");
getContentPane().add(button);
setSize(100,100);
setVisible(true);

}
}

Page 45
Chapter 2 Syntax and Data Types
10 Aug 2005

class WindowCloser extends WindowAdapter{


//override one of the methods in the Adapter class
public void windowClosing(WindowEvent e){
System.exit(0);
}
}

The event handling code

WindowCloser wc = new WindowCloser();


//Attach that listener to this program
addWindowListener(wc);

The first line creates an instance of the WindowCloser class (explained a little later
here). The next line attaches this class as a listener to the current instance of the
program. This line has an implicit reference to the this instance. Thus it would also
correct to have this line as

this.addWindowListener(wc);

If the WindowCloser class were correctly defined outside this file, this would be all
you would have to do to implement code to close this window. However, in this
instance the WindowCloser class is actually defined within the same file and is
explained next.

class WindowCloser extends WindowAdapter{

This line defines a new class within the current file. The name WindowCloser is
arbitrary but I have chosen it to indicate the purpose of the class. It extends
WindowAdapter which is a class that offers methods that control the sort of events
that might happen to a window.

public void windowClosing(WindowEvent e){


System.exit(0);
}

These lines override the windowClosing method in the WindowAdapter class. Note
the naming convention where the method name starts with a lower case letter. This
is in contrast with the name of the parameter that starts with an upper case letter.
When learning the methods it is easy to get this convention wrong and wonder why
the code will compile but not do what you expect. With luck you will mainly use a
GUI builder such as NetBeans to actually create this sort of code.

The System.exit(0) line simply halts the running of the current program. It would be
possible to write code to close the current window, but stopping the current program
is easy to do and has the effect of closing the window. This line that shuts down the
program is where the real work is done. The rest of the code is mainly window
dressing. There are a limited number of events that can be trapped and it is what
you do with them that counts. Thus for instance you might attach an event to a
button that opens another frame and initialises some values on that frame

Page 46
Chapter 2 Syntax and Data Types
10 Aug 2005

according to the contents of a text field.

If you use a GUI builder such as NetBeans you will soon notice if you look at the
code that it does not produce external classes for the event handling code as I have
but uses the concept of inner classes. Where I have created the WindowCloser
class as an external class within the same file, NetBeans creates an instance of the
class actually within the event handling method. This is very handy for a GUI builder
tool and keeps the code compact but it is more complex to write by hand as you
have to keep a close watch on opening and closing of parenthesis and curly
braces. The actual principal of using Listeners is identical.

Quiz
1) What will happen when you attempt to compile and run the following code?

public class IfTest{


int i = 0;
public static void main(String argv[]){
new IfTest();

}
IfTest(){
if(i==1){
System.out.println("true "+i);

}else{

System.out.println("false "+i);

a. Compile time error


b. Compilation and output of true
c. Compilation and output of false
d. Compilation but no output at runtime

2)Is the following statement true or false?

"The body of a do loop will execute zero or more times”

3)What will happen when you attempt to compile and run the following code?

public class ForTest{


public static void main(String argv[]){
new ForTest();
}

Page 47
Chapter 2 Syntax and Data Types
10 Aug 2005

ForTest(){
for(int i = 0; i < 3; i ++){
System.out.println(i);
}
System.out.print(i);

}
}

a. Compiliation and output of 123


b. Compilation and output of 012
c. Compilation but no output at runtime
d. Compile time error, i is not visible after the for loop

4) What will happen when you try to compile and run the following code?

public class IfPar {


public static void main(String argv[]){
new IfPar();
}
public IfPar() {
int i = 0;
if(i){
System.out.print("i="+i);

a. Compilation and output of 0


b. Compile time error
c. Compilation but no output at runtime
d. Compilation but runtime error

Answers
Question 1

c. Compilation and output of false

Question 2

False

Question 3

Page 48
Chapter 2 Syntax and Data Types
10 Aug 2005

c. Compile time error, i is not visible after the for loop

A variable created in the body of a for loop is not visible outside that loop. The
scope is limited to the block created by the braces.

Question 4

c. Compile time error

Question 5

b. The String class has a method to return its length


The length() method of the String class returns the number of characters in the
string.

d. An instance of String can be created as String s = "mystring";

Page 49
Chapter 3 Layout Managers
10 Aug 2005

Chapter 3 Layout Managers


Java uses a different philosophy to layout compared with tools such as
Visual Basic or Delphi (if philosophy is not too grand an expression for
laying out a program). Most design tools use an XY pixel based approach
to placing a component. A component will effectively be placed X number
of pixels from the left of the screen and Y number of pixels from the
bottom of the screen. Thus in Visual Basic you can pick up a text box
from the component palette and drop it at a location on a form, its
location is set.

If you then run the same program with a different screen resolution the
components will retain their location rather than being adjusted to
account for the screen size. If you run the program on a smaller screen it
could be that the component will actually be “off the screen” and
invisible. By contrast Java uses Layout classes to control where a
component is placed according to the current screen.

Part of the reason for this is the cross platform nature of Java. A Java
applet may display on anything from a palm top computer, a mobile
phone to a 19 inch Monitor. I have tried writing Visual Basic applications
that take account of more than one screen resolution and it is not a
trivial activity. Be warned, if you have a background in other RAD tools
you may find the Layout Manager approach a little weird at first. If you
know your guaranteed target platform is going to be a standard desktop
monitor, the layout approach can be frustrating. If at some point in the
future this guarantee turns out to be hollow and you have to target a
different platform, you may be grateful to the designers of the Java
layout system.

Layout managers are generally used in combinations to almost "suggest"


how an application should appear. Thus components have a default
"preferred" size. Under one layout manager configuration they will be
allowed to display at their "preferred" size, but under another they may
be confined to a particular size, which may be influenced by the size of
other components in the application.

FlowLayout
The FlowLayout manager is a good place to start as it is the default for
Applets and Panels The FlowLayout manager simply places components
on a background one after the other from left to right. If it runs out of
space to the right it simply wraps around the components to the next
line.

Page 50
Chapter 3 Layout Managers
10 Aug 2005

The following code creates a very simple application and adds a series of
buttons

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

public class FlowAp extends JFrame{


public static void main(String argv[]){
FlowAp fa=new FlowAp();
//Change from BorderLayout default
fa.getContentPane().setLayout(new FlowLayout());
fa.setSize(200,200);
fa.setVisible(true);
}

FlowAp(){

JButton one = new JButton("One");


getContentPane().add(one);
JButton two = new JButton("Two");
getContentPane().add(two);
JButton three = new JButton("Three");
getContentPane().add(three);
JButton four = new JButton("four");
getContentPane().add(four);
JButton five = new JButton("five");
getContentPane().add(five);
JButton six = new JButton("Six");
getContentPane().add(six);

}//End of constructor

}//End of Application

The following image is the default appearance when you fire it up from
the command line.

If you change the width of the application by dragging the right hand side
of the Frame however, the program re-configures the layout of the
buttons thus.

Page 51
Chapter 3 Layout Managers
10 Aug 2005

Bear in mind that both images are the display for exactly the same java
code. The only thing that has changed is the width. The FlowLayout
manager automatically changes the layout of the components when the
Frame is re-sized. If you were to make the Frame very small the
FlowLayout manager would change the layout so that the buttons were
wrapped around in several rows.

When you first come across this approach to the management of


components it may seem a little arbitrary. Some of the GUI building tools
such as NetBeans and JBuilder offer ways of specifically placing
components. For instance Borland JBuilder offers the XYLayout that gives
you this functionality.

Flow, Border and Gridlayouts compared


For the purposes of this course I will concentrate on three of the Layout
managers shipped by Sun, these are

• FlowLayout
• BorderLayout
• GridLayout

These give you enough control over component layout for most
demonstration programs. The FlowLayout and BorderLayout are the
default Layout Managers for the Frame and Applet class respectively.
Thus if you create a Frame and do not specifically assign a Layout
Manager it will automatically use the BorderLayout.

The default layout for a frame is the


BorderLayout

This is slightly awkward as the BorderLayout is not the most useful of


Managers. It divides the Frame area up into five regions, North, South,

Page 52
Chapter 3 Layout Managers
10 Aug 2005

East, West and Centre. Also if you do not specify a region each new
component defaults to the centre of the Frame and if you add more than
one component without a region, each new component gets added on top
of the old one. So for the purposes of these demonstration programs you
may find it useful change the Layout Manager to FlowLayout. This can be
done using the setLayout Method of Frame. Thus you can change from
the default BorderLayout to a FlowLayout with the following code in a
Frame constructor

f.setLayout(new FlowLayout);

BorderLayout
Here is a small demonstration showing how the BorderLayout places
components added with the region constraints.

import javax.swing.*;

public class BorDemo extends JFrame{


JButton n = new JButton("North");
JButton e = new JButton("East");
JButton s = new JButton("South");
JButton w = new JButton("West");
JButton c = new JButton("Centre");

public static void main(String argv[]){


BorDemo b = new BorDemo();
}
BorDemo(){
getContentPane().add(n,"North");
getContentPane().add(e,"East");
getContentPane().add(s,"South");
getContentPane().add(w,"West");
getContentPane().add(c,"Center");
setVisible(true);
setSize(300,300);
}

Note how the add method is overloaded to take a region constraint.

This is how the program displays itself.

Page 53
Chapter 3 Layout Managers
10 Aug 2005

GridLayout
The GridLayout manager does approximately what you might expect. It
divides the surface area up into a grid and when you add components it
places them one after the other from left to right, top to bottom. Unlike
the BorderLayout and FlowLayout it ignores any preferred size of the
component. For example the preferred size of a button will be wide
enough to show its text. The FlowLayout manager attempts to ensure
that a button is this preferred size. The GridLayout has a more bondage
and discipline approach. The only thing it cares about is making sure the
component fits into the grid.

The following code lays out a set of buttons within a Frame using a
GridLayout that has been set up to have 2 rows and 5 columns.

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

public class GridAp extends JFrame{

public static void main(String argv[]){


GridAp ga=new GridAp();
//Setup GridLayout with 2 rows and 5 columns
ga.getContentPane().setLayout(new GridLayout(2,5));
ga.setSize(400,300);
ga.setVisible(true);
}
GridAp(){
getContentPane().add(new JButton("One"));
getContentPane().add(new JButton("Two"));

Page 54
Chapter 3 Layout Managers
10 Aug 2005

getContentPane().add(new JButton("Three"));
getContentPane().add(new JButton("Four"));
getContentPane().add(new JButton("Five"));
getContentPane().add(new JButton("Six"));
getContentPane().add(new JButton("Seven"));
getContentPane().add(new JButton("Eight"));
getContentPane().add(new JButton("Nine"));
getContentPane().add(new JButton("A very long button label
indeed"));
}//End of constructor

}//End of Application

Using multiple Layout managers in an


application
As you can probably imagine, no one Layout manager is suitable for all
the requirements of an application. They are normally used in
cooperation with other Container controls. Thus a BorderLayout may be
used for a Frame but a Panel will be added to the North. The panel is set
to use a FlowLayout and buttons are added within the Panel. Another
Panel might be added to the Centre which is set to the GridLayout and a
series of Buttons added there.

The following code demonstrates the use of multiple layouts.

Page 55
Chapter 3 Layout Managers
10 Aug 2005

import javax.swing.*;
import javax.swing.JPanel;
import java.awt.*;
/**
* Demonstration of using multiple layouts
* Marcus Green 2005
**/
public class MultiLay extends JFrame{

public static void main(String argv[]){


MultiLay ml=new MultiLay();

}
MultiLay(){
/* Setup GridLayout with 2 rows and 1 column */
/**
* This grid layout will set the button one to occupy all of
* the top of the frame. The flow layout used in the second panel
* means its preferred size will be respected and thus it will
* occupy only enough space to show the text "two"
* If you are using earlier than JDK 1.5 you will need
* getContentPane code here
**/
setLayout(new GridLayout(2,1));
add(new JButton("One"));
JPanel jp = new JPanel();
jp.setLayout(new FlowLayout());
add(jp);
jp.add(new Button("two"));
setSize(400,300);
setVisible(true);
}
}

Text 2MultiLay

Illustration 2Multilay

Quiz
1) Which of the following is the default layout for JApplet?

Page 56
Chapter 3 Layout Managers
10 Aug 2005

a. GridLayout
b. FlowLayout
c. PackLayout
d. BorderLayout

2) What will be displayed when you attempt to compile and run the following
code?

import javax.swing.*;
public class Butt extends JFrame{
public static void main(String argv[]){
Butt MyBut=new Butt();
}

Butt(){
JButton HelloBut=new JButton("Hello");
JButton ByeBut=new JButton("Bye");
getContentPane().add(HelloBut);
getContentPane().add(ByeBut);
setSize(300,300);
setVisible(true);
}
}

a. Two buttons side by side occupying all of the frame, Hello on the left and Bye ont
he right
b. One button occupying the entire frame saying Hello
c. Two buttons at the top of the frame one saying Hello the other saying Byed. One
button occupying the entire frame saying Bye
d. One button occupying the entire frame saying Bye

3) Which of the following statements are true?

a. The default layout for JFrame is FlowLayout


b. A layout manager must be assigned to JApplet before the setSize method is
called
c. The defauult layout manager for JPanel is BorderLayout
d. The FlowLayout manager attempts to honour the preferred size of any
components

4) Which of the following statements are true?

a. Layout managers define the screen as x/y coordinates starting at the bottom right
of the screen
b. Layout managers allow applications to display appropriately without regard to
display resolution.
c. Layout managers are available for both graphical and text mode applications
d. For correct appearance a layout manager must call the getScreenResolution
method before initialisation

5) Is the following statement true or false?

Page 57
Chapter 3 Layout Managers
10 Aug 2005

A Java application may only use one LayoutManager

Answers
Question 1

d. BorderLayout

FlowLayout is the default for Panels but not for JApplet

Question 2

d. One button occupying the entire frame saying Bye

Question 3

c. The defauult layout manager for JPanel is BorderLayout


d. The FlowLayout manager attempts to honour the preferred size of any
components
This is unlike the GridLayout manager which will resize components to fit within the
container.

Question 4

b. Layout managers allow applications to display appropriately without regard to


display resolution.
Layout managers are only available for graphical applications.

Question 5

False

in real world programming a typical Graphical Java application will use multiple
LayoutManager classes.

Page 58
Chapter 4 Arrays and collections
10 Aug 2005

Chapter 4 Arrays and collections


If you cast your mind back to the very first example, the method main had the form

public static void main(String argv[]);

The part between the braces that says

String arg[]

Indicates that the method takes a parameter of a String array. This means that
when the program starts running anything typed onto the command line after the
program name will be contained within this String array. An array is a holder for
multiple instances of a data type. So if you run your program with the command

java build one two three

The array arg will contain the string values

"one" "two" and "three"

You can extract any of the values from the array using the square bracket notation.
Thus if you wanted to print out the second String value contained within the argv
array you could use

System.out.println(argv[1]);

Note that accessing the second value means using 1 and not 2. This is because
almost all counting in Java starts from zero and not one. Although you can make an
argument that this is perfectly logical, it is something that can constantly catch you
out.

The alternative to using an array or some method of holding multiple variables


would be to create multiple variables for each value. So for the previous example
you might create variables in the form

String sArg1;
String sArg2
String sArg3

Which is much less elegant than having a way of carrying round multiple values
within one Array variable.

You can also find out how many elements an array has using it's length method.
Thus you could retrieve the number of command line parameters thus

System.out.println(argv[].length);

Page 59
Chapter 4 Arrays and collections
10 Aug 2005

Note that the elements of an array are always initialized to default values wherever
the array is created. This is in contrast to primitives, which are given default values
when created at class level but not as method variables.

Creating your own arrays


You will generally create your own arrays rather than take them from the command
line. The syntax for this is as follows

int income[] = new int[12];

Note how you can now assign or set the values contained in the twelve slots in this
array, send the array to some other part of the program and retrieve those values.
You might for instance be writing an accounting program and use this array to store
the income for each of the 12 months of the year.

You can assign values to each element by using square brackets to point to each
element in turn. Thus

int income[] = new int[12];


income[0]=2;
income[1]=99;
income[2]=12;
income[3]=100;

A typical way of getting at the values within the elements of an array is with a for
loop controlled by the length field of the array. Thus

for(int i=0; i < income.length; i++){


System.out.println(income[i]);
}

The value of i has 1 added to it each time around the loop. Remember that ++
increments a number by one. It would be perfectly correct to code it with i=i+1 like
this.

for(int i=0; i <3; i=i+1){

But this is not the standard Java idiom for doing this, so avoid this approach if you
want to hold your head up amongst Java programmers. Incrementing the value of i
means that income[i] points to the next element of the income array.

You could also use the other types of loops for accessing each element of the
array, such as the while or do/while loops. Thus you could create a counter outside
the loop, increment the counter each time around the loop and control the number
of times around the loop with the counter. Here is an example of how you could do
that.

public class MyAr{


public static void main(String argv[]){

Page 60
Chapter 4 Arrays and collections
10 Aug 2005

MyAr m = new MyAr();


m.go();
}
public void go(){
int income[] = new int[3];
income[0]=1;
income[1]=22;
income[2]=99;
int i=0;
while(i < income.length){
System.out.println(income[i]);
i++;
}
}

Many programmers prefer to use the for loop for this type of task, as the counter
variable is limited in scope to the actual loop and the whole thing can be set up on
one line. If you use a while/do while loop as in this example it is easy to forget to
include the incrementation line (the i++), exactly as I did whilst creating that
example.

Here is an example using the for loop.

public class Income{


public static void main(String argv[]){
Income i = new Income();
i.go();
}
public void go(){
int income[] = new int[12];
income[0]=2;
income[1]=99;
income[2]=12;
income[3]=100;
for(int i=0; i < income.length; i++){
System.out.println(income[i]);
}

}
}

Note that although the income array has 12 elements, the program only assigns
values to 4 of the elements. When the program runs you will see it output the four
assigned values as expected followed by another 8 zeros. This shows that the
elements of an array get default values if you don't assign any values for yourself.

Assigning array values on creation

It is useful to assign values to arrays at the time of creation. For example if you
were creating an array of Strings to represents the days of the week, it would be
useful to assign the String values at creation time. The following example shows
how you can do this.

Page 61
Chapter 4 Arrays and collections
10 Aug 2005

public class Days{


static String[] saDays = {"mon","tue","wed","thu","fri"};
public static void main(String argv[]){
System.out.println(saDays[0]);
}
}

Note that this only creates elements for the weekdays, if you were to attempt to
access elements 6 or 7 in the expectation of retrieving "sat" and "sun" the program
would show an error message. This is known as "Throwing an exception" in Java
jargon.

The new for loop

JDK1.5 (Java 5) introduced a new more compact version of the for loop. Thus the
code in the previous example can be expressed as

public class NewFor{


static int income[] = new int[]{1,2,3,4};
public static void main(String argv[]){
for(int i : income){
System.out.println(i);
}
}

Note how this form of the for loop does not require explicit coding of the increment
counter and how it automatically steps through each element of the arrays.

The Limitations of Arrays


Arrays are extremely useful and are widely used in Java programs. They have
limitations however. You need to know how many elements they will contain when
you create them and every element must be of the same type. Thus you cannot
create an array that stores an number for Salary and two Strings for first and last
name. When a program is running you may not know how many elements are
going to be needed. You can use a variable to control how many elements are
created, but if you subsequently find your array needs to be bigger you are stuck
with the original size. If you want to store multiple element of different types in one
named storage unit, you can use the classes based on the Java Collections
interface.

Collections
Collections are a way of storing multiple objects in a single named container. Unlike
arrays you do not need to know the size at the time of creation and arrays have
their own characteristics and methods. Note that Collections can only store objects,
not primitives. If you have need to store primitives you can use the wrapper classes
which as the name implies, act as a wrapper class for primitive types.

Page 62
Chapter 4 Arrays and collections
10 Aug 2005

Vectors

The Vector collection class allow the storage of objects and unlike an array does
not need to know how many will be stored when it is created. In many ways it is the
collection class most analogous to an array in that the elements can be accessed
using and index offset. Thus if you have an array called days with elements one,
two and three, you can access element zero as

days[0]

With the equivalent vector you can access element zero as

days.get(0);

The following code shows how an instance of Vector can be created, populated
with elements and then each element accessed in turn.

import java.util.*;
public class VecStore{
public static void main(String argv[]){
new VecStore();
}
VecStore(){
Vector<String> v = new Vector();
v.add("Xavier");
v.add("Bloggs");
v.add("Andrews");
v.add("Jones");
for(String s : v){
System.out.println(s);
}
}
}

The output from this program will be

XavierBloggsAndrewsJones

The program has simply stored the text and then output it in the same order it was
entered.

Note the strange syntax on creating the Vector reference with the angle brackets
<String> is an innovation bought in with JDK1.5 called Templates. This means that
the TreeSet knows it is receiving Objects of type String. Without the use of
Templates the type within the for loop would have to be Object as in

for(Object s :v){

Page 63
Chapter 4 Arrays and collections
10 Aug 2005

HashMap

In computing terms a Hash is sometimes known as an associative array. It is a


represents the relationship between a key and a value. Given the key you can look
up its matching value. For example you might set up a hash using a student ID as
the key and the student name as the value. The key must be unique (so it can
identify the value). The following code shows how you can populate a HashMap
with a number and a String and then use the number as the key to directly look up
the string.

import java.util.*;
public class HashStore{
public static void main(String argv[]){
new HashStore();
}
HashStore(){
HashMap names = new HashMap();
names.put(99,"Xavier");
names.put(12, "Bloggs");
names.put(1, "Andrews");
System.out.print(names.get(1));
}
}

If you compile and run this code it will output Andrews as that is the value that
maps to the key value 1.

TreeSet
For example the TreeSet collection ensures that its elements are sorted. So if you
were storing a set of names you could use the TreeSet to ensure they are sorted.
The following code illustrates this

import java.util.*;
public class NameSort{
public static void main(String argv[]){
new NameSort();
}
NameSort(){
TreeSet<String> names = new TreeSet();
names.add("Xavier");
names.add("Bloggs");
names.add("Andrews");
names.add("Jones");
for(String s : names){
System.out.println(s);
}
}

}
The output from this program will be AndrewsBloggsJonesXavier as the TreeSet
collection stores its elements in “natural order”, which in the case of Strings will be
alphabetical. Note that the fact that this class is called TreeSet tells you it
implements the Set interface. The term Set in this context means that each element

Page 64
Chapter 4 Arrays and collections
10 Aug 2005

must be unique. If you add the same element twice TreeSet will not throw an
exception but you will silently “throw away” the duplicated element. You can check
for this condition by inspecting the value returned when the add method is called.

I/O and exceptions


Almost all non trivial programs need to do Input and Output. Examples of this are
Word Processors that read document files, reading configuration files and network
programs that read information from the Internet. The programs you have seen so
far have performed output to the console using the System.out.println method. This
is fine for very small demonstration programs but for real world programs you need
to know about the built in Java.io classes.

Because I/O is such a big subject I will cover just the basics here before returning to
the subject later on. Java uses a concept of Streams to perform I/O. The idea of a
stream is an analogy from real life such as with a streams in the real world. You use
the Java I/O classes to create streams that can be used to read and write the
contents of files.

Exceptions
If you are going to learn about I/O you need to know about exception handling.
Exceptions are conditions that should not happen, i.e. exceptions to the expected
situation. An example of an exception is where you attempt to read a file from a
disk but find that the file does not exist. This can happen when the disk is
removable and it has unexpectedly been removed. With many programming
languages it is entirely up to the job of the programmer to write exception handling
code, and as a result programmers sometimes forget about it.

Java tries to gently push you in the direction of always handling exception by
ensuring that the methods in the key classes require you to handle the exceptions
they are likely to throw. Of course you can handle the exceptions by simply ignoring
them, but by the time you have put in code to ignore them, you may as well actually
handle them properly.

They keywords for handling exceptions are try and catch. You might like to think of
these as "try to do this task" and if there is an exception "catch the exception and
do something about it". The try and catch keywords surround the code with curly
braces, so you will often read about "try/catch blocks". Here is an example of the
use of a try/catch block

try{
DataInputStream dis = new DataInputStream(System.in);
is.readChar();
}catch(Exception e){
System.out.println(e.getMessage());
}

Page 65
Chapter 4 Arrays and collections
10 Aug 2005

I have always found the format of the catch part easy to get wrong. Note that the
type of the exception is encased in parenthesis and you have to make up a variable
name for the exception you are catching. Within the following brackets you need to
place the code that should be run if the exception occurs. In this case I have used
the getMessage method of the Exception. This is a common way of sending out a
meaningful message indicating what has happened. Typically this might be "File not
found".

In this example I have only caught the great grandparent of all Exceptions, good
programming practice suggests you should try to catch the specific exceptions that
might happen, such as FileNotFound or whatever. As you learn more about I/O you
will quickly become familiar with the most likely Exceptions that can occur.

Here is a complete program that will read in the text of its own code and send it to
the console.

1. import java.io.*;

2. public class FileOut{

3. public static void main(String argv[]){

4. FileOut f = new FileOut();

5. f.go();

6. }

7. public void go(){

8. try{

9. FileReader fr = new FileReader("FileOut.java");

10. int ch;

11. while((ch = fr.read())> -1){

12. System.out.print((char) ch);

13. }

14. }catch (Exception e){

15. System.out.println(e.getMessage());

16. }

17. }

18.}

Page 66
Chapter 4 Arrays and collections
10 Aug 2005

Note how on line 4 the program makes a call to new to create a reference to an
instance of this class. Without creating an instance of itself a program cannot call
any of its own methods. On the following line, line 5 it calls the go method to get
things started.

The first line of the go() method is line 8 of the program which starts a try block.
This is because we are about to run some code that might throw an exception

The second instance of the use of the new keyword occurs with the creation of a
reference to an instance of the FileReader class. The FileReader class is available
to the program because of the use of the import statement at the very start of the
program.

import java.io.*;

The use of the import statement is a little like using a path statement in DOS. It
doesn't actually include or import any code, it just says that if Java is looking for any
classes it should look to see if it can find them in the packages stated in the import
statements. At first the number of packages available in Java can seem to be a bit
daunting, but they are divided up into quite sensible and predictable areas such as
io, sql, and classes covering the various ways of manipulating graphics.
Remembering the names of the methods that classes use is a bit more tricky.

Note how the instance of the FileReader class is fed the name of a file to read. This
is known as a constructor parameter. Constructors are special methods that have
the same name as the class itself. In this case we have used the version of the
class constructor that takes a String value of the name of the file the class is going
to manipulate.

On line 10 the program declares a variable with the name ch and a type of int. The
following three lines loop around the instance of the FileReader class reading in
characters and sending them to the console. The read method of the FileReader
classes returns the value of each character unless it is at the end of the file, in
which case it returns -1. A bit of a fudge is required to get at the values of each
character because the read method of the FileReader class is an int, which is a
signed 32 bit number. What we want to output is a char which is an unsigned 16 bit
number. This conversion is performed by using what is known as a cast, i.e. the
type of an item of data is forced into another type. This is done simply by putting
parenthesis round the name of the datatype you want to convert to.

19. FileReader fr = new FileReader("FileOut.java");

20. int ch;

21. while((ch = fr.read())> -1){

22. System.out.print((char) ch);

23. }

Page 67
Chapter 4 Arrays and collections
10 Aug 2005

Using the throws keyword

In the previous examples the exceptions were handled approximately where they
occur. This can lead to some fairly complex code. For instance if you are doing a
large amount of I/O you will end up with huge amounts of try/catch blocks that can
soon make your code hard to read.

The use of the throws keyword allows you to pass exceptions up the stack to calling
methods. The throws keyword is appended to a method name and is followed by
the Exceptions that might be thrown. Thus typically you might have a method with a
file operation thus

public void amethod() throws IOException{


FileOutputStream fout = new FileOutputStream("test.txt");
fout.close();
}
}

Notice how the throws clause comes after the parameter parenthesis and before
the curly brackets. This sample code simply creates a file in the underlying
operating system called test.txt. It is the close method of the FileOutputStream
class that actually writes the file to the operating system. Without the throws clause
this code would not even compile. Note that the calling method must catch the
declared exception.

To allow the creation of complex I/O processing Java uses the concept of
"chaining" streams. This means that an instance of one Stream is passed as a
parameter to the constructor of another. You can see this in action in the following
example.

import java.io.*;
public class Stio {

public static void main(String argv[]){


try{
File f = new File("Output.txt");
FileOutputStream fos= new FileOutputStream(f);
OutputStreamWriter out = new OutputStreamWriter(fos);
out.write("Hello World");
out.close();
}catch(Exception e){}
}
}

The FileOutputStream class deals with the actual business of opening a file for
writing and the OutputStreamWriter deals writing to the file. The
OutputStreamWriter class was added with the JDK 1.1 and can take a constructor
that takes a String to allow for handling character sets apart from the current
default. This way you can process files that contain Unicode character sets such as
Chinese or Cyrilic. The writer classes understand the idea of data as text rather
than simply as a sequence of bytes that might be numbers or anything at all.

Page 68
Chapter 4 Arrays and collections
10 Aug 2005

Note that the File class is a bit misleading as you might expect it exclusively refer to
an actual file and to be concerned with writing to and from a physical file. By using
Stream chaining you can assemble file processing functionality from multiple
classes, rather than needing a huge range of discreet file processing classes.

Page 69
Chapter 5 Applets and components
10 Aug 2005

Chapter 5 Applets and components


Applets are Java programs embedded into web pages, allowing most of the
functionality of a Java application but removing the need for separate downloading
and installation. They user can interact with applets and pass responses back to
process on the web server such as databases. They perform a similar role to flash
pages except they come with some advantages (and disadvantages) by
comparison. Flash has the advantage that it is especially suitable for creating
animated images, and a user can do that with almost no knowledge of
programming. As flash has developed programming features have been added.
Java has the advantage of being an industrial strength programming language that
was designed from the ground up for software engineering. It also has more
support for encryption and security than any alternative technology.

In the early days of the web many people thought that most web pages would
involve Java applets, but much of the anticipated role has been taken up by
Javascript (almost no relation to Java). Typical examples of early use of applets
were dynamic menus or visual effects such as a rippling image of water on a lake.
In an era where most internet connections involved a relatively slow dial up modem
connection, the delay in downloading applets was generally not offset by a
significant benefit. Users of web pages are not tolerant of delay and web designers
found they could create an interface that was “good enough” with technologies like
HTML and JavaScript.

There are still some tasks for which only a Java Applet will fully solve the problem.
One of the benefits of applets is that once they are downloaded you do not have
the performance benefit of server side applications where you are relying on a
round trip to the server for each interaction, though of course JavaScript is
frequently a more “lightweight” alternative for browser based interactivity.

You can see how complex an applet can be by running the applet embedded in the
SwingSet2.htm file that gets installed with the JDK. With my installation of the JDK
this was installed at

C:\Program Files\Java\jdk1.5.0\demo\jfc\SwingApplet\SwingApplet.html

Yours may be slightly different, but it will probably be found under the demo/jfc
directory of your JDK installation.

Swingset Screenshot

Page 70
Chapter 5 Applets and components
10 Aug 2005

It is worth running this demonstration application as it shows off just how


sophisticated an interface can be built with the Java Swing classes. It shows off
slider controls, tree controls, tabbed forms, graphical buttons and just about
everything you would expect in a modern interface.

Browser wars
The history of Applets was caught up in the “Browser Wars” between Microsoft and
Netscape and the political and business battles between Microsoft and Sun
Microsystems. One of the problems of the early days was that of incompatibility.
When developing an applet you had to test it against different web browsers and
Java implementations. If you recall that one of the great promises of Java was
“write once run anywhere” this was rather a severe blow. Today these issues are
mainly history as the standard target for Java applets to day is the Sun Java
Runtime, a way of allowing just about any browser to be enabled with exactly the
same Java Runtime Environment (JRE).

Page 71
Chapter 5 Applets and components
10 Aug 2005

When it appeared that applets might take over the web Microsoft introduced what
was considered a competing technology in the form of ActiveX controls. The big
criticism of activeX at the time was that it was not secure and it was possible to
create a malicious activeX control that could access the users local hard disk. Also
activeX controls were only available for the windows platform.

Applets are particularly suitable for any task that requires a fully featured industrial
strength programming language. An example of this is anything connected with
security. Javascript is inherently not suited to security based tasks because it is so
easy to view the source code. Java Applets by contrast arrived in the form of binary
.class files and the JRE has a built in security system that makes it difficult for a
rogue applet to cause problems on a client computer. It is arguable that the
Browser Wars are back since the huge success of the Mozilla Firefox browser. This
success has come about even since the first draft of this text. With FireFox taking
around 10% of the browser market, the increased desktop market share of Linux,
and huge take up of broadband internet access, Applets are going to continue to be
an important technology.

Applications vs Applets
Most of the ideas you have learnt about applications can be applied to applets. One
of the key benefits of applets over applications is that they do not have to be
installed. If you consider the work that is required to install conventional applications
in terms of selecting components and the install directories, you may appreciate the
reduced “overhead” of applets.

One of the main areas of difference is security, particularly in accessing local


resources. The main restrictions are as follows.

Applets cannot read or write the the file system of the browser user. This means
they cannot delete files or test to see what programs you have installed. In contrast
to this, some versions of JavaScript in the leading web browsers were able to
access the local file system, leading to the possibility of rogue code.

Applets cannot communicate with any network server other than the one where the
applet was originally loaded from. This prevents an applet from attacking another
system from the readers system.

Applets cannot run any program on the reader system.

Applets cannot load local programs such as DLLS (dynamic link libraries).

Another consideration is that applets cannot start up new windows in the same way
that applications do. If an Applet were to open a new Window, how could you be
sure it was on top of the other windows and not hidden behind?

These restrictions are known as the Java sandbox. It is possible to configure

Page 72
Chapter 5 Applets and components
10 Aug 2005

applets with a finer grade of security using digital signatures and encryption. With
signed applets you are asked if you want to allow the applet greater access to your
system than the default and you have to decide if you trust the developers not to
violate your system. I won't be covering it in this text, but

Hello World
Putting an applet in a web page requires the use of the <applet> tag. To use this
tag you need to know how to use the parameters that indicate where the Java class
file is and any other details that it will require when it starts up within the browser.
Applets start in a different way to applications. Applications start with the “magically
named” method main which is invoked when the application is started from the
command line. Applets by contrast are controlled by the action of loading the web
page that they were embedded in and have a different sequence of methods
invoked at start up time.

HelloApplet

In the same way that the first application was HelloWorld, here is an example of a
basic HelloApplet.

public class HelloApplet extends javax.swing.JApplet{


public void paint(java.awt.Graphics g){
g.drawString("Hello",30,10);
}
}

Note that the HelloApplet class extends the javax.swing.JApplet class, which
provides the graphical capabilities in a similar way that a command line graphical
program might extend the javax.swing.JFrame class. An applet such as this is
compiled in the same way as an application, i.e.

javac HelloApplet.java

and the resultant output will be a file called

HelloApplet.class

In order to view this applet you need to create a basic HTML file that embeds the
applet in the web page.

It can be as little as the single lines

<applet code=HelloApplet.class width=200 height=100> </applet>

Page 73
Chapter 5 Applets and components
10 Aug 2005

Note how the reference to the applet includes the .class extension, unlike when you
run an application where you do not include a reference to the class extension.
Note how there is nothing between each parameter to the class, i.e. There is no
comma between width=200 and height=100.

There are two ways of view applet, either using the appletviewer tool that comes
with the JDK or by opening the html file using a Java enabled browser. One of the
disadvantages of appletviewer is that it does not implement all the security
precautions of the applet plugin. I have wasted a great deal of time testing a
program with the appletviewer only to find it did not work in a browser because I
was using methods that accessed files, so don't rely entirely on the applet viewer.
However for basic testing and learning the appletviewer is quick and convenient
and available from the command line. So to test HelloApplet you can type the
following command line

appletviewer helloapplet.htm

The parameters to the drawString methods are the x,y co-ordinates, and in the
example given it positions the output string at the top of the applet window. If you
were writing the equivalent application you could pass the x,y co-ordinates from the
command line and extract them from the String array that is the parameter to the
main method. However there is no command line with a page embedded within a
web browser. You can pass the equivalent of command line parameters to an
applet by embedding them into the html and capturing them when the applet starts.

Passing parameters to an applet requires additional <param ....> tags between the
starting <applet> tag and closing </applet> tag. For example, if you wanted to pass
the x,y co-ordinates to the helloapplet you could have parameters passed with the
following code.

<applet code=HelloApplet.class width=100 height=100>

<param name="greeting" value="bonjour">

</applet>

Note that the name of the parameter can be just about anything that makes sense
to you and the value will be passed as string to the applet. Examples of parameters
being passed to applets are where an applet acts as a “news ticker” and the
parameter is passed as part of the html. Of course the html can be generated from
a server side interaction.

Applet Lifecycle
If you take a look at the earlier sample applets you will notice that unlike
applications they have no main method. An applet life cycle is controlled by the init
and start methods. The init method is executed when the applet is first loaded into
memory, and the start method runs each time the browser visits the page
containing the applet. In the HelloApplet example given neither of these methods

Page 74
Chapter 5 Applets and components
10 Aug 2005

are defined and so the versions that are called are the default ones supplied by the
JApplet class. The default start method has a call to the paint method, which is why
those sample applets worked. Note that you generally never call the init or start
methods yourself, they are called by the browser at at the appropriate times.

The applet console.


Although applets do not have the standard command line console, you can see the
non GUI output from an applet via the applet console. In Microsoft IE you can
access this from the Tools/Sun Java Console or from Netscape/Mozilla it is visible
from Tools/Web Development/Java Console. This can be useful if you load an
applet from a web site and it does not appear to work correctly. Typically this can
be a failure to locate classes needed in an applet and in my own experience it
allowed me to track down an error where I was using classes that the Java Runtime
thought was trying to access the local file system.

Data Entry Fields and menus


Using the graphical components to create fully fledged Java applications is a
complex task. I have several large books that specialize explicitly in the Swing
libraries only. However to give a flavour of what can be done the following code
creates a form that contains two labels with associated text fields and a Submit
button. To keep things simple I have omitted any event handling code.

import javax.swing.*;
import java.awt.*;
/**
*@author Marcus Green
*Demonsration of use of Java Swing Compontnnts
**/
public class Components extends javax.swing.JFrame{
public static void main(String argv[]){
new Components();
}
Components(){
/* GridLayout with 3 rows and 1 column */
GridLayout gl = new GridLayout(3,1);
setLayout(gl);
/**
*JPanel defaults to a Flow Layout and
*so components added will have their
*preferred size respected
**/
JPanel jpRow1 = new JPanel();
JPanel jpRow2 = new JPanel();
JPanel jpRow3 = new JPanel();

JLabel jlFirstName = new JLabel("First Name");

/** JTextField takes the number of


*columns (width) as a constructor paramter
**/
JTextField jtFirstName = new JTextField(20);

Page 75
Chapter 5 Applets and components
10 Aug 2005

JLabel jlLastName = new JLabel("Last Name");


JTextField jtLastName = new JTextField(20);
/* add the components to the panel */
jpRow1.add(jlFirstName);
jpRow1.add(jtFirstName);
/* add the panel to the row within the GridLayout */
add(jpRow1);

jpRow2.add(jlLastName);
jpRow2.add(jtLastName);
add(jpRow2);
JButton jbSubmit = new JButton("Submit");
jpRow3.add(jbSubmit);
add(jpRow3);
/* Set the overall Frame size */
setSize(300,300);
/* Without this the application will be invisible */
setVisible(true);

The following screen shot shows how the application appears at runtime.

Components

Note that if you resize the application and make the Form narrower, the labels will
wrap so they appear above the associated text fields.

Menus

Creating menus is Java applications is relatively easy using a combination of the


JmenuBar, Jmenu and JmenuItem classes. Note that in a real system you would

Page 76
Chapter 5 Applets and components
10 Aug 2005

not have the names of menus embedded within the code, but separated out as a
resource to allow easy internationalisation. I have included sample code to allow
this application to respond when the exit option is selected.

import javax.swing.*;
import java.awt.*;
/**
*@author Marcus Green
*Demonsration of use of Java Swing Menu Compontnnts
**/
public class Menu extends javax.swing.JFrame{
public static void main(String argv[]){
new Menu();
}
Menu(){
/* Create the bar that runs accross the top of the frame */
JMenuBar jmBar = new JMenuBar();
/*The File menu that all other items will be attached to */
JMenu jm = new JMenu("File");
JMenuItem jmiFile = new JMenuItem("File");
JMenuItem jmiOpen = new JMenuItem("Open");
/* The short cut key that will have an underscore */
jmiOpen.setMnemonic('O');
JMenuItem jmiExit = new JMenuItem("Exit");
jmiExit.setMnemonic('x');
/* Exit back to the system when this menu option is selected */
jmiExit.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
System.exit(0);
}
});

/* Add each item to the menu */


jm.add(jmiOpen);
jm.add(jmiExit);

/* Add the menu to the menu bar */


jmBar.add(jm);
/* attch this menubar to the frame */
setJMenuBar(jmBar);
/* Set the overall Frame size */
setSize(350,350);
/* Without this the application will be invisible */
setVisible(true);
}

The following screen shot shows how the application appears at runtime.

Page 77
Chapter 5 Applets and components
10 Aug 2005

Installing the Java Plugin


Because of inter company politics, Microsoft does not ship a copy of the Java
plugin with its Internet Explorer web browser, and your users may find the idea of
downloading and installing such a piece of software intimidating. Fortunately Sun
has created a system whereby a user without the plugin will be offered the chance
to download, install and run the plugin, fairly automatically. The users still face the
delay of downloading a 5MB file the first time they try to access an applet, but this
is a one off problem, and with many users having improved bandwidth, this should
not be an insurmountable problem. Also you may modify the code to access a copy
of the plugin on your local network to reduce the download time still further. The
Java plugin is installed as an option when you install the Java Development Kit, so
as a student on this course you should have it installed by default.

To check for the presence of the plugin and to re-direct the users you can process
your html using a tool from the JDK called htmlconverter. This is a small graphical
tool that allows you to select the directory and file types you wish to convert, and it
then modifies your HTML to include the code needed to re-direct users who do not
have the plugin installed.

You can find out more about the htmlconverter from

http://java.sun.com/j2se/1.4.2/docs/guide/plugin/developer_guide/html_conv
erter_more.html

Java WebStart
If the you want to deploy Java code that needs greater access than the security of

Page 78
Chapter 5 Applets and components
10 Aug 2005

Applets, another distribution system is Java WebStart. WebStart is like a web


server based installation system that gives the benefit of making it easy to update
applications. WebStart uses the standard HTTP protocol, so it should not have
problems with FireWalls. If the application does require greater access than an
Applet you will be asked if you are happy to give this permission. This means that
you should be confident of the source of the program before you install it.

You can find out more about Webstart from sun at

http://java.sun.com/j2se/1.5.0/docs/guide/javaws/developersguide/faq.html

And you can see an interesting tool for creating UML diagrams that can be installed
via WebStart at

http://argouml.tigris.org/

Jar files

Most significant Applets will consist of more than one class file. The problem with
loading multiple class file through a web browser is that the HTTP protocol means
the browser has to "negotiate" the process of starting and closing a connection for
every individual file. This can add a significant overhead if there are multiple files.
Thus it can take a disproportional time to load an applet, by contrast with how long
it would take to load a single class file amounting to the same file size. There is a
solution to this problem in that Java class files can be “wrapped up” in a single Jar
file that contains the multiple class files required for the entire applet. The following
is a quote from the documentation for the jar utility.

“When the components of an applet or application (.class files, images and sounds)
are combined into a single archive, they can be downloaded by a Java agent (like a
browser) in a single HTTP transaction, rather than require a new connection for
each piece. This dramatically improves download time. The jar tool also
compresses files, which further improves download time”.

The command line syntax of the jar program can seem somewhat arcane, however
if you have a background in Unix/Linux the syntax is similar to that of the tar
archiving program. If you are a mere mortal you might like to become familiar with
the two following command lines.

Packing a Jar
jar -cvf MyJar.jar MyClass.class

Unpacking a Jar

Page 79
Chapter 5 Applets and components
10 Aug 2005

jar -xvf jarfile.jar

If it helps as a memory jerker you can consider the command lines to mean

-create -verbose -file

and

-xtract -verbose -file

of course if you are a mere mortal it may seem entirely spurious to have to specify
that you want to create to a file or extract from a file, but this syntax was "inspired"
by UNIX where there is no such thing as too much detail.

Quiz

1) Which of the following statements is true?

a. By default, applets may not access on the system of the browser user
b. Applets do not allow keyboard or mouse click events
c. Applet code executes on the server where they are retrieved from
d. Output from the System.out.print method will appear in the browser

2) Which of the following statements is true?

a. Applets do not use a layout manager


b. The default layout Manager for JApplet is null
c. The default layout manager for JApplet is FlowLayout
d. The default layout Manager for JApplet is BorderLayout

3) Applets run with many more restrictions than stand alone Java
applications, why is this?

a. Applets are interpreted whereas applications are compiled


b. The version of Java used by Applets is only a subset and thus is feature
restricted
c. Applets have to be synchronized with the host web browser
d. Applets can be loaded from any web site, and thus cannot be trusted by default

4) What html tag is used to indicate the start of an applet?

a. <binary>
b. <code>
c. <bytecode>
d. <applet>
e. <java>

Page 80
Chapter 5 Applets and components
10 Aug 2005

5) Which of the following statements is true

a. It is not possible to view any error message produced during the execution of an
applet
b. Systemm error messages produced by an applet will be displayed after the
applet destroy method
c. System error message produced by an applet get directed to the main applet
frame
d. System error messages produced by an applet can be viewed through the Java
console

Answers
Question 1

a. By default, applets may not access on the system of the browser user

This is part of the security system of applets, to prevent malicious programs


causing damage.

Question 2

a. The default layout manager for JApplet is FlowLayout

Question 3

d. Applets can be loaded from any web site, and thus cannot be trusted by default

Question 4

e. <applet>

In fact the tag <object> can also be used, but that is outside the scope of this book

Question 5

c. System error messages produced by an applet can be viewed through the Java
console

The Java plugin can be configured to automatically display the console when an
error occurs

Page 81
Chapter 06 More Objects
10 Aug 2005

Chapter 06 More Objects


OO Principles
So far this book has concentrated on using Java with a minimal coverage of the
underlying theory. This is based on the assumption that most people learn best
when doing rather than thinking. I have no time for the attitude that writing code is a
trivial activity done only by “code monkeys”, programming is a creative and
absorbing pastime that is inherently intellectually demanding. However every
programmer should be able to see the bigger picture needed by software architects
and system designers. From an organisational perspective creating software is
very expensive. Some projects have cost tens of millions of pounds and yet been
abandoned without success. In the early days of programming languages the main
objective was simply to allow programs to be written. Once that task was achieved
the focus moved on to allowing the management of complexity.

When i first started programming I thought that the people who created commercial
software must have been geniuses, people of an entirely different level of intellect
to myself. Over time I began to appreciate that much of what they achieved was not
due simply to raw intellect or ability but due largely to the management of
complexity. A great engineer such as those behind new aeroplanes or civil
engineering projects will generally not have an intimate knowledge of every nut, bolt
and rivet of the system, but will understand the systems in generalised overall
terms. Other designers and engineers will have a more intimate knowledge of each
subcomponent.

It is very important to understand the underlying theories behind the language, as it


can have a big effect on how you design and create your own programs, and it can
help you understand the thinking behind programs by other people, and the
reasoning behind the decisions of the overall architects of the system.

A brief history of objects

The designers of Java set out with the idea that it would be used for substantial
software engineering projects involving multiple programmers and designers. As a
result it supports features that are easy to overlook if you are new to the language
and writing your first programs in isolation. If this chapter seems overly theoretical
and abstract, bear with me as the ideas it contains are very important to the wider
world of software engineering.

Page 82
Chapter 06 More Objects
10 Aug 2005

Object Oriented programming is the latest in a series of efforts to make


programming easier by dealing with its inherent complexity. The first to major steps
in language developments was first the move from assembler to high level
languages. Assembler required an understanding of the CPU architecture of every
machine that was being programmed. If you think that the speed of a modern CPU
is measured in Mghz or millions of cycles per second, whereas the speed of the
first IBM PC was measured in terms of thousands of cycles per second, you can
appreciate how important raw performance used to be.

The limitations of assembler This made programming a complex task, but it did get
the maximum performance out of the system. The move to high level languages
meant languages could be portable across different hardware systems and they
were designed to be more like human languages rather than computer languages.

The next major step was the idea of structured languages where complexity could
be managed by breaking the program into discreet chunks of functionality by the
use of functions, named pieces of code that could be regarded almost as discreet
separate programs.

Object orientation is the latest concept to manage complexity in programming, and


it does this by attempting to tie code and data together so that objects (instances of
classes) “send messages” to each other. I find the use of the term “sending
messages” to be rather distracting and I regard methods as the OO version of
functions in structured programming. This may simply reflect my background in
structured languages such as C and Pascal rather than any reflection on the nature
of Object Oriented concepts.

Java is one of the more recent in a long line of Object Oriented programming
languages. One of the earliest and most influential was SmallTalk which was
developed at Xerox park in the late 1970's. Smalltalk never reached commercial
critical mass, but the C++ language developed at AT&T Bell Laboratories by Bjarne
Strousjoup became a huge success. This was partly because it built on the syntax
of the C language which was the de-facto standard for low level programming. C++
is a hybrid language which can be used to write in the older procedural way, or in
the Object Oriented style. In a similar way that C++ was an extension of C, Java
was modelled on C++. Unlike C++ Java was designed to be truer to the ideal of
Object Orientation. The use of OO in languages generally as a performance
overhead, but by a combination of optimisation and the increase in hardware
performance this has been largely offset.

The C# language created by Microsoft borrowed many of the ideas in Java and
attempted to improve on it. People who have programmed in C# say it is similar
enough to Java to make it easy to switch between the languages.

What is an object?

The terms object class are sometimes used interchangeably, but they are quite
separate, if related concepts. A class is the blueprint for an object. If you think of

Page 83
Chapter 06 More Objects
10 Aug 2005

the real world you could consider the plan for a house as being a class. Using the
plan for a house you can build many houses. Each one of those houses would be
considered an object of the type house.

The three central principles of Object Orientation are

• Inheritance

• Polymorphism

• Encapsulation

Inheritance

Inheritance is at the heart of Object Orientation, it means basing a new class on an


existing class. The use term inheritance comes from the way it is used in nature, as
in “I inherited my fathers large nose”, or “I inherited my grandfathers huge estate
and massive 90 bedroom stately home”. The idea is that rather than creating
functionality “from scratch” each time you can get it from an existing example. The
practical benefit is that a programmer has less work to do and the code that is used
will have been developed and tested over a longer period of time, which should
result in more reliable code. Another benefit of Inheritance is that you can inherit
most of the functionality of a parent class but modify some of that behaviour, again
all without necessarily having access to the source code of the parent class.

The relationship between classes that inherit from each other can be described in
several different ways, some of which are not obvious. Thus a class is said to be a
child of another or that it “inherits from another” . A class can also be described as
“a base class”, a slightly confusing term as base generally means at the bottom of,
and if you look at an inheritance tree, you might think that the most “recent” class
would be at the bottom and would thus be the base class. In OO terms the base
class is the one further up the inheritance tree, i.e. The grandparent or great
grandparent class. Where one class is a child of another it is sometimes described
as being a subtype of the other.

The keyword for inheritance is “extends”, thus one class extends another. Here is
an example

class Animal{
private String sName="animal";
public String getName(){
return sName;
}

public class Cat extends Animal{


public static void main(String argv[]){
Animal a = new Animal();
System.out.println(a.getName());

Page 84
Chapter 06 More Objects
10 Aug 2005

Note how the class Cat has no method called getName but because it extends the
class Animal it has access to that functionality. A class can only extend one other
class, as Java implements only single inheritance (i.e. One parent class, unlike
humans who have a default of two parents). A

Going back to the example of the Animal class as a base type, note that there is no
concrete example in the real world of a type of Animal that is just an Animal. All
animals are some other type, be that a Cat, Dog, bird or Cow. In the same way a
base class in Java will often be of a type that you may never create an instance of,
but is only used as the base class, or foundation of another.

The hierarchy of inheritance can be as deep as you like, i.e. you can have a child
with a parent, grandparent, great grandparent great, great, grandparent etc. etc.
(you get the picture). However in a similar way that hierarchies of disk directories
usually only go to a few levels it is more common to only have relatively shallow
hierarchies. You can see demonstrations of typical inheritance trees if you look at
the API (Application Programmer Interface) documentation of the Java class
libraries. For example if you take a look at any of the Collection classes you will see
what the parents and grandparents of a class are, and also what other classes
inherit from each class.

Polymorphism

The linguistic roots of the term polymorphism can be translated into “many
meanings”. In programming terms polymorphism is where multiple methods of the
same names have different meanings. Selecting method names is an important
skill for a programmer, choosing good names can make a big difference to how
easy it is to understand code. For this reason programmers have developed
naming conventions so that methods have similar names for similar purposes. Thus
in Java there is the JavaBeans naming convention that cover frequently recurring
tasks that methods are expected to perform. This takes the form of what are called
get and set methods e.g.

getFirstName
setFirstName

An experienced programmer will immediately recognise these methods as


“accessor” and “mutator” methods. Thus getFirstName will return information on a
field called firstname and setFirstName will set the value of the firstname field. A
programmer who was not familiar with the JavaBeans naming convention might
reasonably have created methods called findFirstName and updateFirstName, but
adhering to the established naming convention gives other programmers a slight
head start in understanding the code.

As most programming involves working with existing code, ease of understanding is

Page 85
Chapter 06 More Objects
10 Aug 2005

an essential attribute of good code. One of the ways polymorphism is implemented


in Java is via method overloading. This is where two methods have the same name
but different argument types.

If you have two methods with the same name, there is a need to distinguish
between the different versions. In java this is done via the argument list to the
method. Thus for example you could have

public update(String sFirstName)


public update(double dSalary)

Note how this shows two methods with the same name but different parameter
types. Thus any call to the method update will have a different meaning, depending
on the type of parameter passed to it. Thus a String parameter will call the first
version, whereas the second will call the double version. This is mainly of use to
programmers as it eases the burden of memorising method names. From a
computer/compiler perspective it would as efficient to have two different methods,
perhaps one called updateName and the other called updateSalary. In a small
program having two methods would not be a problem, but in an industrial sized
program with multiple programmers it places a slight additional burden on the
attention of programmers and the need for documentation.

Example PolyUpdate

public class PolyUpdate{


private String sFirstName;
private double dSalary;
public static void main(String argv[]){
new PolyUpdate();

}
/** Constructor for the class */
PolyUpdate(){
/*Note how the same method name is used to
call two versions of update method */
update("james");
update(10.1);

}
public void update(String sFirstName){
this.sFirstName = sFirstName;
}

public void update(double dSalary){


this.dSalary=dSalary;
}
}

In this example an anonymous instance of the program is created with the call

new PolyUpdate();

Within the constructor there are two calls to update, one receives a string and one

Page 86
Chapter 06 More Objects
10 Aug 2005

a double value. Java knows which version to call based on the data type passed to
the method. Note that the names of the parameter do not make any difference only
the type and order. Thus it would be considered overloading if you had two
methods as follows.

Overloaded methods are distinguished by the argument


type and order

public void update(double dSalary, String sFirstName){


/* method body goes here */
}

public void update(String sFirstName, double dSalary){


/* method body goes here */
}

Constructors
Constructors are special methods that have the same name as the class itself.
They were mentioned briefly in chapter 4, but they are worth looking at in detail as
almost any non trivial Java program will use them. In addition to having the same
name as the class a constructor must have no return type.

Thus in the following class the method MyCon is not a constructor.

public class MyCon{


public static void main(String argv[]){
MyCon mc = new MyCon();
}
public void MyCon(){
System.out.println("MyCon");
}
}

If you compile and run this code you will find that there is no output, because
method MyCon has a return type of void, which means it is not a constructor.

Overloading Constructors
Constructors can be overloaded in a similar way to methods. Constructors are
used to initialize classes, and it is common to want more than one way of initialize
an instance of a class. Thus you might have a quiz class you might have one
version that included a userid and one that had no associated user. Thus you could
have classes as follows.

public class Quiz{


Quiz(int iSubjectid, int iUserid){
/* constructor body */

Page 87
Chapter 06 More Objects
10 Aug 2005

}
Quiz(int iSubjectId){
/* no userid in this version */
}

Both of the following lines of code will instantiate Quiz objects.

Quiz q = new Quiz(1,1);


Quiz q2 = new Quiz(1);

Once you get used to overloaded constructors it is hard to imagine writing code
without them. I have written code using PHP4 and found the lack of overloaded
constructors to be quite frustrating.

Overriding and overloading


The terms overloaded and overridden are similar enough to give cause for
confusion. My way of remembering it is to imagine that something that is overridden
has literally been ridden over by a heavy vehicle and no longer exists in its own
right. Something that is overloaded is still moving but is loaded down with lots of
functionality that is causing it plenty of effort. This is just a little mind trick to
distinguish the two, it doesn't have any bearing of the reality on the operations in
Java.

Overriding is a term related to inheritance. A method is overriden in a subclass


when a substitute method of exactly the same name, parameters and return types
is implemented and thus replaces the version in the parent class. With an overriden
method its entire functionality has been replaced in the child class.

Overriding is useful in that it allows a programmer to inherit most of the functionality


of one class but to change that functionality slightly by replacing one or more of the
methods in the child class. The new (overriden) method will appear to be exactly
the same to any other programmer as it will have the same signature, i.e. Name,
parameter types and return type, but what it actually does, its functionality will be
different. This important in that it allows the programmer to keep the same
interface, the outward appearance whilst changing the inner workings.

The core Java language includes an example of overriding starting with the great
grandparent Object class. Every object in Java is implicitly a child (or ancestor at
least) of the Object class. The Object class has a method called equals, which in
the default implementation will compare the memory address of two different
classes. This is rarely what is wanted. So if you had two String objects you would
probably want the equals method to compare the sequence of characters within
each object. So it is no surprise that the Java String object does indeed override the
equals method with a new version that makes a character by character comparison.

Page 88
Chapter 06 More Objects
10 Aug 2005

Page 89
Chapter 06 More Objects
10 Aug 2005

Why Interfaces?

Some Object Oriented programming languages (such as C++) implement multiple


inheritance. This is where a class can inherit from more than one ancestor class
Implementing multiple inheritance is difficult for language designers and can cause
confusion and complexity when creating programs. Most C++ programmers rarely if
ever use multiple inheritance, so the designers of Java decided that it should only
allow single inheritance. To allow for the circumstances where multiple inheritance
is required Java uses a system called interfaces. A single Java class can implement
multiple interfaces.

Using Interfaces
It is possible to write vast amounts of working Java code without ever creating an
interface. Interfaces are more a design technique than an implementation tool, as
they are designed to give information to other programmers. They are part of what
is known as “design by contract”. An interface is a promise that certain functionality
will be implemented in the concrete classes that implement them.

“The interface keyword takes the abstract concept one step further. You could think
of it as a “pure” abstract class. It allows the creator to establish the form for a class:
method names, argument lists and return types, but no method bodies. An interface
can also contain data members of primitive types, but these are implicitly static and
final. An interface provides only a form, but no implementation.”
Bruce Eckel1997

(the term pure abstract is derived from the C++ language, so don't worry about that
term if you are not familiar with C++)

Thus for example, you might have an interface for a User for a software system
that has a promise that a method will be created for getting and setting the
password. The methods will take the form

getPassword
setPassword

Note how each method ends with the parenthesis and has no body, or { /*body */}
portion. On its own the interface does nothing as the methods have no bodies and
thus no functionality. An interface is used when a programmer implements the
interface and creates complete functions for all methods in the interface. So for
example the following class might implement the user interface as follows

interface iUser{
public String getPassword();
public void setPassword(String sPassword);
}

class User implements iUser{

Page 90
Chapter 06 More Objects
10 Aug 2005

private String sPassword;


public String getPassword(){
return sPassword;
}
public void setPassword(String sPassword){
this.sPassword=sPassword;
}
}

Note that interfaces are designed to allow the equivalent of multiple inheritance,
and for this purpose a class may implement multiple interfaces. To extend the
previous example further you could have a student class that also implemented an
called Person which would set out the “contract” for human beings. The following
example illustrates how this might be done for a Student class (assuming that
Students are assumed to be People).

import java.util.*;
interface iPerson{
public String getName();
public String setName(String sName);
}

interface iUser{
public String getPassword();

class Student implements iUser{


private String sPassword;
public String getPassword(){
return sPassword;
}

public void setPassword(String sPassword){


this.sPassword=sPassword;
}
}

Note that a class that implements an interface, must implement all the methods in
that interface. If it does not implement one of the methods, (or quite typically, gets
the signature slightly incorrect) a compile time error will occur. This makes sense as
the purpose of an interface is to ensure that the implementing class exactly
implements the interface as set out in the design.

Abstract Classes
Abstract classes are a little like interfaces in that they are mainly used by class
designers. They allow the creation of a class that cannot be instantiated itself but
can be extended by a child class.

abstract class Person{


public abstract String getName();

Page 91
Chapter 06 More Objects
10 Aug 2005

public abstract String setName(String sName);


}

class Student extends Person{


private String sPassword;
public String getPassword(){
return sPassword;
}

public void setPassword(String sPassword){


this.sPassword=sPassword;
}

Note how each method is marked as abstract as well as the class itself. Unlike an
interface where no method has a body, methods in an abstract class can have a
body. The following example shows an abstract class that has implemented
methods.

abstract class Person{


String sPhoneNumber;
public abstract String getName();
public abstract String setName(String sName);
public void setPhoneNumber(String sPhoneNumber){
this.sPhoneNumber = sPhoneNumber;
}
public String getPhoneNumber(){
return sPhoneNumber;
}
}

Encapsulation
The example code I have given in this chapter have used the technique of
encapsulation. The following code gives a simple example of this

public class Computer{


private String sProcessor;
public String getProcessor(){
return sProcessor;
}
public void setProcessor(String sProcessor){
this.sProcessor=sProcessor;
}
}

Note how the sProcessor String field is marked as private and can only be
accessed externally through the getProcessor and setProcessor methods (known
as accessors and mutator methods) or get and set methods. It would be possible to
create a class with very similar utility simply by marking the sProcessor String as
public and allowing it to be accessed and modified directly from outside the class.
The problem with that approach is that it would be easy to accidentally modify that
field, and if you needed to add any sanity checking” code you would have to do it
on an “ad-hoc” basis wherever you accessed the fields.

Page 92
Chapter 06 More Objects
10 Aug 2005

Encapsulation involves separating the interface of a class from its implementation.


This means you can't "accidentally" corrupt the value of a field, you have to use a
method to change a value

Encapsulation involves hiding data of a class and


allowing access only through a public interface.

Do not be mislead into thinking that the access control with the private keyword is to
do with security. It is not designed to prevent a programmer getting at variables, it is
to help avoid unwanted modification.

The separation of interface and implementation makes it easier to modify the code
within a class without breaking any other code that uses it.

For the class designer this leads to the ability to modify a class, knowing that it will
not break programs that use it. A class designer can insert additional checking
routines for "sanity checks" for the modification of fields. I have worked on
insurance projects where it was possible for clients to have an age of less than
zero. If such a value is stored in a simple field such as an integer, there is no
obvious place to store checking routines. If the age were only accessible via set
and get methods it will be possible to insert checks against zero or negative ages in
such a way that it will not break existing code. Of course as development continues
more situations may be discovered that need checking against.

For the end user of the class it means they do not have to understand how the
internals work and are presented with a clearly defined interface for dealing with
data. The end user can be confident that updates to the class code will not break
their existing code. When you are first learning to write Java code it may seem like
unnecessary extra work to create accessor and mutator methods, but it is a good
habit to get into as you move from a student of the language to a professional
practitioner.

Encapsulation is useful for many different programming problems. For example the
JDBC drivers used to access different database engines use the same interface to
access databases with very different implementations. If a user decides to switch to
a different database, e.g. from access to Oracle, the interface (the calls to the
JDBC driver) stays the same but the way the database behind that driver works
may be entirely different.

Objects and references

All manipulation of objects is done through references to objects. It is common to


see some confusion between references and the objects they refer to. References
are an indirect reference to the actual grouping of code and data which is the

Page 93
Chapter 06 More Objects
10 Aug 2005

object. Bruce Eckel makes a beautiful analogy when he says.

“You might imagine this scene as a television (the object) with your remote control
(the reference). As long as you’re holding this reference, you have a connection to
the television, but when someone says “change the channel” or “lower the volume,”
what you’re manipulating is the reference, which in turn modifies the object. If you
want to move around the room and still control the television, you take the
remote/reference with you, not the television.”

The implication of this is that you never directly manipulate an object reference.
Thus you can never use a math operator such as *, - or + on an object reference.

Quiz
1) Which of the following statements are true?
1) Methods in an interface can only have a return type of void
2) Methods in an interface have no body
3) Methods in an interface must be given a void argument type
4) Methods in an interface cannot be marked as public

2) Which of the following statements are true?


1) The terms base class and child class have the same meanings
2) The implements keyword is used to make one class a child of another
3) Java implements multiple inheritance through the extends keyword
4) The extends keyword is used to make one class a child of another

3) Which of the following statements are true?


1) All methods in an abstract class must be marked abstract
2) A class can implement multiple abstract classes
3) If a class has abstract methods it must be marked as abstract itself
4) Abstract methods must have a void return type

Page 94
Chapter 06 More Objects
10 Aug 2005

4) Which of the following statements are true?

1) Encapsulation requires that all methods should be marked as


private
2) Encapsulation is designed to separate interface from
implementation
3) Fields are marked as private to ensure greater program security

4) Encapsulation is designed to tie implementation more close to


interface

Answers

Question 1
2) Methods in an interface have no body

Question 2
4) The extends keyword is used to make one class a child of another
Java approaches multiple inheritance through the implements keywords, not the
extends keyword. The implements keyword is used when accessing an interface.

Question 3
3) If a class has abstract methods it must be marked as abstract itself

Page 95
Chapter 06 More Objects
10 Aug 2005

Question 4

2) Encapsulation is designed to separate interface from


implementation

Additional Reading

What is an Object (Sun Java Tutorial)

http://java.sun.com/docs/books/tutorial/java/concepts/object.html

Appendix
Topics Not Covered in this book

The title of this book is Welcome to Java, and it is designed as an introduction. The
term Java covers a huge range of technologies and it would be impossible to give a
reasonable introduction to all of the significant ideas under the Java Umbrella. This
section is designed to give some pointers to what I consider to be some of the more
important Java technologies as a starting point.

Threading

Java has threading built into the heart of the Java language unlike almost all other
mainstream programming languages. It allows you to write a single program with
multiple paths of execution, known as threads. For example it is possible to write a
mail client program that checks for the arrival of new emails with a separate thread
from the presentation code. When a new email arrives the main program can be
informed by the checking Thread. Being able to write effective and portable
threaded Java programs is a complex business.
http://java.sun.com/docs/books/tutorial/essential/threads/

Java Thread Programming


by Paul Hyde
ISBN: 0672315858

Page 96
Chapter 06 More Objects
10 Aug 2005

JDBC

Almost all non trivial Java applications require access to a database. When sun
wanted to create a set of libraries to access databases they modelled the design on
Microsofts ODBC and called it JDBC.

http://java.sun.com/docs/books/tutorial/jdbc/

Servlets and JSP.

Server side Java is a way of allowing access to Java applications through a web
browser. This means the user does not have to install a JVM, they only need a
standard web browser such as Internet Explorer or FireFox.

http://jakarta.apache.org/

Enterprise Java Beans

Enterprise Javabeans are frequently referred to by the acronym EJB. It is a server


side architecture for multi-tier client-server systems. If that means nothing to you,
then it might be more relevent to know that it is a technology adopted by many very
large corporations who appear to be willing to pay very handsomely for associated
knowledge. Two EJB development tools that are worth investigating from the
financial point of view are BEA WebLogic and IBM Websphere.

http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/EJBConcepts.html

http://www.jboss.org/products/index

J2ME/Mobile Phone Java


Considering the number of people who have smart mobile phones J2ME maybe the
most significant area of growth in the uptake of Java

http://java.sun.com/j2me/index.jsp

Page 97
Chapter 06 More Objects
10 Aug 2005

Book Recommendations
Headfirst Java
The style of the Headfirst series of books is something you will probably either like
or hate. They are very distinctive books with a strong element of humour, many,
many illustrations and are designed for learning not as a reference. They make
strong use of analogy and multiple ways of learning each item varying from
crosswords, quiz tests and fill in the blank tests. Rather than delivering the contents
and the reader trying to learn from it, they concentrate on learning, even to the
extent of having material on how to learn. The authors have been heavily involved
in http://www.javaranch.com the premier Java discussion forum and have had
almost universally favourable feedback on their writing.

Just Java
Peter Van Der Linden has been closely involved with Java from the very beginning.
This is not the best book for someone who has never done any programming
before, but he is excellent at explaining complex concepts. He covers more
concepts than HeadfFirst and this would probably act as a longer term reference to
HeadFirst.

Mughal and Rasmussen


This is a peculiar recommendation in some ways as this book is actually aimed at
people studying for the Sun Certified Java Programmers Exam. However unlike
many of the other books aimed at that audience this book also acts as a very good
technical book on Java. If you are considering going for that exam in the long run,
but looking for a good textbook then this is an excellent buy. You can tell how
knowledgeable the authors are as they describe me in the introduction as a “Java
guru”.

Thinking in Java (3rd Edition)


by Bruce Eckel

ISBN: 0131002872

Although you can download the text of this book from www.bruceeckel.com I
recommend you buy your own “dead tree” version. You can get an idea of how
good it is from the fact that it receives four out of a possible five stars based on 270
reviews. If you read the reviews you can see that those who give it a low rating are
almost universally clueless. It is a very good book.

Page 98
Chapter 06 More Objects
10 Aug 2005

Website Recommendations

http://www.javaranch.com

The JavaRanch discussions are the best on the web. It is usually the first site I visit
on every web visit I make and I am very proud to have been given the privileged
rank of moderator. Visitors and contributors to JavaRanch are some of the most
experienced, knowledgeable and helpful on the web (or anywhere if it comes to
that).

http://www.javalobby.org/

Plenty of Java discussion. Although it looks slicker than JavaRanch, and is worth
checking up on, it does not have the “grass roots” feel of JavaRanch.

http://www.theserverside.com/

Java on the server. Active discussion forums, interviews with movers and shakers.

http://java.sun.com/docs/books/tutorial/

The granddaddy of Java tutorials. It's not exactly in the same league as “HeadFirst
Java” in terms of readability but its big and its free, what more do you you want,
jokes?

How this book was created


I aimed to use only freely available tools to create the material for this book and
course. The text for this book was created in OpenOffice.org writer
(http://www.openoffice.org). Most of it was done in version 1.1.4 but some was
worked on in a late beta of version 2. OpenOffice writer is particularly suitable for
creating and managing long documents and with automatic generation of tables of
contents and alphabetical indexes. It also allows for the direct export of pdf versions
of documents was tested/compiled originally in JDK 1.4, with later content tested
against JDK 1.5.

Diagrams were created using Dia and argouml. These tools were used under a
mixture of Microsoft Windows XP and RedHat Fedora Linux. The content of the
course was designed to be exported to the moodle course management system.
(http://www.moodle.org). This export was mainly by hand using a cut and paste
approach with some code clean up done using NVU and HTML tidy
(http://www.nvu.org). Other tools used were the Gimp (http://www.gimp.org) for
bitmap image manipulation, emacs for code editing and indentation, NetBeans for
code manipulation

Page 99
Chapter 06 More Objects
10 Aug 2005

Alphabetical Index

A C
abstract 38 C 6, 38
Abstract classes 88 C/C++ 23, 25, 31
accessor 90 C# 10, 81
activeX 69 C++ 6, 29
adapter classes 43 C++ 81
add 51 case 38
ancestor 87 case sensitive 21
Animal 83 cast 65
Apple 6, 39 catch 38, 63
Apple Computer 39 Centre 50
applet 48, 70, 76 Certified 5
applets 9, 68 char 37p.
Applets 41 Character data 37
appletviewer 71 child 82
argument 84 Chinese 37, 66
argv 23 class 38, 81
array 57, 59 class level variable 36
ASP 9 clicks 42
assembler 81 colon 35
assembler 80 color syntax 19
AWT 39 columns 52
command line 57
B command prompt 11
compiled 6
backwards compatibility 29 compiler 84
base 82 component 48
Bill Gates 37 concrete classes 87
Bjarne Strousjoup 81 console 72
black box 18 Console 73
blueprint 81 const 38
body 89 constraints 50
boolean 30, 38 constructor 26
BorderLayout 50, 53 Constructors 65, 85
braces 57 continue 38
break 38 contract 88
browser 8 CPU 80
Browser 69 curly braces 31
Bruce Eckel 5 Cyrilic 66
bugs 35
button 26 D
buttons 24, 52
byte 38 Data Types 35

Page 100
Chapter 06 More Objects
10 Aug 2005

database 9 for loop 33, 58


default 38 Frame 27
Delphi 48 functions 22, 81
design by contract” 87
designers 80 G
device drivers 27
DLLS 70 get 90
do 38 goto 38
do/while 58 grandparent 64, 86
dollar 22 graphical 71
DOS 20, 22, 25, 65 graphics 24
double 38 great grandparent 17
dragging 49 GridLayout 50
dynamic link libraries 70 Gridlayouts 50
GUI 22, 24, 50
E
H
East 50
EJB 9 Hello World 26
else 38 HelloAp 26
emory address 86 Helloworld 21
Encapsulation 82, 90 HTML 9, 71
encryption 70 htmlconverter 76
engineering 68, 80 HTTP 77
engineers 80
Enterprise Java Beans 9
equals 86 I
error 79
European 37 I/O 63
event handling 42 I/O 66
exception 63 i++ 59
Exceptions 64 IBM 6, 27
extends 38, 82 IE 9
if 30, 38
if/else 30
F implements 38, 88
import 38
file 67 Informix 9
FileOutputStream 66 inheritance 17
FileReader 65 Inheritance 81
final 38 initialize 85
finally 38 inner classes 45
flash 68 Input 63
float 38 instanceof 38
floating point 37 instantiated 88
Flow control 29 int 37p.
FlowLayout 48, 50 interface 38, 43
for 38

Page 101
Chapter 06 More Objects
10 Aug 2005

interfaces 43, 87 M
internals 90
Internet 63
Macintosh 6, 24, 39
main 57, 71
J math 37
messages 81
Japanese 37 Metal 39
JApplet 54, 71 method signature. 17
Jar 77 methods 22
java 26 MFC 10, 29
Java.exe 14 Mghz 80
Java.io 63 Microsoft 69
JavaBeans 83 ASP 9
Javac 20 Bill Gates 37
javac.exe 14 C/C++ 37
Javascript 8, 68, 70 C# 10, 81
JavaScript 5, 27 cmd.exe 11
javax.swing 26 command.com 11
JButton 26 Console 73
JDBC 90 IE 9, 72
JDK 11, 27 Internet Explorer 76
JDK 1.1 66 MFC 29
JFrame 25p. Microsoft Foundation Class 29
JRE 69 Microsoft Foundation Classes 10
JSP 9 Netscape 73
plugin 76
K Visual Basic 29p.
Visual Basic, 10
keyword 22 Windows 6, 10p., 19
keywords 63 XP 19
Keywords 38 Windows 2000 19
Microsoft Foundation Class 29
Microsoft Foundation Classes 10
L modifiers 22
Motif 41
lass 77 Mozilla 73
layout 48p. multiple inheritance 87p.
Layout 48 multiple interfaces 87
length 58 mutator 90
libraries 24
Lifecycle 72
Linux 6 N
list box) 39
long 37p. naked 19
loop 33 native 38p.
loops 58 Netscape 9, 41p., 69, 73
new 38
North 50

Page 102
Chapter 06 More Objects
10 Aug 2005

null 38 portability 10
Portable 6
O pre-processor 25
preferred 48, 51
object 81 Primitive 36p.
Object Orientation 27 Primitives 37
Object Orientation private 38
class 16 programmers 29
inheritance 17 protected 38
Object Oriented 10, 81 public 22, 38
base 82
base type 83 Q
behaviour 16
child 82 quote 38
class 22
Encapsulation 82, 90 R
inheritance 26
Inheritance 81p. re-use 18
messages 81 region 50
Polymorphism 82 repaint 26
SmallTalk 81 return 38
UML 18 rows 52
82
Object Oriented 80
OO 82 S
Opera 9
Oracle 9 safer 35
Output 63 sandbox 70
overloaded 86 sanity checking 89
overridden 86 security 70
semi colon 23
sending a message 17
P Server Side 9
set 90
package 38 short 38
Packing 77 signatures 17, 70
palette 18 signed 70
palm 48 single inheritance 87
Panel 53 sizeof 37
parameters 22 SmallTalk 81
Pascal 17, 30, 81 software architects 80
Perl 5, 30 South 50
philosophy 48 sql 65
PHP 9, 36 square bracket 57
pixels 48 static 22, 26, 38, 57
PLAF 39 Stream 67
plugin 76, 79 Streams 63
Polymorphism 82

Page 103
Chapter 06 More Objects
10 Aug 2005

String 22, 37p., 84 Unpacking 77


StringBuffer 38 usable 28
Strings 59
student 90 V
subclass 86
subroutines 22 Vietnamese 37
subtype 82 Visual Basic 5, 10, 29p., 48
Sun 11, 29, 41, 76 visual components 28
Sun Microsystems 6, 27, 69 void 22, 38
Sun Microsystems volatile 38
browsers 42
JavaScript 42
JDK 27 W
JVM 42
plugin 42 web 68
Sun 29, 41 West 50
super 38 while 38, 58
Swing 25, 39 while loop 33
SwingSet2 68 WindowListener 43
switch 38 Windows 6
synchronized 38
syntax 29 X
System 23
System.exit(0) 44 Xerox 81
System.out.println 63 XP 9

T
tag 71 82
theory 80
this 38
throw 38, 63 +
throws 38, 66
transient 38 ++ 58
true 30
try 38, 63 <
try/catch 66
<applet> 71
U
1
UML 18
Unicode 37, 66 16 bit 37
Unix 6, 22, 41

Page 104

Vous aimerez peut-être aussi