Java Student Programming Manual Tutorial & Exercises

User Manual: manual pdf -FilePursuit

Open the PDF directly: View PDF PDF.
Page Count: 207

DownloadJava - Student Programming Manual Tutorial & Exercises
Open PDF In BrowserView PDF
▼
▼
▼

ZDU Student Manual

JAVA
PROGRAMMING:
PART 1

Java Programming: Part 1
ISBN:

0-73725-349-5

Part number:

ZDU56705

ACKNOWLEDGMENTS
Content Development
The content of this self-study guide is based on the training course "Java Programming,"
developed by Instruction Set, Inc. for its curriculum of instructor-led technical training.
This guide was designed and developed by an Instruction Set team of instructional
designers, course developers, and editors.

Administration
Vice President and General Manager of ZD University: Ed Passarella
Marketing Director: Risa Edelstein
Director, ZD University: George Kane
Senior Editor, Curriculum: Jennifer Golden
Project Director, Instruction Set: Laurie Poklop
Project Manager, Instruction Set: Sandy Tranfaglia

DISCLAIMER
While Ziff-Davis Education takes great care to ensure the accuracy and quality of these materials, all
material is provided without any warranty whatsoever, including, but not limited to, the implied warranties of merchantability or fitness for a particular purpose.
Trademark Notices: ZD University and Ziff-Davis Education are trademarks and service marks of ZiffDavis Inc. Java Programming: Part 1 is a Copyright of Instruction Set, Inc. All other product names
and services used throughout this book are trademarks or registered trademarks of their respective
companies. The product names and services are used throughout this book in editorial fashion only
and for the benefit of such companies. No such use, or the use of any trade name, is intended to
convey endorsement or other affiliation with the book.
Copyright © 1998 Instruction Set, Inc. All rights reserved. This publication, or any part thereof, may
not be reproduced or transmitted in any form or by any means, electronic or mechanical, including
photocopying, recording, storage in an information retrieval system, or otherwise, without the prior
written permission of Instruction Set, Inc., 16 Tech Circle, Natick, MA 01760, (508) 651-9085, (800)
874-6738. Instruction Set’s World Wide Web site is located at http://www.InstructionSet.com.
ZD University’s World Wide Web site is located at http://www.zdu.com.
Photocopying any part of this book without the prior written consent of Instruction Set, Inc. is a violation of federal law. If you believe that Instruction Set materials are being photocopied without permission, please call 1-800-874-6738

CONTENTS

Java Programming: Part 1
LESSON 1: FUNDAMENTAL ASPECTS OF PROGRAMMING
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
What Is Programming? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
A Brief Overview of Software Development . . . . . . . . . . . . . . . . .3
Conceptual Differences Between Software and Hardware. . . . . . .4
Conceptual Differences Between the Developer and the User . . . .4
Programming Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4
Syntax vs. Semantics. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5
Types of Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Console Versus Windows-Based Applications . . . . . . . . . . . . . . .6
Procedural Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7
Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . .7
Event-Driven Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9
C/C++/Java Language Family . . . . . . . . . . . . . . . . . . . . . . . . . . . .9
The Common Language Core . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10
Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11
Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11
Expressions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13
Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13
Program Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15
Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16
Scoping. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19
Lesson Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

iv

JAVA PROGRAMMING: PART 1

LESSON 2: THE JAVA ENVIRONMENT
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Uses for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29
The World Wide Web (WWW) . . . . . . . . . . . . . . . . . . . . . . . . .30
HTML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .30
Competing Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31
Java Characteristics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Java Portability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .33
Advantages and Disadvantages. . . . . . . . . . . . . . . . . . . . . . . . . . .34
Applications vs. Applets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .34
Application/Applet Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Writing Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35
Compiling an Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .37
Running the Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .38
Tools and Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
The javadoc and jdb Tools . . . . . . . . . . . . . . . . . . . . . . . . . .41
Using packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .41
Searching for Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .42
The import Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .43
Packages, Classes, Files, Directories. . . . . . . . . . . . . . . . . . . . . . .44
Lesson Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

LESSON 3: JAVA BASICS
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Language Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .50
Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51
Declaring Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .53
Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54
Expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Java Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .56
Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .57
Precedence and Associativity . . . . . . . . . . . . . . . . . . . . . . . . . . . .61
Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Control Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .65

CONTENTS

Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Lesson Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76

LESSON 4: CLASSES IN JAVA
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Java Is Object-Oriented . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Classes, Objects and Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Instantiating a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Class-Type Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Operations on Class-Type Variables. . . . . . . . . . . . . . . . . . . . . . . . . . 81
The null Value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Member Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Invoking a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Class Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Declaring Instance Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Declaring Instance Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
The this Variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Class Definitions and Source Files. . . . . . . . . . . . . . . . . . . . . . . . 89
Lesson Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92

LESSON 5: CLASSES IN JAVA—II
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Method Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Encapsulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Access Specifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Comparing Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Class Variables. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Class Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
final Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Class Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Finalization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Lesson Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

v

vi

JAVA PROGRAMMING: PART 1

Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104

LESSON 6: ARRAYS AND STRINGS
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Java Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Array Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Using Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Copying Array Elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
String Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
String Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
String Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .110
String Searching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .112
Other String Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .113
String Concatenation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Converting Objects to Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Converting Strings to Numbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Lesson Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118

LESSON 7: INHERITANCE
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Introduction to Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Example of Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121
Derivation Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .122
Effects of Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .122
Protected Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Overriding Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
Dynamic Method Dispatching. . . . . . . . . . . . . . . . . . . . . . . . . .125
Polymorphism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .126
The super Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .127
Final Methods and Final Classes . . . . . . . . . . . . . . . . . . . .128
Constructor Chaining . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Inheritance and Finalization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Abstract Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132

CONTENTS

The implements Declaration . . . . . . . . . . . . . . . . . . . . . . . . 133
Casting Between Class Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Lesson Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

LESSON 8: WRITING JAVA APPLETS
Objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
What Is an Applet? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
A "Hello, World" Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
The Applet Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Invoking an Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
Getting Applet Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Specifying Applet Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 146
The Delegation Event Model—Action Events . . . . . . . . . . . . . . . . 146
The ActionEvent Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Adjustment Events . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
The paint() Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
The Graphics Class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Java Fonts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
Selecting a Font . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Drawing Lines and Shapes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
Drawing with Color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
The Color Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Foreground and Background Colors . . . . . . . . . . . . . . . . . . . . . 157
Lesson Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Review Questions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Exercise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161

APPENDIX A: HYPERTEXT MARKUP LANGUAGE (HTML)
HTML History and SGML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Structure. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Head Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Formatting: Blocks and Separators . . . . . . . . . . . . . . . . . . . . . . . . . .
Formatting: Physical . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Netscape List Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

164
165
165
166
166
167
167

vii

viii

JAVA PROGRAMMING: PART 1

Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Forms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
Tables (HTML 3) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
Miscellaneous Netscape Extensions. . . . . . . . . . . . . . . . . . . . . . . . . . 170
Java Applets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Java Script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171

APPENDIX B: JAVA SAMPLE
Usage and Copyright Notification . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
The XYZApp.java Source. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175

APPENDIX C: JAVA CLASS HIERARCHY
Java Class Hierarchy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186

ANSWERS: TO REVIEW QUESTIONS
Lesson 2
Lesson 3
Lesson 4
Lesson 5
Lesson 6
Lesson 7
Lesson 8

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198

▼
▼
▼

LESSON 1
Fundamental Aspects of
Programming
OVERVIEW
Learning to use a programming language effectively requires a good
background in the principles of software development. The novice
programmer must visualize the software development process as a whole,
from requirements analysis through testing. The various types of
programming and their implications must be understood clearly. To
facilitate this, the several basic components of programming and
programming languages are explicated in this lesson by applying them to
an incrementally developed software example.

LESSON TOPICS
● What Is Programming?
● Types of Programming
● The Common Language Core
● Program Structure

2

JAVA PROGRAMMING: PART 1

➤➤➤

OBJECTIVES
By the end of this lesson, you should be able to:

➤ Explain the nature of software development.
➤ Differentiate between the different types of programming approaches.
➤ Understand the similarities and differences between C, C++ and Java.
➤ Edit, compile, and run simple console based applications.

➤➤➤

WHAT IS PROGRAMMING?
Before tackling Java programming, it is important to understand what programming is and how it is used. People program to create software, which
can take many forms such as spreadsheet applications, Web applets, operating systems or corporate transaction databases.
Software consists of a series of instructions that tells hardware (or another
piece of software) to perform one or more actions. The programming language is the set of syntax used to create those instructions and the rules associated with their usage.
Like other natural languages, programming languages allow for some freedom and creativity in how a piece of software achieves its purpose. However,
unlike in spoken languages, programming must rigorously adhere to the
rules and constructs of the programming language to achieve precise results.
Machines cannot guess at meaning like humans can. Therefore, a good programmer must be very good at taking a problem or an idea in real world
human terms, and abstracting it into the constructs provided by the programming language.
Programming generally refers to the coding portion of software development.
Good software development, however, requires several other steps in addition to coding.

LESSON 1: Fundamental Aspects of Programming

3

To develop an application, the developer normally follows a series of steps
such as the following:

➤ Requirement Analysis
➤ Design
➤ Coding
➤ Testing
Requirement analysis is the process of determining the requirements of the
application. Typical application requirements might be, “to support a
spreadsheet-like interface” or “to calculate the precision of a result to 5 significant decimal places.”
The requirement analysis phase is perhaps the most important step in the
development process. Application requirements need to be clearly understood and articulated if the software is to be a success. Proper requirements
analysis will help avoid unnecessary corrective effort later in the process.
The design phase may occur at a high or low level. This step is responsible for
the overall structure of the application and how the parts of the application
interact.
Coding is the process of converting a design into a series of instructions
through a programming language. Source code is written and then put
through a code compiler, which translates the code in machine level instructions.
Before putting code into use, it needs to be tested to locate and remove
errors. Testing checks the application against the requirements, tests the
application functions with sample data, and verifies whether the user will
find the application easy-to-use, among other steps. When the application
behaves abnormally, corrections are made to the software and the testing
process resumes. When testing is complete the application is ready to use.

LESSON 1

A Brief Overview of Software
Development

4

JAVA PROGRAMMING: PART 1

Conceptual Differences Between
Software and Hardware
Software is a series of instructions to a machine. The computer takes the
instructions and executes them to produce the intended results. Software can
be readily changed. It can be modified to make changes in the behavior of
the application. These changes are changes in the application itself.
The hardware that makes up the computer does not readily change. At the
heart of the computer is a central processing unit that executes machine level
instructions. These instructions are very low level and are not easy for the
average programmer to use. The actual set of instructions for any language is
fixed. However, they are recombined in different sequences that result in different behavior for different programs.

Conceptual Differences Between the
Developer and the User
The end user is the individual that executes an application for the purpose of
performing a task. The developer is the individual that creates the application.
There are different types of developers. Some developers specialize in the
requirement analysis or design phase of a project. There are others who primarily code and test an application. For small to medium size projects, one
developer or a small group of developers may perform all of these tasks.
In addition, there are different types of applications that require different
types of development expertise. Database intensive applications will require
the skills of a developer proficient in the architecture and mechanics of databases, usually a specific database such as Oracle. Other developers will specialize in real-time applications that require carefully timed responses to
system inputs.

Programming Languages
A variety of different programming languages have evolved over time. Each
of these languages has its own unique syntax and semantics. Languages are
often categorized as either high level or low level, though this simple classification is not always adequate.

LESSON 1: Fundamental Aspects of Programming

5

Certain high-level languages are specialized. For example, there are languages designed to work directly with databases. Others are targeted towards
developing graphics applications.
Low-level languages have a one-to-one correspondence between a statement
in the language and a machine instruction. These languages are normally
called assembly languages and are unique to a specific computer. They provide a great deal of control over what can be done by a program but are very
difficult and tedious to use.
Some languages rely upon an interpreter instead of a compiler. The interpreter is an application that takes high level instructions for a given language
and simulates the execution of the instructions. The interpreted application
will produce the same results as if it were compiled. Interpreted code executes slower than a compiled version of the application but interpreters provide several advantages over compilers, including better portability and more
powerful development features. Java is an example of a language that is frequently interpreted rather than compiled. Any language may be compiled or
interpreted if a compiler or interpreter has been written for that language.

Syntax vs. Semantics
There are syntactic rules for each language that determine whether a given
command is in the proper form. Like rules that govern the form of an
English sentence, syntax rules of a programming language determine
whether the program is valid or invalid.
When a program violates the syntax rules of the language, the compiler will
generate an error message and will usually stop the compilation process. If
no errors are generated, the program is said to have compiled cleanly. The
program will run, but that does not necessarily mean that the program will
do what it is intended to do. The program must order instructions in such a

LESSON 1

Most developers work with high-level languages such as COBOL, C or
C++, Java, and FORTRAN. High-level languages do not use instructions
that the machine understands directly; instead, they utilize commands that
are more intelligible for humans. Naturally, high-level languages are easier to
use. Few high-level language instructions are required to perform the same
task in a low-level language. While programmers using a high-level language lose direct control of instructions to the machine, this is not a concern
for most developers.

6

JAVA PROGRAMMING: PART 1

way that they produce the correct result. In other words, the program must
be semantically correct.
The semantics of an instruction is the meaning of the instruction i.e., what
the instruction does. Understanding this is fundamental to learning programming languages. Fortunately, this is normally a straight-forward process. High-level programming languages are designed with logical and
intuitive semantic structures.

➤➤➤

TYPES OF PROGRAMMING
There are several types of programming. This section, by no means exhaustive, will discuss some of the key types:

➤ Console-based
➤ Windows-based
➤ Procedural
➤ Object-oriented
➤ Event-driven

Console Versus Windows-Based
Applications
Console based applications use an MS-DOS type user interface (often
called character driven) for input and output. The application is limited to
character-based displays of information. Frequently, the order of data entry
is dictated by the application. There are rarely windows of any nature present
in these.
Windows programming use extensive amount of graphics programming to
provide a more diverse range of input and output features. This graphics
programming may be hidden from the application developer but is supported by various operating system libraries.
Windows programming offers the developer freedom to use different
Graphical User Interface (GUI) controls to display or obtain information
from the user. Text Boxes can be used for textual information, lists can be

LESSON 1: Fundamental Aspects of Programming

7

Console-based programming is easier than windows programming and does
not use as many system resources. Windows programming is more difficult
to learn and is resource intensive. However, given that most people expect
windows based applications these days, creating windows is often an application requirement. The demand for windows has spurred significant advances
in computer processing power and windows development tools.

Procedural Programming
Procedural programming is used by almost all programming languages. Procedural programming focuses the step-by-step sequence of instructions that
are needed to perform a task. This approach has been needed because applications and computers are not capable of automatically deciding the appropriate sequence to use.
Non-procedural programming is characterized by the developer specifying
what needs to be done rather than how the task is to be performed. Procedural programming involves instructing the system as to how to achieve a
task. While non-procedural languages exist, these languages are normally
limited to a small application domain and are limited in the range of tasks
that can perform.
Procedural programming is tricky for large applications. Large procedural
programs can become unwieldy and difficult to manage. There is often little
opportunity for abstraction. By abstracting a problem, it can be simplified.
The interfaces between parts of an application can become difficult to manage also. Programmers tend to spend a lot of time learning how to program
to these interfaces.
Most commonly used languages are procedural, including C, C++, Java and
FORTRAN. These languages have evolved over time but they all have procedural aspects to them.

Object-Oriented Programming
The evolution of object oriented programming brought about a paradigm
shift in how application problem sets are modeled for development. In a traditional procedural language like C, things represented in a banking application like account number, customer, and balance dissolve into a series of

LESSON 1

displayed in List Boxes, and mutually exclusive options can be provided
through Radio Buttons.

8

JAVA PROGRAMMING: PART 1

functions and variables. In object-oriented programming, objects are defined
and maintained that represent these real things that are part of a problem
statement.
Just as things in real life have characteristics and actions associated with
them, objects possess properties, methods, and events. Each of these is directly
associated with the object. For example, a bank account object would have
the properties of account number and balance. These properties are tied
directly to an instance of Bank Account, and do not exist in the program,
other than as a part of Bank Account.
Methods are actions performed against the object. For example, the bank
account object may have a deposit method that is used to add money to an
account. Events are actions that take place under specific conditions. The
bank account might have a negative balance event that would occur whenever the balance became negative. The programmer would code this event to
take appropriate action when this event occurs.
Object-oriented languages support the definition of a class that represents
an object and the actual allocation of memory for the object. Classes are the
generalization of a specific object: Customer is a class, and Kelly Smith is an
object that is an instance of the class Customer. C++ and Java are examples
of object-oriented languages (note that they are also procedural languages).
The coding used in support of methods and events is procedural.
Object-oriented languages offer a number of benefits. Systems modeled in
objects are easier to maintain and manipulate, because properties and methods can be altered for a class without affecting the rest of the system.
Object-oriented programming also supports reuse of code: once developed,
a class can be utilized as often as necessary. For instance, a programmer
could use an existing Button class in an application without necessarily
understanding all of the code that supports the class. In addition, classes
may inherit properties from more general classes, so that the properties do
not have to be redefined for each sub class.
An object-based language, as opposed to an object-oriented one, is a language
that supports the creation of classes but does not support inheritance, a crucial programming feature which facilitates the creation of related types from
existing types. Visual Basic 5.0 and its earlier versions are an example of an
object-based language.

LESSON 1: Fundamental Aspects of Programming

9

Event driven programming is frequently used to support Windows programming. The operating system will monitor the system for events and
then send these events to the appropriate application. The application’s reaction is based on the nature of the event. Keyboard input and mouse movements are the most common events.
An event-driven application is structured around the process of receiving
and reacting to events. Unlike in procedural programming, where the programmer dictates the order of information received, event-driven applications generally allow the user to choose the order in which information is
entered.
For example, an application may have an entry field for Zip Code. In an
event driven application, the Zip Code field will be one in a series of address
fields in a dialog box. The user can use the mouse or tab key to jump around
to different fields and fill them in any order. The application’s structure must
account for the fact that it can not anticipate when Zip Code will be filled,
but rather must react when the event occurs.
Object-oriented programming is well suited for event driven applications.
Objects can have events assigned to them, which the application can monitor. Traditional procedural languages such as C, do not support event driven
programming very well. Java, in particular, is designed to address events
explicitly and has a well defined event model to create and handle events.

C/C++/Java Language Family
C was developed to meet general system programming needs. It was quickly
adapted for general use and found widespread acceptance. C is a high-level
procedural language that has many low-level features. These features help to
make it versatile and efficient. However, many of these features give it a reputation for being cryptic and hard to maintain.
C++ extends the C language to provide object-oriented features. The language is backward compatible with C, and code from the two languages can
be used with each other with little difficulty. C++ has found quick acceptance and is supported by a number of pre-built specialized classes.
Java can be considered the third generation of the C/C++ family. It is not
backward compatible with C/C++ but was designed to be very similar to
these languages. The creators of Java intentionally left out some of the fea-

LESSON 1

Event-Driven Programming

10

JAVA PROGRAMMING: PART 1

tures of C/C++ that have been problematic for programmers. Java is strongly
object-oriented. In fact, one cannot create Java code that is not object-oriented. Java’s portability is a key advantage and is the reason why Java is often
used for Web development.

➤➤➤

THE COMMON LANGUAGE CORE
There are several programming features common to most programming languages. These include the definition of identifiers, expressions, and condition
control statements. These common core features are discussed and illustrated
below with sample code where appropriate.

Comments
Comments are sections of a program that are ignored by the compiler and
are used to document the program. Documentation is important in that it
provides information about the program that is useful in the maintenance of
the program.
Software applications generally require periodic revision—the application
requirements change, errors are corrected or new features are added. Good
documentation aids the programmer in identifying the structure and purpose of each section of code. Often, the person modifying the code is not the
same person that wrote the code, making the use of good comments critical.
The only comment that is common to C, C++ and Java is the multi-line
comment. The comment begins with a /* and ends with a */. Everything
between these two sets of symbols is treated as a comment and is ignored by
the compiler.
/* This is a comment
spread across several lines */
/* This comment occurs on a single line */
i = i + 1; /* This comment begins on the same line as
a statement */

LESSON 1: Fundamental Aspects of Programming

11

i = i + 1;

// Alternate comment notation

Identifiers
Identifiers are used to temporarily hold information. For example, to compute the pay for an individual, the numbers of hours worked is multiplied by
the pay rate. Identifiers (the name of the variable listed on the left) are
needed for these values.
hours = 40;
payrate = 12.50;
pay = hours * payrate;

Identifiers have certain rules for their creation. Generally, the identifier must
begin with a letter and is followed by letters, digits, and perhaps another
character, such as the underscore character.
The assignment operator, which is the equal sign (=), is used to modify the
value assigned to an identifier. Simply using the identifier as part of some
operation will retrieve its current value. The value stored in an identifier can
change.

Data Types
There are different types of identifiers based on different needs. If simple
counting numbers are needed then there is the integer data type. If a number
with decimal points is required then the float data type is used. The common
data types are listed in Table A.
TABLE A. Data Types
Data Type

Value

Examples

int

Positive and negative integers

127
-6

float

Single precision numbers

6.42

LESSON 1

An alternative style available in C++ and Java uses two forward slashes (//) to
indicate that everything from that point until the end of the line is a comment.

12

JAVA PROGRAMMING: PART 1

TABLE A. Data Types (continued)
Data Type

Value

Examples

double

Double precision numbers
(numbers with a very
large value or # of digits)

137.5426246321
5.42 x 1045

char

Single characters

h

char* or String

String data (any series of
characters)

widget
42XXTALL

Note that very large numbers or very precise numbers use a different data
type than normal real numbers. The boundary between single and double
precision numbers is defined differently for each language.
String data is handled differently between C/C++ and Java. C and C++ use a
pointer to the address of a string of characters that is terminated by a zero.
Java uses a built-in data type String to hold strings.
Before an identifier can be used, it must be declared. Specifying the type of
data followed by the identifier’s name does this:
int
float
int
double

i;
pay;
hours;
radius;

Most languages provide the developer with the ability to define more complex data structures based on primitive data types. C and C++ do this using
the struct statement.
struct Employee {
char*name;
int age;
double payrate;
};

An actual identifier is declared as other primitive types are declared.
struct Employee boss;

LESSON 1: Fundamental Aspects of Programming

13

Expressions are needed to perform computations. An expression consists of
an operator and one or more operands. Operators specify the action to be
performed, such as addition or multiplication. Operands are the data acted
upon. Statements are separated by semicolons and consist of one or more
expressions. In the following example, the assignment operator, equal sign,
and the addition operator are used to add two numbers together and assign
the sum to a third identifier.
a = b + c;

There is a predefined order in which expressions are evaluated. This is
known as the order of precedence. For example, addition always occurs before
assignment (+ happens before =). There also exists rules of associativity that
specify the order in which two expressions of equal precedence are to be
evaluated. These rules can be overridden through the use of parentheses. For
addition, evaluation is done left to right. The following two statements are
equivalent:
a = b + c + d;

a = b + (c + d);

Input and Output
Getting information into a program and then writing it out are important
aspects of programming. Data can be read from a number of sources: keyboard, mouse, files, databases, etc. Data can be outputted to the monitor, to
various files, and to a database, among other places.
The syntax of Input/Output (I/O) is mostly language specific. C and C++
rely upon include files that contain specialized code to perform I/O. Java
uses a series of classes to do similar I/O actions. Input statements are not
addressed here, however, output examples are provided.

LESSON 1

Expressions

14

JAVA PROGRAMMING: PART 1

In C, the printf statement is used. It has two major parts: a format specification that is enclosed with double quotes and a list of data values to be
printed. The following shows printing out pay information:
printf(“Hours worked: %f Payrate: %f
hours, payrate, pay);

Pay: %f\n”,

The %f fields within the format string are “place holders” for the output values to be printed. The text printed will be that which is inside of the double
quotes, with the %f field replaced by the values stored in the variables in the
parameter list. The three %f fields are replaced with the values stored in
hours, payrate and pay. The \n is used to cause a carriage return and a new
line to be printed. Output goes to standard output, which is normally the
monitor. For floating values, a %f file is used. For other data types, different
place holders are used.
In C++, insertion operators (<<) are used to display the same information.
cout << “Hours worked: “ << hours << “ Payrate: “
<

The creation of a program is an abstract process. It requires an understanding of the nature of the problem to be solved, an understanding of how the
problem can be solved, knowledge of the language used to implement a solution, and the creativity to put it all together.
A general approach to tackling a programming problem is:

➤ Determine what needs to be done.
➤ Determine how to do it (i.e., write the code).
➤ Determine where to place the code.
In the pay computation example, only the hours worked and payrate are utilized. The problem becomes more complex if other factors have to be considered, such as overtime and insurance deductions.
Creating a successful program for this example requires an understanding of
both the syntax and semantics of the solution. Semantically, the proper process for computing pay must be known and understood. Syntactically, these
procedures must be translated into the proper coding functions, and the I/O
display capabilities of the language must be utilized properly.
Each of the code sequences developed must be placed in the right location in
the program. Functions are used to break a program up into more manageable units. There is frequently more than one way to partition a program.
The right way depends on a number of factors: size of the program, efficiency, portability, etc.

Control Structures
For programs containing more than just the simplest logic, control statements are needed to control the flow of execution of the program. For example, tests may be needed to differentiate between hourly and salaried
employees. Loops may be needed to process more than one employee at a
time.

LESSON 1: Fundamental Aspects of Programming

17

{
/* A block statement */
}

WARNING
It is possible to have
one if statement
nested within
another if statement. When this happens, you should be
careful about knowing which if
matches up with
each else. The else
matches with the
nearest if. When
unsure, use statement blocks with {}
to specify how the
else should be
matched.

The if statement tests an expression. Based on a true or false evaluation of
the expression, branches to one of two places.
if (expression)
statement; /* Branch here if true */
else
statement; /* Branch here if false */

The following illustrates testing for overtime:
if (hours > 40)
pay = 40 * payrate + (hours – 40) * 1.5 *
payrate;
else
pay = hours * payrate;

The switch statement is like a multiple-branch if statement. The expression tested is an integer and branches are made based on the integer’s value.
The case keyword is followed by a constant. If the value of the integer
expression matches the constant, then the branch is made to that location.
The break statement causes control to flow to the end of the switch
statement; otherwise, it will flow through to the next case statement. The

LESSON 1

The block statement is a commonly used control statement. It logically
groups related statements together. The block statement is necessary when
the control statement’s syntax expects a single statement but multiple statements are what are required. The block statement is a single statement
that meets the syntax requirements and also allows multiple statements to be
included at the same time. A block statement is nothing more than one or
more statements included between an open curly brace ({) and a close curly
brace (}).

18

JAVA PROGRAMMING: PART 1

default clause is optional and will catch anything that is missed by the
previous case clauses .
switch (integer) {
case 1:
statement;
break;
case 2:
statement;
break;
…
default:
statement;
}

The following branches based on an age:

WARNING
It is a common error
to forget the break
statement. This will
result in the execution continuing on to
the next statement
instead of falling out
of the switch statement.

int age;
…
switch (age) {
case 1:
printf(“The age is 1\n”);
break;
case 2:
case 3:
printf(“The age is either 1 or 2\n”);
break;
…
default:
printf(“The age is not 1, 2 or 3\n”);
}

Looping statements cause a sequence of statements to be executed multiple
times. This construct is useful for processing multiple lines of input, initializing identifiers, summing values, etc. The two most common looping statements are the for loop and the while loop.
The for loop uses an identifier as a counter and a test condition. It has
three parts: initialization, test and termination. Each of these parts is separated by a semicolon. In the following example, the numbers from 1 to 10

LESSON 1: Fundamental Aspects of Programming

19

for (i=1; i<=10; i++) {
printf(“Number: %d Square: %d\n”, i, i * i);
}

The %d field is used with integers.
The while statement has a test expression and a body. The expression is
tested and as long as it evaluates to true, the body is executed. The following
is the equivalent of the previous for loop.
i = 1;
while (i <= 10) {
printf(“Number: %d
i++;
}

Square: %d\n”, i, i * i);

Scoping
Scoping refers to the bounds of use of a particular identifier. Identifiers may
only be used within the function in which they are declared. Consider the
example again, in which the identifiers named pay and rate have been
declared in both the main function and the ComputePay function.
float ComputePay(float hours, float rate) {
float pay;
pay = hours * rate;
return pay;
}
main () {
float hours;
float payrate;
hours = 40;
payrate = 12.50;
printf(“The pay is: %f\n”, ComputePay(hours,
payrate));
}

LESSON 1

are printed along with their square. The i++ is a shorthand notation that is
allowed to represent the statement, i = i +1;.

20

JAVA PROGRAMMING: PART 1

While the identifiers are given identical names in main and ComputePay,
they should be distinct sets of identifiers. When an identifier is declared, it is
allocated memory in main memory.
In the main function, memory is allocated for the identifiers hours and
payrate. In the ComputePay function, memory is allocated to the identifiers hours, rate and pay. All five identifiers have separate areas of
memory allocated to them. The values of the hours and payrate identifiers are passed to the ComputePay hours and rate identifiers respectively.
The scope of the hours and payrate identifiers is within the main function. That is the only place that these identifiers can be used, since they were
declared within the main function.
The scope of the ComputePay hours, rate, and pay identifiers is
within the ComputePay function, since they were declared within that
function. Attempting to use the pay identifier within the main function
would generate a compile-time error.

LESSON 1: Fundamental Aspects of Programming

LESSON SUMMARY
In this lesson you have learned that

➤ Programming refers to the coding portion of software development.
➤ Software development involves a series of steps—requirement analysis,
design, coding, and testing.
➤ C, C++, Java, etc. are considered high-level languages as these require
fewer instructions to perform a given task than low-level languages.
➤ For a program to be successful, it has to be both syntactically and
semantically correct.
➤ Console based programming is character driven and is easier to use
than Windows based programming which is resource intensive.
➤ Procedural programming specifies step-by-step sequential instruction.
➤ Object-oriented programming supports objects which represent real
world concepts that are part of a problem statement.
➤ Windows programming is event driven programming—the common
events being keyboard input and mouse movement.
➤ Comments are those sections of a program that the compiler ignores,
but useful as signposts for programmers.
➤ int, float, double, char, and String are some of the data
types that programmers use.
➤ Expressions, used to perform computations, consist of an operator and
one or more operands.
➤ A function is a block of code that has an optional return value, a name,
and a set of arguments.
➤ Control statements are needed to control the flow of execution of a program. The block statement is a common control statement.
➤ Looping causes a sequence of statements to be executed multiple times.
➤ Scope refers to the bounds of use for a particular identifier.

LESSON 1

➤➤➤

21

22

JAVA PROGRAMMING: PART 1

EXERCISE
1. Type in the pay computation example as shown below and verify that it
works properly.
public class Exercise1 {
static float ComputePay(float hours, float rate) {
float pay;
pay = hours * rate;
return pay;
}
public static void main (String argv[]) {
float hours;
float payrate;
hours = 40f;
payrate = 12.50f;
System.out.println("The pay is: " +
ComputePay(hours, payrate));
}
}

2. This exercise walks through the construction of a program that reads in
specifications for a geometric figure, tests for valid input, and then computes and displays the area of that figure. You will need to add additional
code to complete the exercise. Type in the first part as shown below.
This section reads in a double number and is provided because Java does
not read in numbers in as easy a manner as other languages.

LESSON 1: Fundamental Aspects of Programming

23

public class Exercise2 {
static double getDouble() throws IOException{
double d = 0.0;
byte buffer[] = new byte[8];
String response;
System.in.read(buffer);
response = new String(buffer,0,buffer.length-2);
try {
d = Double.valueOf(response).doubleValue();
return d;
}
catch (NumberFormatException e) {return d;};
}

The main method follows:
public static void main (String argv[]) throws
IOException {
/* Declare identifiers */
byte buffer[] = new byte[8];
/* Read in geometric shape type */
System.out.print("Enter Geometric Type (r, t or c):
");
System.in.read(buffer);
/* Determine geometric type, get size information
and compute ares */
/* Display area and perimeter */
}
}

The identifie, buffer[0], is used to hold the type of geometric figure
selected by the user. The input statement, System.in.read(buffer),

LESSON 1

import java.io.*;

24

JAVA PROGRAMMING: PART 1

is used to read in data from standard input. Declaration will need to be
added after the comments as explained below.
The three types of shapes to be processed are: rectangle, triangle and circle.
Add declarations for the identifiers in Table B:
TABLE B. Geometric Shape Identifiers
Identifier

Data Type

length

float

width

float

radius

float

area

float

Next, add a switch statement that selects among the three options:

➤ r—Rectangle
➤ t—Triangle
➤ c—Circle
The basic structure of the switch statement will be similar to the following:
switch (buffer[0]) {
case (byte)'r': /* Rectangle selected */
break;
case (byte)'t':
/* Triangle selected */
break;
case (byte)'c':
/* Circle selected */
}

Within each case statement, add code to read in the appropriate values
(height and width for a rectangle) and then compute the area. Use the following format to read in a float data type:
System.out.print(“Enter Height:”);
height = getDouble();

LESSON 1: Fundamental Aspects of Programming

25

if (height <= 0)
height = 1.0;
else
;

In the last section of the program, display the area of the geometric figure.

LESSON 1

Next, add statements to verify that the values entered by the user are positive, non-zero numbers. If they do not meet this criteria, use the value 1.0
instead. The else part of the statement can be a single semicolon.

▼
▼
▼

LESSON 2
The Java Environment
OVERVIEW
Java as an object-oriented language was designed from the outset to be
platform independent, robust, and secure. Many of the concepts and
syntax of Java are borrowed from C++, another object-oriented
language. Java can be used to produce two types of programs. One type is
an application, which is a standalone program that can be run by the
Java interpreter. The other type is an applet, which is a mini-program
that is typically built into World Wide Web pages.

LESSON TOPICS
● Introduction
● Java Characteristics
● Application/Applet Development
● Tools and Packages

28

JAVA PROGRAMMING: PART 1

➤➤➤

OBJECTIVES
By the end of this lesson, you should be able to:

➤ Describe the characteristics of Java environment.
➤ Edit, compile, and run Java programs and applets.
➤ Contrast Java with other programming languages.

➤➤➤

INTRODUCTION
Java (originally called Oak, until it was discovered that another company
used Oak as a trademark) was developed at Sun MicroSystems in a forwardlooking project to develop a new programming language. The primary
design goal of Java was to provide code for programs that would run on
many different hardware platforms. The second design goal was to produce
robust programs—programs that would have as few bugs as possible. The
third design goal was for the language to be easy to learn and use. Since the
world of computers and application development was already populated with
programmers who knew C++, the syntactical model of C++ was chosen
along with some characteristics of Smalltalk. The effectiveness of Java as a
programming language can be illustrated by considering how Java reduces
bugs:

➤ The most common source of difficult-to-track bugs in traditional programming languages is improper handling of dynamically allocated
memory. These memory leaks are caused by programmers allocating
memory, and then losing track of its location or simply not releasing it.
Java handles all memory management issues on its own, rather than
leaving them to the programmer. Java allocates memory when an
object is instantiated and releases it automatically when the object goes
out of existence, through a process called garbage collection.
➤ Another frequent source of problems is out-of-range array indexing. C
and C++ do not check for these errors, but Java does.
➤ Java avoids the syntactical headaches that result from multiple inheritance, which is an object oriented feature (of controversial value) in
C++. Java uses interface files to provide most of the benefits of multiple inheritance (and polymorphism) while avoiding their problems.

LESSON 2: The Java Environment

29

Though it was originally intended as a language for programming embedded
systems, Java has become very popular because of its natural applicability to
programming network software for the World Wide Web (WWW). Java is
best known as a language for programming applets. An applet is a “miniapplication” that runs within the context of a larger application, such as a
network browser.
For a program to be usable across such a diverse network as the World Wide
Web, it must be portable; i.e., it must be able to run on many different systems. Java is designed to be portable.
Any software downloaded across a network must be considered untrustworthy software, suspect for viruses and other malicious programming. To overcome this liability, Java language and Java API (Application Program
Interface) have built-in security features that provide safety from such
attacks.
The structure of a Java program is modular. Instead of being bound into a
single file, a Java application exists as a set of cooperating files, each file representing a discrete module of the program. This has a great advantage.
Rather than downloading an entire program before running it, the user may
download only those Java modules that are needed. To upgrade a Java program, the user may replace only those modules that have changed. This
dynamic nature of the language also speeds application development.
Finally, the Java API includes a wide set of facilities for network communications. The Java programmer can readily create network connections and
either work at the data stream level or at the higher network protocol level.
The programmer can create network applets, agents, and servers in Java. All
these features make Java an ideal platform for network software development.
It is important to note that though Java is ideally suited for the creation of
network software, it is not limited to network software applications. The
Java API also includes facilities for graphical user interfaces (GUI’s), file
access, parsing, and is rapidly expanding to include database access, remote
procedure calls, component software, and other features. Java is a platform
for general purpose application development.

LESSON 2

Uses for Java

30

JAVA PROGRAMMING: PART 1

The World Wide Web (WWW)
Java is an outstanding language for developing applications that will run on
the WWW. The WWW, which uses a client server framework, is a virtual
network built on top of the Internet.

➤ The client is called a browser, which requests data from servers. Currently, the most popular browsers are Netscape Navigator and
Microsoft Internet Explorer.
➤ The server is called a Web server. A Web server responds to requests by
sending Hypertext Markup Language (HTML) documents back to
the browser which are then displayed for the user.
Web servers can send many different file types (text, graphics, audio, etc.) to
requesting browsers as part of an HTML document. Web servers typically
run on systems using Unix or Windows NT. Browsers can request information from any Web server.
Web servers and browsers use the HyperText Transfer Protocol (HTTP) to
communicate with one another. This protocol enables a browser to request
data or other resources from a Web server. HTTP also enables a server to
describe the file types that it can send to a browser. Although an understanding of HTTP may be of interest to a programmer, it is not necessary
prerequisite for writing Java applications.

HTML
Web servers send HTML documents to browsers. In other words, the data
that servers provide to browsers is always coded in the HTML language.
Browsers know how to display HTML documents that describe words,
graphics and audio.
HTML uses a different model for describing the layout of information than
most popular word processors do. Word processors like Microsoft Word or
FrameMaker give the writer complete control over the way text is laid out.
HTML gives the writer only partial control, turning the remainder of control over to the browser. For example, when putting a second level header
into a FrameMaker template, the writer can control the font to be used, the
exact position in which the header will be written, and dozens of other

LESSON 2: The Java Environment

31

The Header Itself

and leaves the exact formatting details (font, position, etc.) to the browser. The current “official” HTML standard is Version 3.2. It is maintained by the WWW Consortium. HTML is a rapidly evolving language. Unfortunately, not all browsers support the same HTML tags. Netscape, for example, continues to supplement standard HTML with many extensions of its own. HTML tags describe not only text but graphic and audio information as well. For instance, the following HTML directive tells the browser to display a graphics image file named logo.gif: HTML tags also describe the hierarchical organization of the document for example: ➤ - HTML document tag ➤ - Head section tag ➤ - Body section tag Finally, HTML also contains directives that tell the browser to run a particular Java applet. An overview of HTML tags can be found in Appendix A. Competing Technologies Just a few years ago, C++ was hailed as the computer language that would revolutionize computer programming and lead to bug-free programs. Unfortunately, C++ was rather hard to learn and ended up creating many bugfilled programs. Nevertheless, although C++ was hardly the first object-oriented language, it did expose many programmers to object-oriented programming. Many programmers now feel that while the future belongs to object-oriented programming, C++ is not the best vehicle for it. Java’s designers took the best features of C++ while rejecting its bad features. LESSON 2 details. By contrast, to put a second level header into an HTML document, the writer merely writes: 32 JAVA PROGRAMMING: PART 1 Languages such as Visual Basic do a terrific job designing GUIs. Yet, Visual Basic lacks many important Java features that are needed for WWW applications. Microsoft has introduced ActiveX technology which can be used with VBScript (a subset of Visual Basic) to provide many of the same user interaction features as Java applets. VBScripts are embedded in HTML documents between tags. In spite of its name, JavaScript has nothing to do with Java. JavaScript is an object-based language which was developed at Netscape (a browser vendor). It is used to give dynamic capabilities to HTML documents, including client-side user interaction. JavaScript programs are not compiled, but are interpreted as part of the HTML document. JavaScript source code is embedded in an HTML document between the Run Script Designed to support new scripts in the future LANGUAGE=”JavaScript” Specifies which language is being used Tells browser that the language code that follows is Java Script function func_name(form) {...} Script The actual script is embedded at this location in the HTML document SCRIPT ATTRIBUTES APPENDIX A ➤➤➤JAVA APPLETS 171 ▼ ▼ ▼ APPENDIX B Java Sample OVERVIEW This appendix contains a sample Java applet. It comes from the demos supplied with the Java Development Kit. The applet can be viewed using any java-capable browser or using the Applet Viewer, which is part of the JDK release. To run this applet with the Applet Viewer, just specify the URL with the appletviewer command. See the course postings for a downloadable version of the applet. 174 JAVA PROGRAMMING: PART 1 ➤➤➤ USAGE AND COPYRIGHT NOTIFICATION Copyright (c) 1994-1996 Sun Microsystems, Inc. All Rights Reserved. Sun grants you (“Licensee”) a non-exclusive, royalty free, license to use, modify and redistribute this software in source and binary code form, provided that i) this copyright notice and license appear on all copies of the software; and ii) Licensee does not utilize the software in a manner which is disparaging to Sun. This software is provided “AS IS,” without a warranty of any kind. ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. This software is not designed or intended for use in on-line control of aircraft, air traffic, aircraft navigation or aircraft communications; or in the design, construction, operation or maintenance of any nuclear facility. Licensee represents and warrants that it will not use or redistribute the Software for such purposes. APPENDIX B: Java Sample /* * @(#)XYZApp.java1.3 96/12/06 * A set of classes to parse, represent and display Chemical compounds in * .xyz format (see http://chem.leeds.ac.uk/Project/MIME.html) */ import java.applet.Applet; import java.awt.Image; import java.awt.Event; import java.awt.Graphics; import java.awt.Dimension; import java.io.StreamTokenizer; import java.io.InputStream; import java.io.BufferedInputStream; import java.io.IOException; import java.net.URL; import java.util.Hashtable; import java.awt.image.IndexColorModel; import java.awt.image.ColorModel; import java.awt.image.MemoryImageSource; /** The representation of a Chemical .xyz model */ class XYZChemModel { float vert[]; Atom atoms[]; int tvert[]; int ZsortMap[]; int nvert, maxvert; static Hashtable atomTable = new Hashtable(); static Atom defaultAtom; static { atomTable.put(“c”, new Atom(0, 0, 0)); atomTable.put(“h”, new Atom(210, 210, 210)); atomTable.put(“n”, new Atom(0, 0, 255)); atomTable.put(“o”, new Atom(255, 0, 0)); atomTable.put(“p”, new Atom(255, 0, 255)); atomTable.put(“s”, new Atom(255, 255, 0)); atomTable.put(“hn”, new Atom(150, 255, 150)); /* !!*/ defaultAtom = new Atom(255, 100, 200); } boolean transformed; Matrix3D mat; float xmin, xmax, ymin, ymax, zmin, zmax; XYZChemModel () { mat = new Matrix3D(); mat.xrot(20); mat.yrot(30); } APPENDIX B ➤➤➤THE XYZAPP.JAVA SOURCE 175 176 JAVA PROGRAMMING: PART 1 /** Create a Cehmical model by parsing an input stream */ XYZChemModel (InputStream is) throws Exception { this(); StreamTokenizer st; st = new StreamTokenizer(new BufferedInputStream(is, 4000)); st.eolIsSignificant(true); st.commentChar('#'); int slot = 0; try { scan: while (true) { switch ( st.nextToken() ) { case StreamTokenizer.TT_EOF: break scan; default: break; case StreamTokenizer.TT_WORD: String name = st.sval; double x = 0, y = 0, z = 0; if (st.nextToken() == StreamTokenizer.TT_NUMBER) { x = st.nval; if (st.nextToken() == StreamTokenizer.TT_NUMBER) { y = st.nval; if (st.nextToken() == StreamTokenizer.TT_NUMBER) z = st.nval; } } addVert(name, (float) x, (float) y, (float) z); while( st.ttype != StreamTokenizer.TT_EOL && st.ttype != StreamTokenizer.TT_EOF ) st.nextToken(); } // end Switch } // end while is.close(); } // end Try catch( IOException e) {} if (st.ttype != StreamTokenizer.TT_EOF) throw new Exception(st.toString()); } // end XYZChemModel() /** Add a vertex to this model */ int addVert(String name, float x, float y, float z) { int i = nvert; if (i >= maxvert) APPENDIX B: Java Sample 177 APPENDIX B if (vert == null) { maxvert = 100; vert = new float[maxvert * 3]; atoms = new Atom[maxvert]; } else { maxvert *= 2; float nv[] = new float[maxvert * 3]; System.arraycopy(vert, 0, nv, 0, vert.length); vert = nv; Atom na[] = new Atom[maxvert]; System.arraycopy(atoms, 0, na, 0, atoms.length); atoms = na; } Atom a = (Atom) atomTable.get(name.toLowerCase()); if (a == null) a = defaultAtom; atoms[i] = a; i *= 3; vert[i] = x; vert[i + 1] = y; vert[i + 2] = z; return nvert++; } /** Transform all the points in this model */ void transform() { if (transformed || nvert <= 0) return; if (tvert == null || tvert.length < nvert * 3) tvert = new int[nvert * 3]; mat.transform(vert, tvert, nvert); transformed = true; } /** Paint this model to a graphics context. It uses the matrix associated with this model to map from model space to screen space. The next version of the browser should have double buffering, which will make this *much* nicer */ void paint(Graphics g) { if (vert == null || nvert <= 0) return; transform(); int v[] = tvert; int zs[] = ZsortMap; if (zs == null) { ZsortMap = zs = new int[nvert]; for (int i = nvert; --i >= 0;) zs[i] = i * 3; } /* * I use a bubble sort since from one iteration to the next, the sort * order is pretty stable, so I just use what I had last time as a * “guess” of the sorted order. With luck, this reduces O(N log N) 178 JAVA PROGRAMMING: PART 1 * to O(N) */ for (int i = nvert - 1; --i >= 0;) { boolean flipped = false; for (int j = 0; j <= i; j++) { int a = zs[j]; int b = zs[j + 1]; if (v[a + 2] > v[b + 2]) { zs[j + 1] = a; zs[j] = b; flipped = true; } } if (!flipped) break; } int lg = 0; int lim = nvert; Atom ls[] = atoms; if (lim <= 0 || nvert <= 0) return; for (int i = 0; i < lim; i++) { int j = zs[i]; int grey = v[j + 2]; if (grey < 0) grey = 0; if (grey > 15) grey = 15; // g.drawString(names[i], v[j], v[j+1]); atoms[j/3].paint(g, v[j], v[j + 1], grey); // g.drawImage(iBall, v[j] - (iBall.width >> 1), v[j + 1] // (iBall.height >> 1)); } } /** Find the bounding box of this model */ void findBB() { if (nvert <= 0) return; float v[] = vert; float xmin = v[0], xmax = xmin; float ymin = v[1], ymax = ymin; float zmin = v[2], zmax = zmin; for (int i = nvert * 3; (i -= 3) > 0;) { float x = v[i]; if (x < xmin) xmin = x; if (x > xmax) xmax = x; float y = v[i + 1]; if (y < ymin) APPENDIX B: Java Sample } this.xmax this.xmin this.ymax this.ymin this.zmax this.zmin } = = = = = = xmax; xmin; ymax; ymin; zmax; zmin; } /** An applet to put a Cehmical model into a page */ public class XYZApp extends Applet implements Runnable { XYZChemModel md; boolean painted = true; float xfac; int prevx, prevy; float xtheta, ytheta; float scalefudge = 1; Matrix3D amat = new Matrix3D(), tmat = new Matrix3D(); String mdname = null; String message = null; Image backBuffer; Graphics backGC; Dimension backSize; private synchronized void newBackBuffer() { backBuffer = createImage(size().width, size().height); backGC = backBuffer.getGraphics(); backSize = size(); } public void init() { mdname = getParameter(“model”); try { scalefudge = Float.valueOf(getParameter(“scale”)).floatValue(); } catch(Exception e) { }; amat.yrot(20); amat.xrot(20); if (mdname == null) mdname = “model.obj”; resize(size().width <= 20 ? 400 : size().width, size().height <= 20 ? 400 : size().height); newBackBuffer(); } APPENDIX B ymin = y; if (y > ymax) ymax = y; float z = v[i + 2]; if (z < zmin) zmin = z; if (z > zmax) zmax = z; 179 180 JAVA PROGRAMMING: PART 1 public void run() { InputStream is = null; try { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); is = new URL(getDocumentBase(), mdname).openStream(); XYZChemModel m = new XYZChemModel (is); Atom.setApplet(this); md = m; m.findBB(); float xw = m.xmax - m.xmin; float yw = m.ymax - m.ymin; float zw = m.zmax - m.zmin; if (yw > xw) xw = yw; if (zw > xw) xw = zw; float f1 = size().width / xw; float f2 = size().height / xw; xfac = 0.7f * (f1 < f2 ? f1 : f2) * scalefudge; } catch(Exception e) { e.printStackTrace(); md = null; message = e.toString(); } try { if (is != null) is.close(); } catch(Exception e) { } repaint(); } public void start() { if (md == null && message == null) new Thread(this).start(); } public void stop() { } public boolean mouseDown(Event e, int x, int y) { prevx = x; prevy = y; return true; } public boolean mouseDrag(Event e, int x, int y) { tmat.unit(); float xtheta = (prevy - y) * (360.0f / size().width); float ytheta = (x - prevx) * (360.0f / size().height); tmat.xrot(xtheta); tmat.yrot(ytheta); amat.mult(tmat); if (painted) { APPENDIX B: Java Sample } prevx = x; prevy = y; return true; } public void update(Graphics g) { if (backBuffer == null) g.clearRect(0, 0, size().width, size().height); paint(g); } public void paint(Graphics g) { if (md != null) { md.mat.unit(); md.mat.translate(-(md.xmin + md.xmax) / 2, -(md.ymin + md.ymax) / 2, -(md.zmin + md.zmax) / 2); md.mat.mult(amat); // md.mat.scale(xfac, -xfac, 8 * xfac / size().width); md.mat.scale(xfac, -xfac, 16 * xfac / size().width); md.mat.translate(size().width / 2, size().height / 2, 8); md.transformed = false; if (backBuffer != null) { if (!backSize.equals(size())) newBackBuffer(); backGC.setColor(getBackground()); backGC.fillRect(0,0,size().width,size().height); md.paint(backGC); g.drawImage(backBuffer, 0, 0, this); } else md.paint(g); setPainted(); } else if (message != null) { g.drawString(“Error in model:”, 3, 20); g.drawString(message, 10, 40); } } private synchronized void setPainted() { painted = true; notifyAll(); } private synchronized void waitPainted() { while (!painted) { try { wait(); APPENDIX B painted = false; repaint(); 181 182 JAVA PROGRAMMING: PART 1 } catch (InterruptedException e) {} } painted = false; } } // end class XYZApp class Atom { private static Applet applet; private static byte[] data; private final static int R = 40; private final static int hx = 15; private final static int hy = 15; private final static int bgGrey = 192; private final static int nBalls = 16; private static int maxr; private int Rl; private int Gl; private int Bl; private Image balls[]; static { data = new byte[R * 2 * R * 2]; int mr = 0; for (int Y = 2 * R; --Y >= 0;) { int x0 = (int) (Math.sqrt(R * R - (Y - R) * (Y - R)) + 0.5); int p = Y * (R * 2) + R - x0; for (int X = -x0; X < x0; X++) { int x = X + hx; int y = Y - R + hy; int r = (int) (Math.sqrt(x * x + y * y) + 0.5); if (r > mr) mr = r; data[p++] = r <= 0 ? 1 : (byte) r; } } maxr = mr; } static void setApplet(Applet app) { applet = app; } Atom(int Rl, int Gl, int Bl) { this.Rl = Rl; this.Gl = Gl; this.Bl = Bl; } private final int blend(int fg, int bg, float fgfactor) { return (int) (bg + (fg - bg) * fgfactor); } private void Setup() { balls = new Image[nBalls]; byte red[] = new byte[256]; APPENDIX B: Java Sample } APPENDIX B red[0] = (byte) bgGrey; byte green[] = new byte[256]; green[0] = (byte) bgGrey; byte blue[] = new byte[256]; blue[0] = (byte) bgGrey; for (int r = 0; r < nBalls; r++) { float b = (float) (r+1) / nBalls; for (int i = maxr; i >= 1; --i) { float d = (float) i / maxr; red[i] = (byte) blend(blend(Rl, 255, d), bgGrey, b); green[i] = (byte) blend(blend(Gl, 255, d), bgGrey, b); blue[i] = (byte) blend(blend(Bl, 255, d), bgGrey, b); } IndexColorModel model = new IndexColorModel(8, maxr + 1, red, green, blue, 0); balls[r] = applet.createImage( new MemoryImageSource(R*2, R*2, model, data, 0, R*2)); } } void paint(Graphics gc, int x, int y, int r) { Image ba[] = balls; if (ba == null) { Setup(); ba = balls; } Image i = ba[r]; int size = 10 + r; gc.drawImage(i, x - (size >> 1), y - (size >> 1), size, size, applet); } 183 ▼ ▼ ▼ APPENDIX C Java Class Hierarchy OVERVIEW The Java Class Hierarchy is shown in the next series of pages. Generally, pages are divided by packages, although some packages are too large to fit on a single page. The boxes that are not part of the class library with the centered text serve as keys to the packages represented on that particular page. 186 JAVA PROGRAMMING: PART 1 ➤➤➤ JAVA CLASS HIERARCHY FIGURE 9 KEY Class Interface Extends Implements * - Duplicated APPENDIX C: Java Class Hierarchy java.lang Boolean Character Class ClassLoader Compiler Math Number Double Float Integer Long Process Runtime SecurityManager String StringBuffer System Thread ThreadGroup Throwable Runnable APPENDIX C Object 187 188 JAVA PROGRAMMING: PART 1 Object (java.lang) java.io java.lang File FileDescriptor InputStream ByteArraryInputStream FileInputStream FilterInputStream BufferedInputStream DataInputStream DataInput* LineNumberInputStream PushbackInputStream PipedInputStream Exception (java.lang) SequenceInputStream IOException StringBufferInputStream EOFException OutputStream ByteArrayOutputStream FileNotFoundException FileOutputStream InterruptedIOException FilterOutputStream BufferedOutputStream DataOutputStream DataOutput* PrintStream PipedOutputStream DataInput* RandomAccessFile DataInput* StreamTokenizer FileNameFilter APPENDIX C: Java Class Hierarchy java.lang StreamTokenizer java.io ContentHandler Exception (java.lang) DatagramPacket DatagramSocket InetAddress ServerSocket Socket SocketImpl URL IOException (java.io) MalformedURLException ProtocolException SocketException UnknownHostException UnknowenServiceException URLConnection SocketImpFactory URLEncoder URLStreamHandlerFactory URLStreamHandler ContentHandlerFactory APPENDIX C java.net 189 190 JAVA PROGRAMMING: PART 1 java.lang Throwable java.awt Error AWTError LinkageError ClassCircularityError ClassFormatError IncompatableClassChangeError AbstractMethodError IllegalAccessError InstantiationError NoSuchFieldError NoSuchMethodError NoClassDefFoundError UnsatisfiedLinkError VerifyError ThreadDeath VirtualMachineError InternalError OutOfMemoryError StackOverflowError UnknownError APPENDIX C: Java Class Hierarchy java.lang ColorModel DirectColorModel IndexColorModel ImageConsumer* ImageFilter Cloneable* CropImageFilter RGBImageFilter FilteredImageSource ImageProducer* MemoryImageSource ImageProducer* PixelGrabber ImageConsumer* APPENDIX C java.awt.image Object (java.lang) 191 192 JAVA PROGRAMMING: PART 1 Object (java.lang) BorderLayout LayoutManager* CardLayout LayoutManager* CheckBoxGroup Color Component ImageObserver* Button Canvas java.awt Checkbox java.awt.image Choice java.applet Container Panel Applet Window Dialog FileDialog Frame MenuContainer* Label List AppletContext Scrollbar TextComponent TextArea TextField AppletStub AudioClip APPENDIX C: Java Class Hierarchy java.lang Event FlowLayout LayoutManager* Font FontMetrics Graphics GridBagConstraints Cloneable* GridBagLayout LayoutManager* GridLayout LayoutManager* Image Insets Cloneable* MediaTracker MenuComponent MenuBar MenuContainer* MenuItem Menu CheckBoxMenuItem Point Polygon Rectangle Toolkit MenuContainer* APPENDIX C java.awt Dimension 193 194 JAVA PROGRAMMING: PART 1 java.util Object (java.lang) java.lang BitSet Cloneable* Date Dictionary HashTable Cloneable* Properties Observable Random StringTokenizer Enumeration Vector Cloneable* Stack Observer ▼ ▼ ▼ ANSWERS To Review Questions 196 JAVA PROGRAMMING: PART 1 ➤➤➤ LESSON 2 Review questions, page 46 1. javac 2. Browsers usually run Java applets, though several programs (including appletviewer and HotJava) can also run Java applets. 3. 4. False. Java applications require a main method, but Java applets do not. 5. False. import merely allows programmers to type shorter names when accessing classes or methods. ➤➤➤ LESSON 3 Review questions, page 74 1. a. int b.int c. long d. double e. double 2. a. The & operator always evaluates both its left and right operands. The && operator always evaluates its left operand, then evaluates its right operand only if the result of the left operand is true. b. The >> operator fills the high bits of the result with the sign bit of the operand, retaining the original sign in the result. (This is an arithmetic right shift, because it is equivalent to division by a power of two.) The >>> operator fills the high bits of the result with zero. (This is a logical right shift.) 3. The variable named half has gone out of scope at the close of the compound statement within the do..while loop, but it appears in a relational expression afterward. ANSWERS: To Review Questions LESSON 4 Review questions, page 91 1. The declaration is as follows: Animal Lion = new Animal(500, 45); 2. The following two lines are needed: Lion.weight = 250; Lion.length = 35; 3. There may be only one public class in any particular source file. ➤➤➤ LESSON 5 Review questions, page 103 1. A class with default protection can be accessed (and instantiated) only by other classes in the same package. 2. final 3. static ➤➤➤ LESSON 6 Review questions, page 117 1. The length data member is read-only, and as a result can not be explicitly modified. 2. The two methods are: new_sport = sport.concat(“ball”); // or new_sport = sport + “ball”; ANSWERS ➤➤➤ 197 198 JAVA PROGRAMMING: PART 1 3. StringBuffers are needed to modify character arrays, since regular Strings are immutable. ➤➤➤ LESSON 7 Review questions, page 136 1. The declarations are as follows: public class Animal { } public class Dog extends Animal { } public class Bulldog extends Dog { } 2. Both protected and private protected members are accessible to derived classes. However, a protected member is accessible to any class in the same package, while a private protected member is not. 3. The super keyword is used in a derived class constructor to call the base class’s constructor. ➤➤➤ LESSON 8 Review questions, page 160 1. java.applet.Applet 2. getParameter ANSWERS: To Review Questions ANSWERS 3. The HTML code is: 199
Source Exif Data:
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
PDF Version                     : 1.2
Linearized                      : Yes
Create Date                     : 1998:10:01 13:05:01
Producer                        : Acrobat Distiller 3.02
Creator                         : FrameMaker 5.5.3L15a
Modify Date                     : 1998:10:01 13:09:28
Page Count                      : 207
Page Mode                       : UseOutlines
EXIF Metadata provided by EXIF.tools

Navigation menu