Java Programming Fundamentals
Java Programming Fundamentals
Fundamentals:
Student Guide
prosofttraining
TM
ComputerPREP
A division of ProsoftTraining
410 N. 44th Street, Suite 600
Phoenix, AZ 85008
(602) 275-7700
Contributors
James E. Roos, James Stanger, Ph.D., and Vartan Nazarian
Editors
Susan M. Lane and David Oberman
Publishers
Joseph Flannery and Joseph A. Servia
Project Managers
David De Ponte and Todd Hopkins
Trademarks
Prosoft is a trademark of ProsoftTraining. All product names and services identified throughout this book are
trademarks or registered trademarks of their respective companies. They are used throughout this book in editorial
fashion only. No such use, or the use of any trade name, is intended to convey endorsement or other affiliation with the
book. Copyrights of any screen captures in this book are the property of the software's manufacturer.
Disclaimer
ProsoftTraining makes a genuine attempt to ensure the accuracy and quality of the content described herein; however,
ProsoftTraining, makes no warranty, express or implied, with respect to the quality, reliability, accuracy, or freedom
from error of this document or the products it describes. ProsoftTraining makes no representation or warranty with
respect to the contents hereof and specifically disclaims any implied warranties of fitness for any particular purpose.
ProsoftTraining disclaims all liability for any direct, indirect, incidental or consequential, special or exemplary damages
resulting from the use of the information in this document or from the use of any products described in this document.
Mention of any product or organization does not constitute an endorsement by ProsoftTraining of that product or
corporation. Data used in examples and labs is intended to be fictional even if actual data is used or accessed. Any
resemblance to, or use of real persons or organizations should be treated as entirely coincidental. ProsoftTraining
makes every effort to ensure the accuracy of URLs referenced in all its material, but cannot guarantee that all URLs
will be available throughout the life of a course. When this course/disk was published, all URLs were checked for
accuracy and completeness. However, due to the ever-changing nature of the Internet, some URLs may no longer be
available or may have been re-directed.
Copyright Information
This training manual is copyrighted and all rights are reserved by ProsoftTraining. No part of this publication may be
reproduced, transmitted, stored in a retrieval system, modified, or translated into any language or computer language,
in any form or by any means, electronic, mechanical, magnetic, optical, chemical, manual or otherwise without written
permission of ProsoftTraining, 3001 Bee Caves Road, Austin, TX 78746.
iv
Version 6.1
Table of Contents
Course Description............................................................................................................................x
ProsoftTraining Courseware ..............................................................................................................x
Course Objectives ...........................................................................................................................xii
Classroom Setup .............................................................................................................................xii
System Requirements .....................................................................................................................xii
Conventions and Graphics Used in This Book ................................................................................xiv
Lesson 1: Java Runtime Environment .......................................................................................... 1-1
Pre-Assessment Questions ................................................................................................................ 1-2
The Java Virtual Machine.................................................................................................................. 1-3
The Java 2 Software Development Kit ................................................................................................ 1-4
Java Comments ................................................................................................................................ 1-4
Lesson 1 Review ................................................................................................................................ 1-7
Lesson 2: Data Types, Variables and Operators ............................................................................. 2-1
Pre-Assessment Questions ................................................................................................................ 2-2
Data Types ........................................................................................................................................ 2-3
Declaring Variables ........................................................................................................................... 2-3
Variable Scope .................................................................................................................................. 2-4
Casting ............................................................................................................................................. 2-5
Operators.......................................................................................................................................... 2-6
Automatic Casting............................................................................................................................. 2-8
Lesson 2 Review .............................................................................................................................. 2-10
Lesson 3: Control Statements ....................................................................................................... 3-1
Pre-Assessment Questions ................................................................................................................ 3-2
Code Blocks ...................................................................................................................................... 3-3
Conditional Statements ..................................................................................................................... 3-3
Iterative Statements (Loops) .............................................................................................................. 3-5
Assertions ......................................................................................................................................... 3-8
Lesson 3 Review .............................................................................................................................. 3-13
Lesson 4: Methods ........................................................................................................................ 4-1
Pre-Assessment Questions ................................................................................................................ 4-2
Java Methods.................................................................................................................................... 4-3
Return Statements ............................................................................................................................ 4-3
Calling a Method ............................................................................................................................... 4-4
Parameters........................................................................................................................................ 4-4
Pass by Value.................................................................................................................................... 4-4
Overloading....................................................................................................................................... 4-5
Lesson 4 Review ................................................................................................................................ 4-7
Lesson 5: Arrays............................................................................................................................ 5-1
Pre-Assessment Questions ................................................................................................................ 5-2
What Is an Array? ............................................................................................................................. 5-3
Initializing an Array........................................................................................................................... 5-3
Objects.............................................................................................................................................. 5-4
Using an Array .................................................................................................................................. 5-4
Passing an Array to a Method ............................................................................................................ 5-5
Garbage Collection ............................................................................................................................ 5-5
Command Line Parameters ............................................................................................................... 5-6
Hashing ............................................................................................................................................ 5-7
Lesson 5 Review .............................................................................................................................. 5-10
Lesson 6: Classes and Objects ....................................................................................................... 6-1
Pre-Assessment Questions ................................................................................................................ 6-2
Object-Oriented Programming ........................................................................................................... 6-4
What Is an Object? ............................................................................................................................ 6-4
Instance and Class Members............................................................................................................. 6-5
Abstraction ....................................................................................................................................... 6-8
Object References.............................................................................................................................. 6-8
Version 6.1
vi
Version 6.1
vii
Version 6.1
viii
List of Labs
Lab
Lab
Lab
Lab
Lab
Lab
Lab
Lab
Lab
Lab
Lab
Lab
Lab
Lab
Lab
Lab
Lab
Lab
Lab
Lab
1-1: Compiling and running your first Java program ...................................................................... 1-5
2-1: Using primitive variables and operators................................................................................... 2-9
3-1: Using while and for loops ........................................................................................................ 3-8
4-1: Writing methods in Java ......................................................................................................... 4-6
5-1: Using arrays in Java ............................................................................................................... 5-9
6-1: Creating your own classes in Java........................................................................................... 6-9
7-1: Implementing inheritance in Java ........................................................................................... 7-6
8-1: Building constructors in Java ............................................................................................... 8-13
9-1: Using interfaces and polymorphism in Java ............................................................................ 9-9
10-1: Using encapsulation, accessors and mutators in Java ......................................................... 10-6
11-1: Creating basic Swing components ..................................................................................... 11-18
12-1: Creating sophisticated layouts in Java .............................................................................. 12-13
13-1: Drawing to a JFrame ......................................................................................................... 13-10
14-1: Implementing a WindowListener for event handling in Java............................................... 14-10
15-1: Event-enabling your Java drawing application .................................................................... 15-5
16-1: Converting a Java application into an applet ..................................................................... 16-12
18-1: Creating a threaded digital clock in Java ........................................................................... 18-11
19-1: Enhancing the digital clock with advanced thread techniques in Java ............................... 19-13
20-1: Creating a simple word processor in Java.......................................................................... 20-16
21-1: Building a client/server chat system ................................................................................. 21-13
List of Figures
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Version 6.1
ix
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
Figure
List of Tables
Table
Table
Table
Table
Table
Table
Table
Table
Table
Table
Table
Version 6.1
Course Description
The Java Programming Fundamentals course teaches you how to write Java applications and applets. You
will learn the Java language mechanics found in other programming languages, such as variables,
iterations, control statements, methods and arrays. You will also discuss object-oriented theory as it
relates to Java. You will create Graphical User Interfaces (GUIs) for both applications and applets,
emphasizing components, layouts, and graphics. The course concludes with an in-depth study and
implementation of the SDK 1.2 event delegation model, an essential element in further Java studies. You
will also complete a course-long project to create an operational client/server messaging system.
Upon completion of this course, you will be experienced in writing Java applications and applets. We
recommend and will frequently refer you to another excellent Java resource, David Flanagan's Java in a
Nutshell. Students who plan to pursue the jCert Level I Certification or the Sun Java Programmer
certification are encouraged to study the CIW Sun Certified Java Programming Exam Preparation Guide
when preparing for the exams.
Length
Java Programming Fundamentals is a 30-hour course.
Series
Java Programming Fundamentals is a single course representing the CIW Java Programming series. This
series is part of the Master CIW Enterprise Developer track as well as the jCert Initiative. For students
interested in the jCert certification or the Sun Java Programmer certification, we recommend the CIW Sun
Certified Java Programmer Exam Preparation Guide.
The Java Programming Fundamentals course is also part of the CIW Web Developer series. For more
information, please visit the www.CIWcertified.com Web site.
Prerequisites
Students must have a basic knowledge of programming fundamentals before taking this course.
ProsoftTraining Courseware
This coursebook was developed for instructor-led training and will assist you during class. Along with
comprehensive instructional text and objectives checklists, this coursebook provides easy-to-follow
hands-on labs and a glossary of course-specific terms. It also provides Internet addresses needed to
complete some labs, although due to the constantly changing nature of the Internet, some addresses may
no longer be valid.
The student coursebook is organized in the following manner:
Version 6.1
xi
! course title
" table of contents
# list of labs
# list of figures
# list of tables
" lessons
# lesson objectives
# pre-assessment questions
# narrative text
$ graphics
$ tables and figures
$ warnings
$ tech notes
# labs
$ graphics
$ tables and figures
$ warnings
$ tech notes
# lesson summary
# lesson review
" appendixes
" glossary
" index
" supplemental CD
When you return to your home or office, you will find this coursebook to be a valuable resource for
reviewing labs and applying the skills you have learned. Each lesson concludes with questions that review
the material. Lesson review questions are provided as a study resource only and in no way guarantee a
passing score on CIW exams.
The course is available as either an academic or a learning center/corporate version. Each of these
versions has an instructor book and student books. Check your book to verify which version you have,
and whether it is an instructor or student book. Following is a brief discussion of each version.
Academic: Designed for students in an academic classroom environment; typically taught over a
quarter (10-week) or semester (16-week) time period. Example syllabi are included on the instructor
CD-ROM. The instructor's book and CD-ROM contain all answers, as well as activities (pen-andpaper-based labs), optional labs (computer-based labs), quizzes, a course assessment, and the
accompanying handouts for the instructor to assign during class or as homework. No answers exist
in the student book or on the student CD-ROM. Students will have to obtain answers from the
instructor.
Version 6.1
xii
Course Objectives
After completing this course, you will be able to:
%
Use the Java Abstract Windowing Toolkit (AWT) and Swing components central to SDK 1.2.
Throw exceptions.
Create threads.
Use streams.
Classroom Setup
Your instructor has probably set up the classroom computers based on the system requirements listed
below. Most software configurations on your computer are identical to those on your instructor's
computer. However, your instructor may use additional software to demonstrate network interaction or
related technologies.
System Requirements
Hardware
The following table summarizes the hardware requirements for all courses in the CIW program. Each
classroom should be equipped with enough personal computers to accommodate each student and the
instructor with his or her own system.
Version 6.1
xiii
Note: The CIW hardware requirements are similar to the lowest system requirements for Microsoft
implementation (Level 1 requirements) except that CIW requires increased hard disk space (8 GB) and RAM
(128 MB). This comparison may be helpful for the many training centers that implement CIW and are also
CTEC because personnel at these centers are familiar with the Microsoft hardware specifications.
Processor
L2 cache
256 KB
Hard disk
RAM
At least 128 MB
CD-ROM
32X
Sound card/speakers
Video adapter
At least 4 MB
Monitor
15-inch monitor
Network hubs
Router
Software
The recommended software configurations for computers used to complete the exercises in this book are
as follows.
Microsoft Windows 98/Me/XP, Windows 2000, Red Hat Linux 7.x or later, or any operating system
with an available Java 2 SDK
Sun Java 2 Software Development Kit (SDK), Standard Edition, version 1.2 or later
Connectivity
The minimum requirement is a networked classroom with TCP/IP installed. Each computer should have
its own IP address, or have local loop-back capability (IP 127.0.0.1). Internet connectivity is not required,
but it is helpful.
Supplemental CD-ROM
Each coursebook includes a supplemental CD-ROM. The files on the CD-ROM are important, as they are
referenced and used throughout the course. Because the labs will explicitly refer to the CD-ROM, the
instructor and students will access and load these files during class.
Version 6.1
xiv
Technology terms defined in the margins are indicated in bold the first time they
appear in the text. Not every word in bold is a term requiring definition.
Lab Text
Text that you enter in a lab appears in bold. Names of components that you access
or change in a lab also appear in bold.
Notations
Notations or comments regarding screenshots, labs or other text are indicated in italic
type.
Program Code or
Commands
Text used in program code or operating system commands appears in the Lucida
Sans Typewriter font.
'
This graphic indicates a line of code that is completed on the following line.
Version 6.1
1Lesson 1:
Java Runtime
Environment
Objectives
By the end of this lesson, you will be able to:
%
1-2
Pre-Assessment Questions
1.
2.
Which of the following employs the Java syntax for a multiline comment?
a.
b.
c.
d.
3.
Text files
*.java files
*.class files
*.exe files
// This is a comment.
/* This is a comment */
/** This is a comment */
/** This is a comment. **/
What benefit does the use of a virtual machine provide to Java developers?
______________________________________________________________________________________
______________________________________________________________________________________
______________________________________________________________________________________
Version 6.1
1-3
applet
A small Java
program that must
be run from a Web
browser.
Java Virtual
Machine (JVM)
The artificial
computer that runs
Java programs.
class
A type of container
into which all Java
code must be
placed. Also, the
template or
blueprint for an
object.
method
A procedural part of
a class that contains
executable Java
statements.
The Java Virtual Machine (JVM) gives Java its platform independence. One of the
primary design goals of the Java language is to enable the same code to run on any
platform. The JVM is a software program that behaves like an entire computer. By using
this artificial computer on different computer platforms (UNIX, Win32, Macintosh, and so
forth), you can reuse programs without creating a version for each platform. Your Java
programs will always run on a JVM. A Java program can be run on any platform for
which a JVM is available.
You will begin writing a simple program by defining a class. A class is a type of container
into which all Java code must be placed. You need not be familiar with classes already;
you will learn more about them in a later lesson. A class consists of a name and a pair of
curly braces to contain the body of the class. By convention, the class name should start
with a capital letter as in the following example:
class HelloWorld
{
}
When you write a stand-alone application, the Java Virtual Machine must know where to
begin executing the code. To begin executing code, the JVM looks for and calls a special
method by the name of public static void main(String[] args). The JVM uses
this method to begin executing your program. Study the following code example:
class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello World!");
}
}
This program is complete. Note that Java programs are case-sensitive; the word Class is
not read the same as class. You must save the program with your text editor as
HelloWorld.java (giving it the same name as your class), and compile it using a Java
compiler. You can use the javac program if you have the Java 2 Software Development
Kit (SDK) supplied by Sun.
javac HelloWorld.java
The Java compiler converts, or compiles, your source code (saved as HelloWorld.java, a
text file) and creates a HelloWorld.class file. This *.class file is no longer a standard
text file, but a file compiled into bytecode.
Version 6.1
1-4
bytecode
A platform-neutral
file consisting of
bytes that the JVM
can execute.
Bytecode is another element that makes Java different from other programming
languages. Other compiled programming languages generate machine code binaries,
which are files that contain native machine language statements. To make Java portable,
the javac compiler generates bytecode. Java bytecode is composed of an instruction set
native only to the JVM. Because JVMs exist for multiple platforms, the Java bytecode is
portable. Portability, however, comes at a price: speed.
Finally, to launch your program, you must run it in a JVM. You can accomplish this by
invoking the Java interpreter java as follows:
java HelloWorld
Note that you type java HelloWorld, not java HelloWorld.class. When you enter the
proper command, the JVM will display "Hello World!" in a command line window. The
Java application development cycle is shown in Figure 1-1.
Text Editor
javac
*.java
java
*.class
Output Window
Java Comments
Throughout the course, you will find it useful to add comments to your code. Java
supports three types of comments; two will be recognizable to those familiar with C or
C++, and the third type is unique to Java.
The three types of comments are as follows:
Single-line comment//
Multiline comment /* */
Javadoc comment
/** */
Version 6.1
1-5
You will use the single-line and multiline comments similar to C++.
4. Prompt: Execute HelloWorld. From the command line, enter the following:
java HelloWorld
Version 6.1
1-6
7. (Optional) Modify the public static void main(String[] args) method in any
way you choose (for example, delete the word void). What happens?
8. (Optional) Add some comments to the file to document each step that you made while
programming this application.
Lesson Summary
Application project
When Java was originally released, it was widely praised for its platform independence.
This platform independence made Java applets possible, allowing Web site operators to
develop applications that could be downloaded and executed by any client with a
compatible browser, regardless of platform. Search the Web for at least five examples of
Java applets in which the functionality could not be easily duplicated using server-side or
client-side scripting technologies.
Skills review
Java consists of three types of programs: applications, applets, and servlets. In this
lesson, you learned that applications contain a main method. After the program is written
as a text source file (having a name *.java), the program is converted into bytecode
(having a name *.class) by the Java compiler. The compiled bytecode can be executed
using the Java interpreter. In the following lessons, you will learn the basic syntax of the
Java programming language.
Now that you have completed this lesson, you should be able to:
(
Version 6.1
1-7
Lesson 1 Review
1.
______________________________________________________________________________________
______________________________________________________________________________________
2.
______________________________________________________________________________________
______________________________________________________________________________________
______________________________________________________________________________________
3.
What is a class?
______________________________________________________________________________________
______________________________________________________________________________________
4.
What is a method?
______________________________________________________________________________________
______________________________________________________________________________________
______________________________________________________________________________________
5.
Are Java programs case-sensitive? Give an example that describes its policy.
______________________________________________________________________________________
______________________________________________________________________________________
6.
______________________________________________________________________________________
______________________________________________________________________________________
______________________________________________________________________________________
______________________________________________________________________________________
______________________________________________________________________________________
7.
______________________________________________________________________________________
______________________________________________________________________________________
8.
______________________________________________________________________________________
______________________________________________________________________________________
Version 6.1