SlideShare uma empresa Scribd logo
1 de 104
Baixar para ler offline
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/
Page 14
Java API Documentation
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.
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
Text 1: NetBeans Tool Palette
Illustration 1:
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.5bin
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
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java
Welcome 2-java

Mais conteúdo relacionado

Mais procurados

Font creatormanual
Font creatormanualFont creatormanual
Font creatormanualJorge Muñoz
 
A byte of python (2005)
A byte of python (2005)A byte of python (2005)
A byte of python (2005)vaibhsss
 
Manual smart ideas 5
Manual smart ideas 5Manual smart ideas 5
Manual smart ideas 5spejo
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>tutorialsruby
 
Fashion design essentials
Fashion design essentialsFashion design essentials
Fashion design essentialsStilguiden
 
Creating Scientific Posters
Creating Scientific PostersCreating Scientific Posters
Creating Scientific Postersemphemory
 
Poser 7 Tutorial Manual
Poser 7 Tutorial ManualPoser 7 Tutorial Manual
Poser 7 Tutorial Manualguestcf62c9
 
C:\fake path\askeet 1.0-en
C:\fake path\askeet 1.0-enC:\fake path\askeet 1.0-en
C:\fake path\askeet 1.0-enunivalle
 
ÍNDICE - General (4 páginas)
ÍNDICE - General (4 páginas)ÍNDICE - General (4 páginas)
ÍNDICE - General (4 páginas)FINA ORDORIKA
 

Mais procurados (16)

Font creatormanual
Font creatormanualFont creatormanual
Font creatormanual
 
Write it right
Write it rightWrite it right
Write it right
 
A byte of python (2005)
A byte of python (2005)A byte of python (2005)
A byte of python (2005)
 
Manual smart ideas 5
Manual smart ideas 5Manual smart ideas 5
Manual smart ideas 5
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
Fashion design essentials
Fashion design essentialsFashion design essentials
Fashion design essentials
 
Workbook vf
Workbook vfWorkbook vf
Workbook vf
 
Creating Scientific Posters
Creating Scientific PostersCreating Scientific Posters
Creating Scientific Posters
 
Surfer9 guide
Surfer9 guideSurfer9 guide
Surfer9 guide
 
Poser 7 Tutorial Manual
Poser 7 Tutorial ManualPoser 7 Tutorial Manual
Poser 7 Tutorial Manual
 
The language of school designebook
The language of school designebookThe language of school designebook
The language of school designebook
 
C:\fake path\askeet 1.0-en
C:\fake path\askeet 1.0-enC:\fake path\askeet 1.0-en
C:\fake path\askeet 1.0-en
 
Zambak it excel2010
Zambak it excel2010Zambak it excel2010
Zambak it excel2010
 
Connect now
Connect nowConnect now
Connect now
 
ÍNDICE - General (4 páginas)
ÍNDICE - General (4 páginas)ÍNDICE - General (4 páginas)
ÍNDICE - General (4 páginas)
 
Manual rational rose
Manual rational roseManual rational rose
Manual rational rose
 

Destaque

4 Benefits of Flexible Staffing When Outsourcing QA
4 Benefits of Flexible Staffing When Outsourcing QA4 Benefits of Flexible Staffing When Outsourcing QA
4 Benefits of Flexible Staffing When Outsourcing QAQASource
 
40% dos micro e pequenos empresários estão pessimistas com o futuro da economia
40% dos micro e pequenos empresários estão pessimistas com o futuro da economia40% dos micro e pequenos empresários estão pessimistas com o futuro da economia
40% dos micro e pequenos empresários estão pessimistas com o futuro da economiaSPC Brasil
 
Yves Doyon – L’homme d’affaires
Yves Doyon – L’homme d’affairesYves Doyon – L’homme d’affaires
Yves Doyon – L’homme d’affairesYves Doyon
 
Custom AHU Start-up Form
Custom AHU Start-up FormCustom AHU Start-up Form
Custom AHU Start-up FormMark Schwedel
 
Market research survey
Market research surveyMarket research survey
Market research surveyHarryateccles
 

Destaque (9)

Cijferlijst Master
Cijferlijst MasterCijferlijst Master
Cijferlijst Master
 
4 Benefits of Flexible Staffing When Outsourcing QA
4 Benefits of Flexible Staffing When Outsourcing QA4 Benefits of Flexible Staffing When Outsourcing QA
4 Benefits of Flexible Staffing When Outsourcing QA
 
filename_1
filename_1filename_1
filename_1
 
40% dos micro e pequenos empresários estão pessimistas com o futuro da economia
40% dos micro e pequenos empresários estão pessimistas com o futuro da economia40% dos micro e pequenos empresários estão pessimistas com o futuro da economia
40% dos micro e pequenos empresários estão pessimistas com o futuro da economia
 
Week5Activity2
Week5Activity2Week5Activity2
Week5Activity2
 
CV
CVCV
CV
 
Yves Doyon – L’homme d’affaires
Yves Doyon – L’homme d’affairesYves Doyon – L’homme d’affaires
Yves Doyon – L’homme d’affaires
 
Custom AHU Start-up Form
Custom AHU Start-up FormCustom AHU Start-up Form
Custom AHU Start-up Form
 
Market research survey
Market research surveyMarket research survey
Market research survey
 

Semelhante a Welcome 2-java

Swaroop c h a byte of python
Swaroop c h a byte of pythonSwaroop c h a byte of python
Swaroop c h a byte of pythonLagal Tchixa
 
Symfony metabook 2.0
Symfony metabook 2.0Symfony metabook 2.0
Symfony metabook 2.0Rengga Aditya
 
Arduino: 30 proyectos de Arduino para genio malvado
Arduino: 30 proyectos de Arduino para genio malvadoArduino: 30 proyectos de Arduino para genio malvado
Arduino: 30 proyectos de Arduino para genio malvadoSANTIAGO PABLO ALBERTO
 
Podcasting Legal Guide[1]
Podcasting Legal Guide[1]Podcasting Legal Guide[1]
Podcasting Legal Guide[1]legal3
 
Towards 2012 The New Legal Landscape
Towards 2012 The New Legal LandscapeTowards 2012 The New Legal Landscape
Towards 2012 The New Legal Landscapelegaladvice
 
Podcasting Legal Guide[1]
Podcasting Legal Guide[1]Podcasting Legal Guide[1]
Podcasting Legal Guide[1]legal5
 
Legal Advice On
Legal Advice OnLegal Advice On
Legal Advice Onlegal1
 
Legal Advice On
Legal Advice OnLegal Advice On
Legal Advice Onlegal1
 
Podcasting Legal Guide[1]
Podcasting Legal Guide[1]Podcasting Legal Guide[1]
Podcasting Legal Guide[1]legal5
 
Podcasting Legal Guide[1]
Podcasting Legal Guide[1]Podcasting Legal Guide[1]
Podcasting Legal Guide[1]legal4
 
Podcasting Legal Guide[1]
Podcasting Legal Guide[1]Podcasting Legal Guide[1]
Podcasting Legal Guide[1]legal2
 
Podcasting Legal Guide[1]
Podcasting Legal Guide[1]Podcasting Legal Guide[1]
Podcasting Legal Guide[1]legalcounsel
 
The Complete FreeBSD
The Complete FreeBSDThe Complete FreeBSD
The Complete FreeBSDjoonatantorga
 
The complete free bsd
The complete free bsdThe complete free bsd
The complete free bsdirul_11
 
Modelsim Tuttranslate
Modelsim TuttranslateModelsim Tuttranslate
Modelsim Tuttranslateguest2d20022
 
Drmx2004 Getting Started
Drmx2004 Getting StartedDrmx2004 Getting Started
Drmx2004 Getting StartedUiTM
 
Salesforce creating on_demand_apps
Salesforce creating on_demand_appsSalesforce creating on_demand_apps
Salesforce creating on_demand_appswillsco
 

Semelhante a Welcome 2-java (20)

Swaroop c h a byte of python
Swaroop c h a byte of pythonSwaroop c h a byte of python
Swaroop c h a byte of python
 
Symfony metabook 2.0
Symfony metabook 2.0Symfony metabook 2.0
Symfony metabook 2.0
 
Arduino: 30 proyectos de Arduino para genio malvado
Arduino: 30 proyectos de Arduino para genio malvadoArduino: 30 proyectos de Arduino para genio malvado
Arduino: 30 proyectos de Arduino para genio malvado
 
C sharp programming[1]
C sharp programming[1]C sharp programming[1]
C sharp programming[1]
 
Podcasting Legal Guide[1]
Podcasting Legal Guide[1]Podcasting Legal Guide[1]
Podcasting Legal Guide[1]
 
Towards 2012 The New Legal Landscape
Towards 2012 The New Legal LandscapeTowards 2012 The New Legal Landscape
Towards 2012 The New Legal Landscape
 
Podcasting Legal Guide[1]
Podcasting Legal Guide[1]Podcasting Legal Guide[1]
Podcasting Legal Guide[1]
 
Legal Guide
Legal GuideLegal Guide
Legal Guide
 
Legal Advice On
Legal Advice OnLegal Advice On
Legal Advice On
 
Legal Advice On
Legal Advice OnLegal Advice On
Legal Advice On
 
Legal Advice On
Legal Advice OnLegal Advice On
Legal Advice On
 
Podcasting Legal Guide[1]
Podcasting Legal Guide[1]Podcasting Legal Guide[1]
Podcasting Legal Guide[1]
 
Podcasting Legal Guide[1]
Podcasting Legal Guide[1]Podcasting Legal Guide[1]
Podcasting Legal Guide[1]
 
Podcasting Legal Guide[1]
Podcasting Legal Guide[1]Podcasting Legal Guide[1]
Podcasting Legal Guide[1]
 
Podcasting Legal Guide[1]
Podcasting Legal Guide[1]Podcasting Legal Guide[1]
Podcasting Legal Guide[1]
 
The Complete FreeBSD
The Complete FreeBSDThe Complete FreeBSD
The Complete FreeBSD
 
The complete free bsd
The complete free bsdThe complete free bsd
The complete free bsd
 
Modelsim Tuttranslate
Modelsim TuttranslateModelsim Tuttranslate
Modelsim Tuttranslate
 
Drmx2004 Getting Started
Drmx2004 Getting StartedDrmx2004 Getting Started
Drmx2004 Getting Started
 
Salesforce creating on_demand_apps
Salesforce creating on_demand_appsSalesforce creating on_demand_apps
Salesforce creating on_demand_apps
 

Mais de Adenekan Orlanshilay (8)

Why students fail
Why students failWhy students fail
Why students fail
 
Wkspb09
Wkspb09Wkspb09
Wkspb09
 
Word processing-dtp
Word processing-dtpWord processing-dtp
Word processing-dtp
 
Word03p3
Word03p3Word03p3
Word03p3
 
Word03p1
Word03p1Word03p1
Word03p1
 
Word03p2
Word03p2Word03p2
Word03p2
 
World famous-nursary-rhymes-volume-2
World famous-nursary-rhymes-volume-2World famous-nursary-rhymes-volume-2
World famous-nursary-rhymes-volume-2
 
World famous-nursery-rhymes-volume-1
World famous-nursery-rhymes-volume-1World famous-nursery-rhymes-volume-1
World famous-nursery-rhymes-volume-1
 

Welcome 2-java

  • 1. 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
  • 2. 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
  • 3. 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
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. 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
  • 12. 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
  • 13. 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
  • 14. 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/ Page 14 Java API Documentation
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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. 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 Text 1: NetBeans Tool Palette Illustration 1:
  • 19. 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
  • 20. 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.5bin 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
  • 21. 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
  • 22. 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
  • 23. 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
  • 24. 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
  • 25. 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
  • 26. 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
  • 27. 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
  • 28. 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
  • 29. 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
  • 30. 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
  • 31. 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
  • 32. 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
  • 33. 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
  • 34. 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
  • 35. 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
  • 36. 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
  • 37. 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
  • 38. 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
  • 39. 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
  • 40. 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
  • 41. Chapter 2 Syntax and Data Types 10 Aug 2005 The Metal (Java) Look and feel Page 41
  • 42. Chapter 2 Syntax and Data Types 10 Aug 2005 The Windows Look and feel Page 42
  • 43. 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
  • 44. 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
  • 45. 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
  • 46. 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
  • 47. 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
  • 48. 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
  • 49. 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
  • 50. 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
  • 51. 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
  • 52. 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
  • 53. 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
  • 54. 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