Java Workshop
- About
-
Chapters
- Installing Java
- The Eclipse IDE
- Java Packages
- Javadoc Comments
- Java Archive (Jar) Files
- Apache Ant
- Unit Testing
- Performing Logging
- XML Processing
- Appendices
- End Matter
About
Welcome to the Java Workshop
The programs in this book have been included for instructional value, the author does not offer any warranties or representations in respect of their fitness for a particular purpose, nor does the publisher accept any liability for any loss or damage arising from their use.
About The Book
Introduction
The original idea behind the Java Workshop was to introduce some of the practicalities faced when developing software using the Java Platform. As such, the original book focused on developing software using the Java Platform and not so much on the tools or the practical side of things. In revising the text, I decided to shift the focus somewhat to a new direction, the tools that a Java Developer should have in his / her toolbox.
It has often been said that the right tools for the job can make the job a lot easier. This is even more so when one considers the practice of developing software. When one uses the right tools, suddenly the task at hand becomes easier and quicker to accomplish creating a marked improvement in productivity. This book therefore focuses on the practical aspects of developing in Java specifically looking at common tasks and at the tools that make accomplishing these tasks easier and faster.
This is not a book that teaches Java. Instead it is a book that showcases typical tools found in a Java developer's toolbox. If you are looking for a book that teaches Java you should look elsewhere and once you've found such a book, you should couple it with this one, I guarantee the result will be worth it.
An "Open Source Book"?
The idea behind this is far from original. Credit must be given to Bruce Eckel's Thinking in Java, which is freely available on the web and also available in printed format. While I used a similar concept, the Java Workshop differs fundamentally in that it may be redistributed and modified, much like open source software. For those that are a little finicky about details, the license is available here: License.
Who The Book Is For
This book is for anyone interested in Java. Whether that interest is purely in an academic sense or truly a passion for the language, I hope that everyone can gain something from this book.
The target audience is specifically students who are learning Java for the first time. I remember when I first learnt Java, many of the trivialities were far from trivial and even the simple task of setting an environment variable was no small feat. I hope that if anything, this book will help students to accomplish these and many more trivial tasks and that they will not seem like small miracles.
The goal of this book is to introduce students to the practicalities of the Java language and provide them with enough references to pursue the topic further. In this regard, each topic is presented in a simplistic manner and a topic does not cover all there is, especially those topics that are extremely broad like XML. Rather a brief introduction is given and then a list of suitable references for further information.
Overview
Ironically my vision for the first edition was to showcase a number of tools for Java developers, however the book also included a large amount of theoretical content which was contrary to the idea of an introduction to the practicalities of programming with the Java platform; this second edition is much closer to a manifestation of that original vision than the first edition was.
I focused each chapter around a certain piece of software that I have found exceedingly useful, a tool that I consider to be an essential item in each developer's toolbox. This means that each chapter focuses around performing a specific task.
Topics Presented In The Book
Installing The Java Development Kit
Installing the Java Development Kit (JDK) is not difficult but it can be tricky for people that have never done it before. One of the most important learning experiences novice programmers can have is to install the JDK an set the PATH variable. Not only is it an enriching experience but also the satisfaction gained from accomplishing this task is monumental. I hope that the steps outlined in this theme will guide many to successfully install Java on their computers.
Using The Eclipse Integrated Development Environment
With all the IDEs available, many students may wish to become familiar with one of them and use it to write their programs with. The choice of which IDE to use is not an easy one, yet Eclipse has become the industry standard IDE surpassing many of its competitors. This chapter will look at installing and using this invaluable tool that every Java Developer should have.
Creating and Using Java Packages
Understanding Java Packages is key when one wishes to organize one's source code and this chapter will look at how to create and use Java Packages.
Using the Javadoc Tool to Produce an Application Programmer Interface
This chapter will focus on the importance of comments and the correct way to write Javadoc comments and will show how to use the Javadoc tool to produce an API.
Using the Jar Tool to Create Libraries and Executable Java Archive Files
Java Archives or jar files have become the most popular form of packaging and distributing Java software. It is thus imperative for students to understand what a jar file actually is, how to create one, view the contents and extract the contents as well as package software in an executable jar file.
Using Apache Ant to Simplify the Build Process
Small projects can quite easily be compiled from the command-line. Medium to large projects can become tedious to compile and package and therefore a build tool of some sort can make the process easier. In this regard, Apache Ant is simply the best build tool available. This chapter will discuss Ant and how to use it.
Using JUnit Framework to Perform Unit Testing
Unit testing is perhaps one of the most important aspects of software development. This chapter looks at how unit testing can be performed using the JUnit package.
Using Apache Log4J to Perform Logging
Logging is a very important way of debugging code as it provides a mechanism to see what a program is doing at every step of the way. This chapter looks at logging using the Apache Log4J package.
Processing XML with Apache Xerces
XML is used in a number of places and it is useful to know how to process it. This chapter will look at how to process XML using the Xerces parser as well as perform transformations using Apache Xalan.
Software and Versions Used
Keeping up to date with rapidly changing technologies is difficult at best. Below is the list of software and versions used during the writing of this book, by the time you read this there will no doubt be newer versions of some if not all the software listed below.
| Tool | URL | Chapter | Description |
|---|---|---|---|
| JDK 1.5.0 | java.sun.com | 1, 3-5 | The Java 2 Standard Edition SDK |
| Eclipse 3.0 | eclipse.org | 2 | The Eclipse IDE |
| Apache Ant 1.6.5 | ant.apache.org | 6 | The Apache Ant build tool |
| JUnit 3.2 | junit.sourceforge.net | 7 | JUnit unit testing framework |
| Apache Log4J 1.2.11 | logging.apache.org | 8 | Apache Log4J logging framework |
| Apache Xerces 2.7.1 | xml.apache.org | 9 | Apache Xerces XML parser |
| Apache Xalan 2.7.0 | xml.apache.org | 9 | Apache Xalan XML Transformation tool |
Conventions Used
Italic is used for emphasis.
Constant width is used for all code fragments, paths and filenames.
Constant width italic is used for general placeholders that indicate some item is replaced for an actual value.
Constant width bold is used for emphasis in a code fragment.
Reach Out
I would like your feedback. After you have had a chance to use this book please take a moment to e-mail me with your evaluation. I'd like to know what you liked, what was useful and more importantly what wasn't of use. Although I will read all mails I recieve, I cannot guarantee a reply.
tcmiller@users.sourceforge.net
Despite numerous efforts to ensure this book is error free, some errors have most likely slipped through. Even still, some of the material in this book will change or no longer be applicable over time. Please let me know of any errors or omissions in this text.
Trevor C. Miller
Pretoria, South Africa, January 5, 2006
Acknowledgements
This book would not have been possible if it were not for the aid and assistance of a number of people. First I would like to thank the people of Sun Microsystems, the Apache Software Foundation, IBM, and of course the Fedora Linux Community. All the software used to write this book came from these organizations that have all produced open source software of such a high standard that it often exceeds that of commercial software. The book was written on Windows using custom software that I wrote to produce the XML content. This was then transformed into static HTML using Apache Forrest. The book was also tested on Linux using Fedora Core.
I wish to thank all those wonderful people that I've had the pleasure tutoring and teaching, whether it was Java, C, C++ or Delphi. These people truly inspired me by persevering, and in those times they even challenged me by asking awkward questions that I at times didn't have an answer for. While I was teaching programming to these people, they in return taught me much; about teaching, about people and most importantly, about myself. To them I am ever grateful.
Lastly, writing this book wouldn't have been possible if it weren't for the music of Leftfield, Michelle Branch and 30 Seconds To Mars.
Download the Java Workshop
Editions
You can get the latest edition here.
Extracting The Archives
Windows
It is recommended that you download the zip distribution archive. Windows XP has a native built-in Zip tool that allows you to extract zip archives. Other versions can use the Jar tool bundled with the JDK to extract the contents of the archive. Tools like Winzip and ZipGenius can extract the zip archive as well as the tarball.
Linux / Unix
Most Linux and Unix distributions have the tar utility so it is recommended that you download the tarball. If you do not have tar you may have unzip in which case it is advisable to get the zip archive. If you do not have any of these utilities you can use the Jar tool bundled with the JDK to extract the contents of the zip archive.
Java Workshop Licence
Licensed under the Academic Free License version 2.1
This Academic Free License (the "License") applies to any original work
of authorship (the "Original Work") whose owner (the "Licensor") has
placed the following notice immediately following the copyright notice
for the Original Work:
Licensed under the Academic Free License version 2.1
1) Grant of Copyright License. Licensor hereby grants You a world-wide,
royalty-free, non-exclusive, perpetual, sublicenseable license to do
the following:
A. to reproduce the Original Work in copies;
B. to prepare derivative works ("Derivative Works") based upon the Original
Work;
C. to distribute copies of the Original Work and Derivative Works to the
public;
D. to perform the Original Work publicly; and
E. to display the Original Work publicly.
2) Grant of Patent License. Licensor hereby grants You a world-wide,
royalty-free, non-exclusive, perpetual, sublicenseable license, under
patent claims owned or controlled by the Licensor that are embodied in
the Original Work as furnished by the Licensor, to make, use, sell and
offer for sale the Original Work and Derivative Works.
3) Grant of Source Code License. The term "Source Code" means the preferred
form of the Original Work for making modifications to it and all available
documentation describing how to modify the Original Work. Licensor hereby
agrees to provide a machine-readable copy of the Source Code of the
Original Work along with each copy of the Original Work that Licensor
distributes. Licensor reserves the right to satisfy this obligation by
placing a machine-readable copy of the Source Code in an information
repository reasonably calculated to permit inexpensive and convenient
access by You for as long as Licensor continues to distribute the Original
Work, and by publishing the address of that information repository in a
notice immediately following the copyright notice that applies to the
Original Work.
4) Exclusions From License Grant. Neither the names of Licensor, nor the
names of any contributors to the Original Work, nor any of their
trademarks or service marks, may be used to endorse or promote products
derived from this Original Work without express prior written permission
of the Licensor. Nothing in this License shall be deemed to grant any rights
to trademarks, copyrights, patents, trade secrets or any other intellectual
property of Licensor except as expressly stated herein. No patent license is
granted to make, use, sell or offer to sell embodiments of any patent claims
other than the licensed claims defined in Section 2. No right is granted to
the trademarks of Licensor even if such marks are included in the Original
Work. Nothing in this License shall be interpreted to prohibit Licensor from
licensing under different terms from this License any Original Work that
Licensor otherwise would have a right to license.
5) This section intentionally omitted.
6) Attribution Rights. You must retain, in the Source Code of any Derivative
Works that You create, all copyright, patent or trademark notices from the
Source Code of the Original Work, as well as any notices of licensing and
any descriptive text identified therein as an "Attribution Notice." You must
cause the Source Code for any Derivative Works that You create to carry a
prominent Attribution Notice reasonably calculated to inform recipients that
You have modified the Original Work.
7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that
the copyright in and to the Original Work and the patent rights granted
herein by Licensor are owned by the Licensor or are sublicensed to You
under the terms of this License with the permission of the contributor(s)
of those copyrights and patent rights. Except as expressly stated in the
immediately proceeding sentence, the Original Work is provided under this
License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied,
including, without limitation, the warranties of NON-INFRINGEMENT,
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO
THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY
constitutes an essential part of this License. No license to Original
Work is granted hereunder except under this disclaimer.
8) Limitation of Liability. Under no circumstances and under no legal theory,
whether in tort (including negligence), contract, or otherwise, shall the
Licensor be liable to any person for any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or the use of the Original Work including,
without limitation, damages for loss of goodwill, work stoppage,
computer failure or malfunction, or any and all other commercial
damages or losses. This limitation of liability shall not apply to
liability for death or personal injury resulting from Licensor's
negligence to the extent applicable law prohibits such limitation.
Some jurisdictions do not allow the exclusion or limitation of
incidental or consequential damages, so this exclusion and limitation
may not apply to You.
9) Acceptance and Termination. If You distribute copies of the Original
Work or a Derivative Work, You must make a reasonable effort under the
circumstances to obtain the express assent of recipients to the terms
of this License. Nothing else but this License (or another written
agreement between Licensor and You) grants You permission to create
Derivative Works based upon the Original Work or to exercise any of
the rights granted in Section 1 herein, and any attempt to do so except
under the terms of this License (or another written agreement between
Licensor and You) is expressly prohibited by U.S. copyright law, the
equivalent laws of other countries, and by international treaty.
Therefore, by exercising any of the rights granted to You in Section
1 herein, You indicate Your acceptance of this License and all of its
terms and conditions.
10) Termination for Patent Action. This License shall terminate
automatically and You may no longer exercise any of the rights granted
to You by this License as of the date You commence an action, including
a cross-claim or counterclaim, against Licensor or any licensee alleging
that the Original Work infringes a patent. This termination provision
shall not apply for an action alleging patent infringement by combinations
of the Original Work with other software or hardware.
11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this
License may be brought only in the courts of a jurisdiction wherein the
Licensor resides or in which Licensor conducts its primary business, and
under the laws of that jurisdiction excluding its conflict-of-law
provisions. The application of the United Nations Convention on Contracts
for the International Sale of Goods is expressly excluded. Any use of the
Original Work outside the scope of this License or after its termination
shall be subject to the requirements and penalties of the U.S. Copyright
Act, 17 U.S.C. § 101 et seq., the equivalent laws of other countries,
and international treaty. This section shall survive the termination of
this License.
12) Attorneys Fees. In any action to enforce the terms of this License or
seeking damages relating thereto, the prevailing party shall be entitled
to recover its costs and expenses, including, without limitation,
reasonable attorneys' fees and costs incurred in connection with such
action, including any appeal of such action. This section shall survive
the termination of this License.
13) Miscellaneous. This License represents the complete agreement concerning
the subject matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable.
14) Definition of "You" in This License. "You" throughout this License,
whether in upper or lower case, means an individual or a legal entity
exercising rights under, and complying with all of the terms of, this
License. For legal entities, "You" includes any entity that controls,
is controlled by, or is under common control with you. For purposes of
this definition, "control" means (i) the power, direct or indirect, to
cause the direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
15) Right to Use. You may use the Original Work in all ways not otherwise
restricted or conditioned by this License or by law, and Licensor
promises not to interfere with or be responsible for such uses by You.
This license is Copyright (C) 2003-2004 Lawrence E. Rosen. All rights
reserved. Permission is hereby granted to copy and distribute this
license without modification. This license may not be modified without
the express written permission of its copyright owner.
Chapters
Installing Java
Jargon
- API
- Application Programming Interface, Set of related classes and methods that provide certain functionality. The API represents the parts of a class exposed through access modifiers to code written by other programmers.
- Compiler
- A computer program that translates a high-level programming language into machine language. The program fed into the compiler is called the source program; the generated machine language program is called the object program.
- Computer
- An electronic device that has the ability to store, retrieve, and process data, and can be programmed with instructions that it remembers. The physical parts that make up a computer (the central processing unit, input, output, and memory) are called hardware. Programs that tell a computer what to do are called software.
- Environment Variable
- A variable that specifies how an operating system or another program runs, or the devices that the operating system recognizes.
- JDK
- Java Development Kit, A software package that contains the minimal set of tools needed to write, compile, debug, and run Java applets and applications.
- Java
- Java is an object-oriented programming language developed initially by James Gosling and colleagues at Sun Microsystems. The language, initially called Oak (named after the oak trees outside Gosling's office), was intended to replace C++, although the feature set better resembles that of Objective C. Java should not be confused with JavaScript, which shares only the name and a similar C-like syntax. Sun Microsystems currently maintains and updates Java regularly.
- Platform
- In computing, a platform describes some sort of framework, either in hardware or software, which allows software to run. Typical platforms include a computer's architecture, operating system, or programming languages and their runtime libraries.
- Program
- A set of intangible instructions that tells a computer how to operate. Computer programs are also known as software.
- SDK
- Software Development Kit A set of programs that allows software developers to create products to run on a particular platform or to work with an API.
- Software
- A computer program that helps the user accomplish a specific task; for example, a word processing program. Application programs should be distinguished from system programs, which control the computer.
Introduction
In order to develop software using the Java language you will need to install a suitable compiler and interpreter on your computer. This will enable you to compile and run Java programs that you write.
This is not a complex process but varies depending on which platform you use. The platform will dictate the method you use to set variables as different platforms use different methods for achieving this task. Windows itself has different ways depending on which version of Windows you use. Linux and Unix based platforms also have numerous different ways of performing the same task.
Once you have installed Java, you may wish to consult some references. There are a number of excellent references available to Java programmers; some of these include Sun Microsystems's Java Page and the Java API.
You can get the JDK @ java.sun.com
How to install the JDK
For this installation, the latest version of Java was used at the time of writing, Java 1.5.0, but previous and later versions should work just fine.
Microsoft Windows 95
Installing the JDK
-
Run the setup program jdk-1_5_0-windows-i586.exe

-
Click "Continue" on the warning message.

-
Click "Accept Terms in License Agreement" then click on the Next button.

-
Select the components to install. If you are low on free space you can leave out the Demos and Source Code.

-
The wizard will now install the JDK files on your system. This may take a while.

-
Click the Next button to install the J2SE Runtime Environment

-
In the next dialog select the browsers to integrate the JRE with, I recommend all. Click the Next button.
-
The installation should be complete! Click the Finish button.

Setting the Path Variable
We need to set the path variable so that the system can find the Java compiler.
-
Open the Windows Explorer and navigate to the C:\ drive. Right-click on the file named Autoexec.bat and select edit from the menu.
WarningAutoexect.bat may not be visible if it is set as a hidden file. You should set folder options to display hidden files by selecting Options from the Folder menu. -
The file may be empty, but it will most likely contain some entries. You should add the following entries at the bottom of the file, after the last entries:
set JAVA_HOME=C:\Program Files\Java\jdk1.5.0 set PATH="%PATH%;%JAVA_HOME%\bin"
NoteIf you changed the installation location of java to some other location, you will have to change the location here to. -
Save the file, close the text editor and restart your computer.
Microsoft Windows 98
Installing the JDK
-
Run the setup program jdk-1_5_0-windows-i586.exe

-
If you use Windows 98 First Edition and get the warning message, click "Continue" on the warning message.

-
Click "Accept Terms in License Agreement" then click on the Next button.

-
Select the components to install. If you are low on free space you can leave out the Demos and Source Code.

-
The wizard will now install the JDK files on your system. This may take a while.

-
Click the Next button to install the J2SE Runtime Environment

-
In the next dialog select the browsers to integrate the JRE with, I recommend all. Click the Next button.
-
The installation should be complete! Click the Finish button.

Setting the Path Variable
We need to set the path variable so that the system can find the Java compiler.
-
Open the Windows Explorer and navigate to the C:\ drive. Right-click on the file named Autoexec.bat and select edit from the menu.
WarningAutoexect.bat may not be visible if it is set as a hidden file. You should set folder options to display hidden files by selecting Options from the Folder menu. -
The file may be empty, but it will most likely contain some entries. You should add the following entries at the bottom of the file, after the last entries:
set JAVA_HOME=C:\Program Files\Java\jdk1.5.0 set PATH="%PATH%;%JAVA_HOME%\bin"
NoteIf you changed the installation location of java to some other location, you will have to change the location here to. -
Save the file, close the text editor and restart your computer.
Microsoft Windows 2000
Installing the JDK
-
Run the jdk-1_5_0-windows-i586.exe setup program.
-
Select Accept with the Terms in the License Agreement and click the Next button.

-
Select the components you wish to install. If you are low on disk space you can leave out the Demos and Source Code. Click the Next button to continue.

-
The installer will now copy files to your computer, this may take a while.

-
Install the Public Java Runtime Environment by clicking the Next button. You should not have to edit any settings here.

-
Select which browsers to integrate the runtime environment with. I recommend all.

-
That should take care of the installation. The JDK is now successfully installed on your system.

Setting the Path Variable
We need to set the path variable so that the system can find the Java compiler.
-
Right click on the My Computer icon on the desktop and select Properties from the pop up menu. Click the Environment Variables button.

-
Under the System Variables section click the New button to add a new variable.

-
Add a variable named JAVA_HOME with the value C:\Program Files\Java\jdk1.5.0 and click the Ok button.
NoteIf you installed Java to a different location, you should change the value here to reflect this. -
Lastly edit the variable named PATH, add a semi colon (;) after the last entry in the value field and then add C:\Program Files\Java\jdk1.5.0\bin

Microsoft Windows XP
Installing the JDK
-
Run the jdk-1_5_0-windows-i586.exe setup program.

-
Select Accept with the Terms in the License Agreement and click the Next button.

-
Select the components you wish to install. If you are low on disk space you can leave out the Demos and Source Code. Click the Next button to continue.

-
The installer will now copy files to your computer, this may take a while.

-
Install the Public Java Runtime Environment by clicking the Next button. You should not have to edit any settings here.

-
Select which browsers to integrate the runtime environment with. I recommend all.

-
That should take care of the installation. The JDK is now successfully installed on your system.

Setting the Path Variable
We need to set the path variable so that the system can find the Java compiler.
-
Right click on the My Computer icon on the desktop and select Properties from the pop up menu. Click the Environment Variables button.

-
Under the System Variables section click the New button to add a new variable.

-
Add a variable named JAVA_HOME with the value C:\Program Files\Java\jdk1.5.0 and click the Ok button.
NoteIf you installed Java to a different location, you should change the value here to reflect this. -
Lastly edit the variable named PATH, add a semi colon (;) after the last entry in the value field and then add C:\Program Files\Java\jdk1.5.0\bin

Linux (Red Hat, Fedora Core & Mandrake)
Installing the JDK
-
Start a shell. Copy the Linux installer to the /usr/local directory.
cp jdk-1_5_0-linux-i586.bin /usr/local
-
Now change into the /usr/local directory and run the installer.
cd /usr/local chmod +x jdk-1_5_0-linux-i586.bin ./jdk-1_5_0-linux-i586.bin
-
Read through the license agreement and if you agree type yes. This will start the installer.
-
If everything goes well you should end up with output that ends with:
Done.
Setting the Path Variable
-
Create the file named java.sh in the directory named /etc/profile.d using your favourite text editor. I used Vi.
cd / touch /etc/profile.d/java.sh vi /etc/profile.d/java.sh
-
Add the following to the file.
export JAVA_HOME=/usr/local/jdk1.5.0 export PATH=${PATH}:${JAVA_HOME}/bin -
Make the script executable.
chmod +x /etc/profile.d/java.sh
-
Log out and then log in again for the changes to take effect.
Sun Solaris
The JDK should be installed and setup by default. For information on upgrading go to Sun's Website and browse through the Solaris documentation.
MacOS
Most newer versions of MacOS have the JDK installed and setup by default. For information on upgrading check out the MacOS documentation.
Compiling and Running Java Programs
Compiling Java Programs
We will now test our installation by compiling and running a simple Java Program.
Microsoft Windows
-
Open the Notepad text editor Start > All Programs > Accessories > Notepad and type the following program into it:
class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } -
Save the program to the C:\ drive in a file named HelloWorld.java. Make sure to select "All Files" in the Type field of the Save As dialog box.
-
To compile the program, open the Dos Prompt Start > All Programs > Accessories > Command Prompt and type:
cd\ javac HelloWorld.java
If you don't get any errors then everything went well. If you get errors, check firstly that you saved the program on the C:\ drive and that it is named HelloWorld.java.
Linux
-
Start your favourite text editor and type the following program in it, then save it in a file named HelloWorld.java in your home directory.
class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } -
To compile the program, start a shell and use the Java Compiler:
cd ~ javac HelloWorld.java
If you don't get any errors then everything went well. If you get errors, check firstly that you saved the program in your home directory and that it is named HelloWorld.java.
Solaris
-
Start a text editor, either vi in the command line or Gedit. Type the following program in it then save it in a file name HelloWorld.java in your home directory.
class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } -
To compile the program, start a shell and use the Java Compiler:
cd ~ javac HelloWorld.java
If you don't get any errors then everything went well. If you get errors, check firstly that you saved the program in your home directory and that it is named HelloWorld.java.
Running Java Programs
-
To run the program, type:
java HelloWorld
you should get the following output:
Hello World!
Common Errors and Solutions
-
Exception in thread "main" java.lang.NoSuchMethodError: main
You must define a main method as: public static void main(String[] args) {...}
-
HelloWorld.java:3: illegal character: \8220 System.out.println(öHelloWorld!ö);
Do not type your code in a word processor application that uses smart quotes!!
-
HelloWorld.class Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorld/class
The correct way to call a program is java HelloWorld without the ".java" or ".class"
Valuable Resources
The Java Application Programmer Interface
The Java API is an Application Programmer Interface that describes in great detail the core Java Foundation Classes that make up the Java Platform. It highlights which packages make up the Platform, which classes belong to which packages and what methods and fields are available in each class. It is an invaluable tool to any Java Programmer.

Sun's Java Page
Sun Microsystems's Java page can be accessed via the Internet at http://java.sun.com and it provides a download page where you can download all of the Java Technology that you want. It includes documentation: API's, Tutorials, Short Courses and White Papers. It often has industry news and updates and is also an invaluable resource to any Java programmer.

Summary
In order to compile and run Java programs you need to install the J2SE SDK and set the PATH environment variable. Setting an environment variable is dependent on the underlying platform.
Compiling java programs is done using the "javac" command and running them with the "java" command.
The Java API and Sun's Java page are exceptional resources for any Java programmer.
Exercise Set
Multiple Choice
-
The JDK is available for which platforms?
- Windows
- Linux
- MacOS
- Sun Solaris
- All of the above
-
The JDK contains:
- Tools to develop software for the Java Platform
- A Java Runtime Environment
- The core Java API
- The Java Source Code
- All of the above
-
Installing the JDK requires:
- Extracting the JDK archive.
- Depends on the platform.
- Running the installation binary.
- Setting the path and classpath variables.
- 1 and 4.
-
The Java API:
- Explains which packages form the core of Java Programming Language
- Which classes are located in which package.
- Which methods a class contains.
- The fields that the class contains.
- All of the above.
-
Sun's java page:
- Contains the Java Tutorial.
- Contains all the Java Software.
- Is not worth visiting.
- 1 and 2.
- 2 and 3.
Exercises
- Install the JDK on your own computer.
- Compile and Run the Hello World program.
- Browse through the Java API.
- Browse the Java page at Sun Microsystems's site: java.sun.com
- Download or browse the Java Tutorial at: http://java.sun.com/docs/books/tutorial/index.html
Programming Exercises
- Go read through the Java Tutorial at Sun's Java page and then try the following programs:
- Change the Hello World program so that it prints out your name.
- Write a program to display the first twenty powers of two.
- Write a program that generates a temperature conversion chart between Fahrenheit and Celsius.
- Write a program to display the first twenty Fibonacci numbers.
- Write a program that reads a number and displays it's square root.
The Eclipse IDE
Jargon
- Command
- An instruction given to the computer, by means of a keyboard, punch card, mouse, voice command, or other method.
- Console
- The command prompt window that rece ves output from a System.out.print call.
- Drive
- A device that spins disks or tapes in order to read and write data; for example, a hard drive, floppy drive, CD-ROM drive, or tape drive.
- Error
- A mistake made by a software developer that introduces a defect in a computer program.
- Generate
- The automated creation of source code.
- IDE
- Integrated Development Environment, an IDE combines the editor, compiler and other useful tools in the same software package. Its advantage is that when a program with syntax errors is compiled, the programmer sees the error messages and the original program at the same time -- this makes debugging much easier.
- Refactor
- Refactoring is the process of rewriting written material to improve its readability or structure, with the explicit purpose of keeping its meaning or behavior.
- Syntax
- The rules by which the words in a program are combined to form commands to a computer.
- Syntax Highlight
- Syntax highlighting is a feature of some text editors that displays text, especially source code, in different colors and fonts according to the category of terms. This feature eases writing in a structured language such as a programming language or a markup language as both structures and syntax errors are visually distinct.
- Zip
- To zip a file is to compress it into an archive so that it occupies less disk space.
Introduction
Often newcomer's to programming will find editing source files in a text editor to be tedious. Seasoned developers hardly ever use a text editor either. An Integrated Development Environment (IDE) provides the functionality to edit source code, compile it and run the source code all from within a single application.
Eclipse is an excellent open source IDE for Java. It is developed by IBM and written in Java itself. Eclipse provides a wide range of capabilities and features; we will look at this useful IDE in this chapter.
You can get Eclipse @ www.eclipse.org
Installing The Eclipse SDK
The first thing we need to do is to install Eclipse.
Installing on Windows
-
Extract the eclipse archive to the C:\ drive using a program like Winzip or ZipGenius. You should end up with a folder in the C: drive named eclipse.
-
The eclipse program is in the eclipse folder and is a file named eclipse.exe. You can double click this file to run the program. You might want to create a shortcut to this file on your desktop or in your start menu.
Installing on Linux
-
Copy the Eclipse SDK archive to the /usr/local directory.
cp eclipse-SDK-3.0-linux-gtk.zip /usr/local/
-
Change into the /usr/local directory and extract the archive.
cd /usr/local/ unzip eclipse-SDK-3.0-linux-gtk.zip
-
Edit the file named java.sh in the /etc/profile.d directory and add the following to it.
NoteIf you installed java according to chapter 1 you should have a file named java.sh in the /etc/profile.d directory. If not, now would be an opportune time to create it.export ECLIPSE_HOME=/usr/local/eclipse
-
Now add ECLIPSE_HOME to the PATH variable, save the file and exit your editor.
PATH=${PATH}:${ECLIPSE_HOME}Log out and then log in again for the changes to take effect.
-
Run Eclipse: in a terminal type
eclipse
-
In the dialog that asks you to select a workspace click the OK button. After eclipse has started, you will get a welcome screen.
Creating a Hello World Application
The best way to learn about Eclipse and its features is to start using it; we will therefore create a simple Hello World application using it.
Create a New Java Project
-
Start eclipse with the command:
eclipse
-
Select a workspace from the dialog and ensure to check the box that makes it the default workspace.
-
In the welcome screen, click on the "Workbench" icon.
-
From the File menu, select New and then Project.
File > New > Project
-
In the New Project Dialog, click Java Project and then click the Next button.
-
In the New Java Project Dialog enter Hello World as the Project name and click the Finish button.
-
A dialog will pop up asking you to confirm the switch to the Java Perspective. Check the checkbox that reads Remember my decision and then click the Yes button.
-
In the Java Perspective, in the left side of the screen is the Package Explorer. In it you will see the Project named Hello World. Make Sure it is selected.
Create a New Class
-
Select File from the menu and click New. Select Class.
File > New > Class
-
In the New Java Class dialog enter HelloWorld as the name of the class, ensure that the public static void main(String[] args) checkbox is selected and then click the Finish button.
-
You'll notice in the source code editor that the class has already been created for you.
Add Source Code
-
In the main method, type
System.
You'll notice a popup, prompting you to select a member of the System class. Select the out member.
-
Append the following to the line:
.println("Hello World!") -
You'll notice a red squiggly line under the closing bracket. This indicates that there is an error in your code. Add a semi colon (;) and it will disappear.
Save the Code
-
Select Save from the File menu to save the changes to the source code. You'll notice that Eclipse compiles source code automatically, every time that you save it.
File > Save
Run the Program
-
Right Click on the HelloWorld.java file in the Package Explorer and select Run followed by Java Application from the pop up menu.
Run > Java Application
-
You'll notice the output in the console.
Some Advanced Features
Configuring Some Preferences
We will now change a few of the default preferences.
-
Select Preferences from the Window menu.
Window > Preferences
-
Click the arrow next to Workbench to expand the sub categories and select Colors and Fonts. In the right pane expand Java and then Java Editor Text Font. Click the Change button, and change the font according to your preferences.
-
In the left pane, expand the Java category and then the Code Style sub category. Select Code Templates. In the right pane select Comments and then Types. Click the Edit button and change the comment to your preferences.
-
Now select Code and then the New Java files sub category. Click the Edit button and change the comment according to your preferences.
-
In the left pane select Editor and select the Show line numbers check box.
-
Select the Syntax tab in the right pane and change the color of the keywords from mauve to blue. Click the Apply button.
-
Click the Ok button. You'll notice that the changes have taken effect in the source code editor.
Create a New Project
We will now create a project outside of eclipse and then import it into eclipse.
-
In your home directory, create some directories:
mkdir ~/test mkdir ~/test/src mkdir ~/test/classes
-
In Eclipse, create a new project by selecting New from the File menu and then select Project.
File > New > Project
-
In the dialog, ensure that Java Project is selected and click the Next button.
-
In the next dialog, use Test as the project name. Then click the radio button that reads Create project at external location. Click the browse button and select the test directory in your home directory. Be sure to click the Next button.
-
In the source folders list, select Test and click the remove button. Click the Add Folder button and select the src directory. Click the OK button.
-
Click the browse button to change the Default output folder and select the classes directory. Click the Ok button.
-
The resulting changes should be as follows:
-
Click the Finish button.
Create Some Packages
You'll notice the Test project in the Package Explorer. We will define a package for our project.
-
In the package explorer expand the Test project.
-
Right click on the src folder in the package explorer and select New and then Package. Add test as the package name and click the Finish button.
-
You will now see the empty package in the Package Explorer.
Create a New Class
We will create a simple class in the package we have just created..
-
Right click on the Test package. Create a new class named Cat by selecting New and then Class from the pop up menu.
-
Add two variables, one named age of type int and one named name of type String.
-
Add a simple constructor to initialize the variables.
Generate Getters and Setters
Now we will use eclipse to generate getter and setter methods for our class.
-
Select Generate Getters and Setters from the Source menu.
Source > Generate Getters and Setters
-
In the dialog click the Select All button followed by the Ok button.
-
You'll notice that the get and set methods were created.
-
Don't forget to save the file.
Refactoring
We would like to change the name of the package from test and have all changes reflected. First we will create a main program that will use our class.
-
Create a new package named com.acme.test.main
-
Create a program called Main in the new package.
-
Add the following code to the main method.
Cat kitty = new Cat()
-
You will again notice some squiggly red lines. In the gutter next to the line numbers you will see a hint icon. Click on it.
-
In the pop up hint you will be prompted to import the Cat class. Do so, by clicking on the suggestion. You will notice that an import statement has been added to your code, namely: import test.Cat. Save the class.
-
Right click on the test package in the Package Explorer and select refactor from the menu. Select Rename from the sub menu.
Refactor > Rename
-
Rename the package to com.acme.test.pets .
-
If you look at the main class, you'll notice that the import statement has changed to match the new package name, ie: import com.acme.test.pets.Cat!
Installing a Plug-In
Eclipse is designed in such a way that third party developers can create plug-ins for it. One such plug-in allows you to edit XML files: it provides syntax highlighting for XML and code completion.
Installing a plug-in in Eclipse is a simple and painless process. All plug-ins are distributed in zip compressed archives, much like eclipse. All you have to do is extract the archive in the correct directory within Eclipse and it should work out of the box.
For this installation, we're using the XML buddy plug-in form here.
-
If you open an XML file in Eclipse you will notice that Eclipse uses the default text editor for XML files. This allows you to edit the files but it doesn't provide features common to most IDE's. In this case, installing a plug-in will help.
- Close Eclipse before proceeding.
- Extract the archive to location of your choice. This results in a folder named com.objfac.xmleditor_version.
-
Move this folder into a folder named plugins within the eclipse folder.
-
Start Eclipse and open an XML document, you should see that it is now syntax highlighted.
Summary
Eclipse is an advanced and feature rich IDE for the Java language. It is simple to install and easy to learn to use. We will be using this valuable tool in the next few chapters in this book.
Exercise Set
Multiple Choice
-
Eclipse is written in which language?
- Pascal
- C
- C++
- Java
- Delphi
-
Eclipse is:
- Proprietary Software
- Commercial Software
- Open Source Software
- Shareware
- Freeware
-
Which is not a feature of Eclipse
- Eclipse allows easy refactoring of code.
- Eclipse is available for many platforms.
- Eclipse has Apache Ant integrated into it.
- Eclipse requires you to compile source code after it is saved.
- Eclipse has JUnit integrated into it.
-
Eclipse allows you to:
- Generate new classes and interfaces quickly and easily.
- Use third-party plug-ins.
- Generate getters and setters.
- Refactor code.
- All of the above.
-
Eclipse is available for:
- Windows
- Linux
- Sun Solaris
- 1 and 2.
- 2 and 3.
Exercises
- Install the Eclipse on your own computer.
- Create the Hello World program described in this chapter.
- Import your existing projects into Eclipse.
- Configure the Preferences of Eclipse according to your taste.
- Install the plug-in as described in this chapter.
Programming Exercises
- Complete the following programs using Eclipse:
- A program that calculates how much is left of a bank loan. Input parameters are initial loan amount, interest rate, payment per month and current month.
- A program to calculate the average of a list of numbers.
- A program that calculates a student's grade from grades, each counting an equal percentage.
Java Packages
Jargon
- Attribute
- A single piece of information that represents a property present in all instances of a class. An attribute is often modeled as a variable in a class.
- Byte
- The amount of memory space used to store one ASCII character, which is usually 8 bits. A bit is the smallest unit of information a computer can hold; short for binary digit, the value can be either one or zero.
- Component
- A piece of software with a clear function that can be isolated and replaced by another component with equivalent functionality.
- Function
- A method that performs some form of processing in order to return a result. For example, a function to calculate the sum of two integers.
- Input
- Something put into a system or expended in its operation to achieve output or a result.
- Library
- A library is a collection of subprograms used to develop software. Libraries are distinguished from executables in that they are not independent programs.
- Namespace
- A scoping construct to subdivide the set of names and their visibility within a system. In many languages, this is tied to other computational constructs, eg, classes, procedures, modules, packages. A mechanism used to resolve naming conflicts.
- Performance
- A major factor in determining the overall productivity of a system, performance is primarily tied to availability, throughput and response time.
- Statement
- An entity in a programming language which is typically the smallest indivisible unit of execution.
- Sub-class
- A class that is an extension of another class and inherits public and protected variables and methods from the other class. Also known as a derived class.
Introduction
In order to provide namespace management Java provides the mechanism of creating Java Packages. A Java Package can be thought of as a collection of Java source files, usually grouped by functionality. In order to utilize Java fully you should understand how packages work.
Java Packages
What is a Package?
One of the many concerns that programmers face today is trying to ensure that their source code does not conflict with the source code of other programmers. A typical example is the case when two programmers define two distinct classes that have the same name. Suppose you decide to write a List class that keeps a sorted list of objects. This would inherently conflict with the List class in the Java API that is used to display a list of items in a Graphical User Interface. Java has a simple solution to this problem that is known as namespace management. Each programmer defines their own namespace and place their code within that namespace, thus two classes that have the exact same name are now distinguishable since they occur in different name spaces. Namespaces are called packages in Java.
Another important reason for using packages is that it provides programmers with greater control over their source code. It is typical to have a few thousand source files in medium to large scale applications, and trying to maintain them would be difficult at best, if not impossible. However, separating these source files into packages makes it much easier to manage the source code. What usually occurs is that related classes are grouped into a single package, for example, all the user interface classes of an application will be grouped into a package.
Access protection is another benefit of using packages. Suppose a group of different applications utilize the same set of source code, it would make sense to separate this source code and maintain it as a separate library that each application uses. In such a library, there is a public interface and a private interface. The public interface is those classes and methods that are accessible to the application using the library, while the private interface is not accessible to the application. Using a package makes it easier to define which classes form part of the public interface and which are part of the private interface. This makes it easy to control access to certain code sections.
Some of the benefits of using packages are:
- It shows that the classes and interfaces in the package are related.
- Often a group of classes and interfaces are related according to functionality so naturally they should be grouped into a package. An excellent example is the java.io package which groups a set of classes that all perform input and output functions.
- You know where to find the classes you want if they're in a specific package.
- If you are looking for a specific class and you know what functionality it provides you will naturally be able to find it in the right package. If you are looking for an InputStreamReader you will find it in the input and output package, ie: java.io
- The names of your classes and interfaces won't be in conflict with those of other programmers.
- If you decide to implement your own String class and you place it in a package it will be distinguishable from the java.lang.String class that comes with the Java API.
- You can restrict the access to your classes.
- When you only want your code or program to access certain code, for example in a library, then using packages makes access control to source code much easier.
Creating Packages
Creating a Java Package is relatively simple but may seem a bit confusing for people who have not done it before. There are two fundamental requirements for a package to exist:
- The package must contain one or more classes or interfaces. This implies that a package cannot be empty.
- The classes or interfaces that are in the package must have their source files in the same directory structure as the name of the package.
Naming Packages
Since packages are used to create namespaces that are used to prevent the problem of name conflicts, namespaces must be unique. This means that package names must be unique. Naming a package is therefore a very important aspect of creating a package.
Often organizations that are involved in software development will use their organi ation's domain name, since domain names by definition are unique. The domain name is inverted to make it easier to read. Good examples can be found from looking at the source code of the Apache Software Foundation, whose domain name is www.apache.org. All their code is placed into packages that have names beginning with org.apache.
Since the Apache Software Foundation has a number of sub-projects, each with its own web address, the project name is also used in the package name. The Ant project can be found at http://ant.apache.org, and it should be no surprise that their code is in the packages with names beginning with org.apache.ant.
When naming your package you should take your inverted domain name, if you have one, and add the project name to it. This will ensure that you have a unique package name, since it is highly unlikely that your organization is working on two projects that have the exact same name. As an example: com.mycompany.myproject
Some companies have decided to drop the top level domain (com, org, net, ...) from their package names for the sake of brevity, this is still perfectly acceptable: mycompany.mypackage
Declaring Package Members
The first thing to do when creating a package is to decide which classes and interfaces should belong to that package. Once you have decided that, you need to specify this by adding a package declaration to the source file of each class and interface that is a part of the package.
The declaration is simple, you use the package keyword followed by the package name. This declaration comes right at the top of the source file, before any import statements.
/*
* File comments...
*/
package com.mycompany.myproject;
import java.util.*;
class MyClass {
}
Source and Class File Organization
One of the requirements for a package is that the source file should be contained in a directory structure that resembles the name of the package. This is simply creating a set of directories with the names given in the package name.
Take the package name and split it up according to where the periods (.) occur, for example, com.mycompany.myproject can easily be split up into three components, namely: com, mycompany and myproject. These will be the three directories that you create. The first directory will be the com directory and within this directory you will create a sub directory namely the mycompany directory and within that directory a sub directory, namely the myproject directory.
Finally, all the source files that are part of the package will go into the myproject directory.
It is typical in many java project to have the source code go into a src directory and when it is compiled, the resulting byte code goes into a classes directory. The package directories will therefore go into the src directory. As an example, consider a class named MyClass in the package named com.mycompany.myproject and all source code in the src directory. The following picture depicts this situation clearly:

Compiling The Package
At first it may seem like a nightmare trying to compile the package, especially having the resulting class files occur in the classes directory, but it can be achieved using a single command. You don't even need all the package directories under the classes directory since they will be created in the compilation.
To try this out, create a test directory and all the sub directories required:
mkdir test mkdir test\src mkdir test\classes mkdir test\src\com mkdir test\src\com\mycompany mkdir test\src\com\mycompany\myproject
Now create the MyClass source file named MyClass.java in the test\src\com\mycompany\myproject directory.
/* MyClass.java
* Author: Trevor Miller
*/
package com.mycompany.myproject;
public class MyClass {
}
Change into the test directory and compile the package:
cd test javac -d ./classes/ ./src/com/mycompany/myproject/*.java
If you take a look in the classes directory, you will find the exact same directory structure as in the src directory. You'll also find a MyClass.class file in the test\classes\com\mycompany\mypackage directory. This is good as it allows you to keep your source and class files separate and provides greater control over your files.

Using Packages
Once you have created your package you may want to use it in your program or you may wish to use another programmer's package or the packages in the Java API. There are three ways of using the resources in a package; inline package member declarations, importing only the package member that you want and importing the entire package.
Inline Member Declarations
In this approach you simply declare the package member you wish to use with its fully qualified package name. As an example, suppose you wish to use the Vector class in the java.util package. You can easily declare a vector using java.util.Vector vector;
When you initialize the object by calling its constructor, you will again have to use the fully qualified package name.
class Test {
java.util.Vector vector;
Test() {
vector = new java.util.Vector();
}
}
Importing a Single Package Member
Using the inline declaration works well if you only use it a few times in your source code, but it can become a pain to type the fully qualified package name if you use it often. Instead you want to do this once and only once, and from then on, simply use the member's name wherever you need it.
This is easily achieved using an import statement in which the import keyword is followed by the fully qualified name of the member you wish to use. Consider the example given previously, but revised to use this method:
import java.util.Vector;
class Test {
Vector vector;
Test() {
vector = new Vector();
}
}
Importing an Entire Package
It may be that you use a number of members from a package and end up with a large number of import statements. As an example consider the following:
import java.util.Vector;
import java.util.LinkedList;
import java.util.Hashtable
import java.util.Stack
import java.util.Set
class Test {
...
}
This can become messy quite quickly, and you would like to get away from this. The answer is to simply import the entire package, again using the import statement but instead of declaring the member you use a wildcard symbol to indicate that everything should be imported. The wildcard symbol is an asterisk (*), using this method you can replace all the import statements of the previous example with simply one import statement.
import java.util.*;
class Test {
...
}
As you can see, this is much cleaner but it does have its limitations. If the package is very large and you import everything in the package, this will impact the performance of your program. You should consider carefully whether greater clarity in your code and ease of writing the code outweighs the addition of some overhead to the performance of your application.
Summary
Packages are a great way to organize your source code and split source code from byte code (class files). Understanding how packages work is vital to writing quality software.
Exercise Set
Multiple Choice
-
Namespaces are used to:
- Control access to classes.
- Resolve naming conflicts among programmers.
- Bundle a set of classes together.
-
Which is not a benefit of using packages?
- Finding the classes you want is difficult.
- Access protection.
- Separation of source and class files.
-
To create a package named "za.co.nephila.maculata" you would use which statement?
- package maculata
- package nephila.maculata
- package za.co.nephila.maculata
-
To import the ChatServer member of the Maculata package (za.co.nephila.maculata) you would use:
- import maculata.*;
- import za.co.nepihla.maculata.*;
- import za.co.nephila.maculata.ChatServer;
-
The classes of the Maculata package (za.co.nephila.maculata) will be in which directory?
- /Maculata/classes
- /Maculata/classes/za/co/nephila/maculata
- /Maculata/src/za/co/nephila/maculata
Exercises
- Take a look at the Java API and see how the packages are structured.
Programming Exercises
- Complete the following:
- Create a package named org.shapes.
- Create s


