Vous êtes sur la page 1sur 270

Java Fundamentals (Java SE 7)

Java Fundamentals (Java SE 7)


Java Fundamentals (Java SE 7)
Part Number: NH85664(IGEE)
Course Edition: 1.0

ACKNOWLEDGMENTS
Project Team
Content Developer: Anusha Ganti Content Manager: Solomon Antony Graphic Designer: Thyagarajan M Project
Manager: Suresh I and Rajkumar Lingavan Media Instructional Designer: Content Editor: Tayub Refai Materials Editor:
Karthika Sathish Business Matter Expert: Technical Reviewer: John Rizzo Project Technical Support: Mike Toscano

NOTICES
DISCLAIMER: While Element K Corporation takes care to ensure the accuracy and quality of these materials, we cannot guarantee their accuracy, and all materials are provided without any warranty
whatsoever, including, but not limited to, the implied warranties of merchantability or tness for a particular purpose. The name used in the data les for this course is that of a ctitious company. Any
resemblance to current or future companies is purely coincidental. We do not believe we have used anyones name in creating this course, but if we have, please notify us and we will change the name in
the next revision of the course. Element K is an independent provider of integrated training solutions for individuals, businesses, educational institutions, and government agencies. Use of screenshots,
photographs of another entitys products, or another entitys product name or service in this book is for editorial purposes only. No such use should be construed to imply sponsorship or endorsement of
the book by, nor any afliation of such entity with Element K. This courseware may contain links to sites on the Internet that are owned and operated by third parties (the External Sites). Element K is
not responsible for the availability of, or the content located on or through, any External Site. Please contact Element K if you have any concerns regarding such links or External Sites.

TRADEMARK NOTICES: Element K and the Element K logo are trademarks of Element K Corporation and its afliates.

Eclipse is a registered trademark of Apache Software Foundation in the U.S. and other countries; the Java products and services discussed or described may be trademarks of Oracle. All other product
names and services used throughout this course may be common law or registered trademarks of their respective proprietors.

Copyright 2012 2012 Logical Operations, Inc. All rights reserved. Screenshots used for illustrative purposes are the property of the software proprietor. 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 express written
permission of Logical Operations, 500 Canal View Boulevard, Rochester, NY 14623, (585) 240-7500, (800) 478-7788. Logical Operations World Wide Web site is located at
www.logicaloperations.com.

This book conveys no rights in the software or other products about which it was written; all use or licensing of such software or other products is the responsibility of the user according to terms and
conditions of the owner. Do not make illegal copies of books or software. If you believe that this book, related materials, or any other Logical Operations materials are being reproduced or transmitted
without permission, please call (800) 478-7788.

ii Java Fundamentals (Java SE 7)


CONTENTS
JAVA FUNDAMENTALS (JAVA SE 7)

LESSON 1 - PROGRAMMING IN JAVA


A. Create a Simple Java Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Java Programming Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Java Platform Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
The Eclipse IDE Workbench . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
The Main Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
B. Dene a Simple Class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Instantiation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Attributes. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
The Dot Notation Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Types of Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
C. Create and Initialize Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Identiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Primitive Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Enumerated Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Types of Literals . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

Contents iii
CONTENTS
D. Write an Expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Arithmetic Operators in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Relational Operators in Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Increment and Decrement Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Prex and Postx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Operator Precedence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
E. Work with Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Arrays. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Multi-dimensional Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Array Data Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

LESSON 2 - CONTROLLING PROGRAM FLOW


A. Write If Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
The If Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Control Flow Through If Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
The If...Else Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Control Flow Through If...Else Statements . . . . . . . . . . . . . . . . . . . . . . . . . 56
Nested If Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Control Flow Through Nested If Statements . . . . . . . . . . . . . . . . . . . . . . . 58
B. Write a Switch Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Switch Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
The Break Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Control Flow Through Switch Statements . . . . . . . . . . . . . . . . . . . . . . . . . 66
Switch Statement with Enum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67

iv Java Fundamentals (Java SE 7)


CONTENTS
C. Write a For Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Control Flow Through For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Nested For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Control Flow Through Nested For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . 75
The Continue Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
ForEach Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Accessing Array Data Using For Each Loops . . . . . . . . . . . . . . . . . . . . . . . 77
D. Write While and Do...While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
The While Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Control Flow Through While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Do...While Loops. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Control Flow Through Do...While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . 85

LESSON 3 - WORKING WITH JAVA CLASS LIBRARIES


A. Use the Java Class Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Java Class Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Packages in the Java Class Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
The Math Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
The String Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
The StringBuffer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
B. Invoke Attributes of an Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
Dot Notation for Attributes and Methods . . . . . . . . . . . . . . . . . . . . . . . . . 104
Method Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
Methods of the Math Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Methods of the String Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Methods of the StringBuffer Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108

LESSON 4 - CREATING CLASSES


A. Dene Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Method Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Local Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

Contents v
CONTENTS
B. Overload a Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Method Overloading . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
C. Dene Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Constructor Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
The This Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129
Overloading Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
D. Create Static Class Members . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Static Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
Static Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
E. Use Command-Line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Command-Line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
F. Dene JavaBeans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
The JavaBean Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
Getter and Setter Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148

LESSON 5 - IMPLEMENTING INHERITANCE


A. Import a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
Import Declaration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
B. Extend a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Inheritance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Subclass and Superclass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Access Modiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
C. Override Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Method Overriding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
D. Create Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Abstract Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
E. Implement Interfaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
Interface Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176
F. Work with Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
The Equals Method . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
The Instanceof Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Object Casting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180

vi Java Fundamentals (Java SE 7)


CONTENTS
LESSON 6 - REPRESENTING OOP CONCEPTS USING UML
A. Introduction to UML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
UML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Types of UML Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Class Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
UML Representation for Java Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
B. Apply UML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
UML Notations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
UML for OOP Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190

LESSON 7 - IDENTIFYING CLIENT-SIDE TECHNOLOGIES


A. Introduction to Client-Side Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
Client-Side Technologies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
Types of Client-Side Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
B. Introduction to Thin UI Clients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
The Thin UI Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
HyperText Markup Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Thin UI Deployment Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
C. Introduction to Fat UI Clients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Applets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Swing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199
Instantiating Swing Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Types of Swing Containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
JWindow Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Methods of JFrame . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Deployment Issues with Swing and Applets . . . . . . . . . . . . . . . . . . . . . . . 200
D. Introduction to Micro UI Clients . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
Java ME. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
MIDlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
The Life Cycle of a MIDlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
MIDlet Deployment Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203

Contents vii
CONTENTS
LESSON 8 - IDENTIFYING SERVER-SIDE TECHNOLOGIES
A. Introduction to Server-Side Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
Server-Side Technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
The Java EE Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
Server-Side Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
B. Identify Web Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Servlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
The Life Cycle of a Servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
The JSP Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
The JSP Life Cycle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
C. Identify Business Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
The EJB Technology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
Types of EJB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
The Home Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
The Remote Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
D. Process XML and Associating Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
The XML Parser . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Types of XML Parsers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
XML Binding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216

LESSON 9 - IDENTIFYING INTEGRATION TECHNOLOGIES


A. Describe Synchronous Communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
JNDI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
RMI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
RMI Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 221
RMI Interface and Classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
B. Introduction to Web Services . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
JAX-RPC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
SOAP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
UDDI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
WSDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224

viii Java Fundamentals (Java SE 7)


CONTENTS
C. Introduction to Database Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
RDBMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
SQL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
JDBC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
D. Describe Asynchronous Communication . . . . . . . . . . . . . . . . . . . . . . . . . . 228
JavaMail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
JMS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228

LESSON LABS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233


GLOSSARY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

Contents ix
NOTES

x Java Fundamentals (Java SE 7)


INTRODUCTION

ABOUT THIS COURSE


The Java Fundamentals (Java SE 7) course helps you to build a foundation of basic concepts
of Java programming language and covers the essential elements of the Java Standard Edition
7. This course offers you a job-related approach to successful Java programming. Finally, it
provides all the basic skills required to develop functionally sound and efficient Java applica-
tions.
Java SE 7, one of the most popular programming languages available today, employs object-
oriented techniques, making it powerful, functional, and efficient. The skills and knowledge
you gain in this course will help you master Java programming to create robust, multi-platform
applications.

Course Description
Target Student
This course is designed for students who are looking for an entry into an application develop-
ment or a software project management career using Java technologies.

Course Prerequisites
This is the rst course in the series of Java courses and does not have any prerequisites.

Introduction xi
INTRODUCTION
How to Use This Book
As a Learning Guide
This book is divided into lessons and topics, covering a subject or a set of related subjects. In
most cases, lessons are arranged in order of increasing prociency. The results-oriented topics
include relevant and supporting information you need to master the content. Each topic has
various types of activities designed to enable you to practice the guidelines and procedures as
well as to solidify your understanding of the informational material presented in the course. At
the back of the book, you will nd a glossary of the denitions of the terms and concepts used
throughout the course. You will also nd an index to assist in locating information within the
instructional components of the book.

As a Review Tool
Any method of instruction is only as effective as the time and effort you, the student, are will-
ing to invest in it. In addition, some of the information that you learn in class may not be
important to you immediately, but it may become important later. For this reason, we encour-
age you to spend some time reviewing the content of the course after your time in the
classroom.

As a Reference
The organization and layout of this book make it an easy-to-use resource for future reference.
Taking advantage of the glossary, index, and table of contents, you can use this book as a rst
source of denitions, background information, and summaries.

Course Objectives
In this course, you will create basic applications using the Java SE 7 programming language.
You will also describe object-oriented concepts, Unied Modeling Language (UML) represen-
tation of object-oriented programming (OOP) concepts, and Java platforms and technologies.
You will:
create simple programs in Java using basic code components.
control program ow by writing code to respond to specic situations and produce appro-
priate results.
work with Java class libraries to instantiate objects from Java classes.
create classes.
write Java programs that reuse objects and their attributes.
represent OOP concepts using UML.
identify client-side technologies.
identify server-side technologies.
identify integration technologies.

xii Java Fundamentals (Java SE 7)


INTRODUCTION
Course Requirements
This course was developed
using the Windows 7
Hardware Professional operating system;
however, the manufacturers
For this course, you will need one computer for each student and one for the instructor. Each
documentation states that it
computer will need the following minimum hardware congurations: will also run on Windows
1 GHz Pentium-class processor or faster Vista. If you use Vista, you
might notice some slight
Minimum 256 MB of RAM (512 MB of RAM recommended) differences when keying the
10 GB hard disk or larger (You should have at least 250 MB of free hard disk space course.
available for the Eclipse installation)
CD-ROM drive
Keyboard and mouse or other pointing device
1024 x 768 resolution monitor recommended
Network cards and cabling for local network access
Internet access (contact your local network administrator)
Printer (optional) or an installed printer driver
Projection system to display the instructors computer screen

Software
Eclipse for Java SE 7, Indigo
JDK 1.7

Class Setup
For Initial Class Setup
1. Install Windows 7 Professional on an empty partition.
Leave the Administrator password blank.
For all other installation parameters, use values that are appropriate for your environ-
ment (see your local network administrator for details).
2. On Windows 7 Professional, disable the Welcome screen. (This step ensures that students
will be able to log on as the Administrator user regardless of what other user accounts
exist on the computer.)
a. Click Start and choose Control PanelUser Accounts.
b. Click Change The Way Users Log On And Off.
c. Uncheck Use Welcome Screen.
d. Click Apply Options.
3. On the computer, install a printer driver (a physical print device is optional). Click Start
and choose Printers and Faxes. Under Printer Tasks, click Add a Printer and follow
the prompts.

Introduction xiii
INTRODUCTION
If you do not have a physical printer installed, right-click the printer and choose Pause
Printing to prevent any print error message.
4. Run the Internet Connection Wizard to set up the Internet connection as appropriate for
your environment, if you did not do so during installation.
5. Display known le type extensions.
a. Right-click Start and select Explore to open Windows Explorer.
b. Choose ToolsFolder Options.
c. On the View tab, in the Advanced Settings list box, uncheck Hide Extensions For
Known File Types.
d. Click Apply and then click OK.
e. Close Windows Explorer.

For JDK Setup


1. Run the executable le for JDK 1.7. (Update 3 was used for testing this course).

For Eclipse IDE Setup


1. Download and extract the Eclipse IDE for Java SE 7 (Indigo version) from
www.eclipse.org/.
2. Create a shortcut to the Eclipse executable le on the desktop.

Before Every Class


1. Log on to the computer as the Administrator user.
2. If necessary, delete the C:\085664Data folder.
3. On the course CD-ROM, run the 085664dd.exe self-extracting le located in the Data
folder. This will install a folder named 085664Data on your C drive. This folder contains
all the data les that you will use to complete this course. Solution les are also provided
in this folder. These les may help you nd a possible solution if you get stuck at any
point during the course.

List of Additional Files


Printed with each activity is a list of les students open to complete that activity. Many activi-
ties also require additional les that students do not open, but are needed to support the le(s)
students are working with. These supporting les are included with the student data les on the
course CD-ROM or data disk. Do not delete these les.

xiv Java Fundamentals (Java SE 7)


LESSON 1

LESSON 1 Lesson Time


5 hour(s)

Programming in Java
In this lesson, you will create simple programs in Java using basic code components.
You will:
Create a simple Java program.
Create a simple class.
Create and initialize variables.
Write an expression.
Work with arrays.

Lesson 1: Programming in Java 1


LESSON 1
Introduction
The Java programming language possesses the capability to create visually rich, dynamic, and
interactive applications. Before leveraging these capabilities, you need to understand the syntax
and structure of the Java programming language. In this lesson, you will create, compile, and
run simple Java applications.
Java provides you with a rich programming environment for developing a variety of platform-
independent applications. As with all programming languages, the quickest way to understand
Java is by creating simple applications. Such an exercise will help you to build your knowl-
edge of Java and develop complex programs.

TOPIC A
Create a Simple Java Program
The best way to learn how to compile and run a simple Java application is by building your
own application. To begin using Java, you will need a solid understanding of the Java pro-
gramming language and its structure. In this topic, you will create a simple Java program.
Knowing how to compile and run Java source code is important to create Java applications.
You can employ the basic architecture of Java programming to create a simple application.
This will help you to understand the syntax and structure of Java better and enable you to cre-
ate complex programs at a later stage.

Java Programming Language


Java is a secure, platform-independent, object-oriented, and interpreted programming language.
It is used to create high-end applications for a variety of domains, such as mobile phones and
the web. In addition, the consistent syntax framework of Java helps programmers to write pro-
grams easily.

OOP
Object-oriented programming (OOP) is a programming technique that:
Is based on the concept of combining data and functions into a single entity.
Refers to each entity as an object, which contains specic attributes, behaviors,
and values.
Utilizes the object-oriented philosophy.
Denes specic structures and keywords for actual implementation of object ori-
entation during programming.

Java Platform Process


Java Platform Process
The Java platform process consists of ve programming phasesedit, compile, load, verify,
and interpret. To execute a new or a modied program, all ve phases of the process must be
performed.
1. In the edit phase, programmers use a text editor to write, correct, and save their source
code.

2 Java Fundamentals (Java SE 7)


LESSON 1
2. In the compile phase, Java source code is translated into computer-readable machine code,
or bytecode.
3. In the load phase, the class loader uses the compiled le and transfers the bytecode into
the computers primary memory.
4. In the verify phase, the bytecode contained within the le is validated.
5. In the interpret phase, the Java Virtual Machine (JVM) reads the bytecode to execute the
Java application.

Figure 1-1: The Java platform process.

IDE
Java code can be written in simple text les and executed through the command
prompt. However, when creating large applications, extensive code needs to be created.
Programmers typically use an Integrated Development Environment (IDE) such as
Eclipse or NetBeans, to write and maintain code in Windows, UNIX, or Mac environ-
ments.

JVM
A JVM is the component of the Java technology that enables Java programs to be
delivered across different platforms. A JVM provides an abstract environment in which
the bytecode of a Java program can be executed. A JVM is distributed along with a set
of standard class libraries that implement the Java application programming interface
(API).

Eclipse
Eclipse is a commonly used Integrated Development Environment (IDE) for developing Java
applications. It provides shortcuts that enable developers to write code quickly and correctly. It
is a platform-independent open source software that is distributed with a free license and pro-
vides a core shell, in which developers can add the necessary plug-ins based on the type of
application they intend to create. It enables easy integration of different components of a soft-
ware system that are developed in various phases of product development.

Lesson 1: Programming in Java 3


LESSON 1
The Eclipse IDE Workbench
The Eclipse IDE Workbench
When you start Eclipse IDE, it launches a workbench consisting of various components and
provides the necessary tools for developing programs.

Figure 1-2: The Eclipse IDE Workbench.

Workbench
Component Description
Menu bar Provides access to all commands.
Toolbar Provides quick access to often used commands.
Editor area Displays the content of the selected le in an appropriate editor. Content of multiple
les can be stacked in the editor area. An asterisk appears before the le name to
indicate that the changes to the le are not saved.
Views Provides navigation information in the workbench. Each view may contain a menu,
accessed by clicking the icon at the left end of the views title bar, and a toolbar.
Examples of views include Bookmarks view and Task view.
Resources Comprises les, folders, and projects that are displayed in an hierarchical view in the
project explorer.

Perspective
A perspective denes the initial set and layout of views in the workbench window,
including options in menus and the toolbar. Each perspective provides functionality
aimed at accomplishing a specic type of task using specic types of resources. Each
category of Eclipse users, such as developers and code reviewers, customize the layout
of the view to suit the specic requirement of their roles.

4 Java Fundamentals (Java SE 7)


LESSON 1
The Main Method
Denition: Main Method
A method is a way of dening actions that a component of a Java application can per-
form. A main method is a type of method that:
The method concept is
Provides the entry point for a Java application. covered in detail later in this
Declares all actions performed by the application. lesson. Right now, it is
sufcient to introduce the
Is required by standalone Java programs. If a standalone Java program does not main method as a method type
contain a main method, an error is thrown and the application is not executed. without explaining the details.
Contains the method body within the open and close braces. The method body
varies for different Java applications.

Syntax: The Main Method


The main method uses the following syntax:
public static void main (String [] args)
{
//..action statements
}

Example:

Figure 1-3: A main method.

How to Create a Simple Java Program


Procedure Reference: Create, Compile, and Run a Simple Java Application
To create, compile, and run a simple Java application:
1. Open a new text le.
2. Dene a new class by specifying the class name.
3. Dene the main method by specifying the return type and parameters.
4. Type code inside the main method.
5. Save and compile the program.
6. Run the program.
7. View the output of the program to verify its functionality.

Lesson 1: Programming in Java 5


LESSON 1
It is strongly recommended and is considered a best practice to use a current-generation IDE
such as Eclipse to write code in Java. However, you can enter your code directly in a text editor
such as Notepad, or a more sophisticated editor such as Textpad that provides automatic line
numbering and other features. If you use a text editor to create your code, then you will need to
save it manually and compile it using the javac compiler.

How to use the javac compiler


is covered in lesson 3.
Procedure Reference: Run an Existing Java Application
To run an existing Java application:
1. Open the Java source le.
2. If required, view and edit the source code.
3. Run the program.
4. View the output of the program to verify its functionality.

ACTIVITY 1-1
Creating a Simple Java Program
Data Files:
Kiosk_1A.jar

Scenario:
You are a Java programmer for the Home Improvement Retail division of Our Global Com-
pany (OGC) Inc. The division has more than 100 stores across the United States. Your
manager asks you to take over a project to develop an in-store kiosk application, which will
provide customers with product information and store locations. Youll begin with a limited
number of products to test the kiosk and eventually roll it out to include all products for all
stores. Your rst step is to verify the functionality of les you received by compiling and run-
ning a simple application. Because you will be using the Eclipse IDE, you want to explore its
various features so that you work easily.

6 Java Fundamentals (Java SE 7)


LESSON 1
What You Do How You Do It

1. Explore the Eclipse IDE interface. a. On the desktop, double-click the eclipse -
Shortcut icon to launch the Eclipse IDE.

b. To select a workspace, in the Workspace


Launcher dialog box, in the Select a
workspace page, in the Workspace text
box, type C:\085664Data\Workspace
and click OK.

c. In the Welcome screen, click Close.

d. To view the options of the File menu,


choose File.

e. View the options of the File menu. Then,


to close the File menu, choose File.

f. To view the tooltip of a Toolbar button,


on the toolbar, position the mouse pointer
over New.

2. Access help on using the Eclipse IDE. a. To seek information on using the Eclipse
IDE, choose HelpHelp Contents.

b. In the Help - Eclipse window, in the Con-


tents pane, click the Workbench User
Guide link.

c. On the right pane, click the Eclipse plat-


form overview link.

d. In the right pane, view the information


related to the Eclipse platform.

Lesson 1: Programming in Java 7


LESSON 1
e. Below the title bar, in the Search text
box, type console view and click Go.

f. In the Search Results pane, click the Con-


sole View link, which is the first search
result.

g. On the right pane, view the information


related to Console View and close the
Help - Eclipse window.

3. Import the Kiosk application into the a. In the Eclipse IDE, choose FileImport.
Eclipse IDE.
b. In the Import wizard, in the Select page,
in the Select an import source list box,
expand the General folder.

c. From the list of options, select the Exist-


ing Projects into Workspace option and
click Next.

d. In the Import Projects page, select the


Select archive file option and click
Browse.

e. In the Select archive containing the


projects to import dialog box, navigate to
the C:\085664Data\Programming in Java
folder and open the Kiosk_1A.jar file.

f. In the Import Projects page, in the


Projects list box, verify that the project
name appears selected and click Finish.

8 Java Fundamentals (Java SE 7)


LESSON 1
g. Observe that the project name appears in
the Package Explorer view.

Lesson 1: Programming in Java 9


LESSON 1
4. View the source code and execute a. To view the file associated with the
the program. Kiosk_1A project, in the Package Explorer
view, expand the Kiosk_1A
project.

b. To view the associated packages, in the


Package Explorer view below Kiosk_1A,
expand the src folder.

c. To view the source files associated with


this package, in the Package Explorer
view, expand the (default package)
folder.

d. From the displayed list, double-click the


Kiosk_1A.java file to open it in the Text
Editor area.

e. View the source code of the Kiosk_1A.java


file and the syntax of the main method.
Then, on the toolbar, click Run.

f. Below the Text Editor area, in the Con-


sole view, view the output of the
Kiosk_1A application.

g. In the Package Explorer view, select the


Kiosk_1A project.

h. To close the selected project, choose


ProjectClose Project.

10 Java Fundamentals (Java SE 7)


LESSON 1
TOPIC B
Dene a Simple Class
In the previous topic, you created a simple Java program to establish the basic syntax and
structure of Java. Now you may want to write specic code that allows your application to
store the data it needs to process. In this topic, you will create a simple class.
Now that you are familiar with the Java programming language, you have the necessary tools
to begin coding. the In this topic, you will identify the relationship between classes and
objects, and create a simple class. You will also discover how classes and objects take on
attributes and behaviors to create functionality within a Java application.

Class
Denition: Various attributes of a class
will be covered in detail later
A class is a Java code element that:
in this lesson.
Denes a template containing attributes and methods.
Is used to create objects.
Class
Begins with the keyword class.
Contains attributes and methods within braces that delimit its beginning and end.

Syntax: Class Declaration


A class name is usually indicative of its use. If you cannot identify the use of a class
from its name, then you should rethink its name. By convention, class names start with
an uppercase letter. A class declaration uses the following syntax:
class ClassName {...}

Example:

Figure 1-4: A class declaration.

Case Sensitive Feature


Java is a case-sensitive language. If you declare an element, such as a class, variable,
or method using lowercase letters, but refer to it using uppercase letters, the compiler
will consider the two names to be different. For example, myMethod and myMETHOD
are considered to be two different identiers. The second line does not compile
because the identier myMETHOD is not dened.
String myVariable = new String ("Hello");
System.out.println( myVARIABLE );

Lesson 1: Programming in Java 11


LESSON 1
Naming Conventions in Java
Java developers strongly enforce specic naming conventions. Even though the Java
compiler will let you break naming conventions, Eclipse may remind you to adhere to
naming conventions through warnings in source code. Naming conventions in Java
include:
Identiers are usually in camel-case, that is each word starts with an uppercase
letter. For example: ClassEmployeeDetails.
Variables, attributes, and method names start with a lowercase letter. For example:
totalDepartments, main(...), and println(...).
Package names are in lowercase. For example: java.lang, java.util, and
com.ourglobalcompany.myproject.model.
Constant names are usually in uppercase and may contain an underscore word
separator. For example: MAX_TEMPERATURE.

Objects
Objects Denition:
An object is a Java code element that:
Is declared from a class as an instance of that class.
Is a self-contained item that stores specic and unique data values.
Shares features with the class and all objects instantiated from the same class.
Contains related actions to perform a task.
May use other objects to perform an action.

Example:

Figure 1-5: Declaration of objects in a Java class.

Instantiation
Instantiation Denition:
Instantiation is a Java code statement that:
Creates an instance, or object, for a class in Java.
Species a name for the object during instantiation, which you can use to refer-
ence the object in your code.
Uses the Java keyword new followed by the class name.
Invokes a constructor method, dened within a class, that will initialize objects in
the class.

12 Java Fundamentals (Java SE 7)


LESSON 1
Allocates memory space when an object is created.

Syntax: Instantiation
The instantiation statement uses the following syntax to create a new object of a class:
ClassName objectName = new ClassName(value);

Example:

Figure 1-6: Object instantiation.

Object Reuse
The Java programming language allows you to reuse an object to save valuable pro-
gramming time. Once you dene a class with a specic set of features and behaviors,
you can use it to create numerous objects. In other words, you reuse the variables and
methods dened in a class without having to rewrite the code dening the class. Effec-
tive programmers determine the right set of classes to fulll their programming
requirements.

Attributes
Denition: Attributes
Attributes are characteristics that:
Are displayed by a class and its objects.
Determine various features of a class or object, such as the appearance, state, and
type.
Are dened as variables to hold specic values.

Example:

Figure 1-7: Attributes of the BankAccount class.

Lesson 1: Programming in Java 13


LESSON 1
Static Variables
The keyword static may be used before a variables declaration to dene that the
attribute is accessible to the entire class.

Methods
Methods Denition:
A method is a Java element that:
Denes an action or behavior for objects based on a class.
May communicate with other objects by sending or receiving information and
commands.
May alter the attributes of dened objects.
May be used once or applied to an entire class.
Consists of two partsdeclaration and body.
Contains the name, return type, and parameters in the declaration part.
May dene its return type and parameters.
Contains the code to perform the required action in the method body.
A method may accept arguments, within parentheses, to perform its tasks. When imple-
menting behaviors, methods are named to dene the active properties of a class.

Example:

Figure 1-8: Declaration of a method.

Naming Methods
When implementing behaviors, methods are named to dene the active properties of a
class. For example, to display the employee name, number, and designation, use
method names such as displayName, displayNumber, and displayDesignation respec-
tively.

The Dot Notation Operator


Dot notation is an operation to reference attributes and methods of a class using the dot opera-
tor ( . ). In Java, you use dot notation between an object and its variables or methods. For an
object of a class to call a specic method, you use the dot operator with the syntax,
objectName.methodName();.

14 Java Fundamentals (Java SE 7)


LESSON 1
Comments
Denition: Comments
Comments are statements in source code that are:
Ignored by the Java compiler.
Used by developers to enter notes that describe a code blocks purpose or func-
tionality.
Used to prevent a line or a block of code from executing while testing and debug-
ging a program.

Example:

Figure 1-9: Comments in Java code.

Types of Comments
Java supports three types of comments in source code.

Comment Type Used To


Single-line comments Preserve comments that span a single line. They are preceded by a double slash
(//) and do not need any terminating character.
Multi-line comments Preserve comments that span multiple lines. They are preceded by /* and end
with */.
Computer-readable Denote official documentation for class and method functions. They may be
comments interpreted by some Java utilities, such as javadoc. They are preceded by /**
and end with */.

Javadoc
Javadoc is the Java Development Kit (JDK) tool that uses declarations and documenta-
tion comments in source code to create an HTML document that describes the objects
in the code.

Lesson 1: Programming in Java 15


LESSON 1
Create a Simple Class
Procedure Reference: Create a Simple Class
To create a simple class:
1. Open a new source code le.
2. In the le, insert a class declaration.
3. If necessary, declare any class objects in the class body.
4. If this is the main class, insert the main method declaration.
5. In the main method body, write code that performs a function.
6. If necessary, apply comments to the code.
To enter single-line comments, type // before the comment.
To enter multi-line comments, type /*, then enter the comment and end with
*/.
To enter computer-readable comments, type /**, then enter the comment
and end with */.
7. Save the le, giving it the same name as the class name, followed by the .java
extension.
8. Compile and run the le.

ACTIVITY 1-2
Creating a Simple Class
Data Files:
Kiosk_1B.jar

Before You Begin:


Import the C:\085664Data\Programming in Java\Kiosk_1B.jar project into the Eclipse IDE.

Scenario:
Now that you veried your le setup, your manager wants you to create a class to represent
the departments in your store that will be included in your kiosk. He informs you that the rst
test implementation of the kiosk application will only incorporate three departments: Paint,
Lumber, and Electrical. He describes some functionality he wants to have when running the
application. Currently, he would like to have the option to display the names of the depart-
ments below the welcome statement. As a professional programmer, when you create or
modify a program, you follow the best practice of entering comments to describe the purpose
of code.

16 Java Fundamentals (Java SE 7)


LESSON 1
What You Do How You Do It

1. Create and initialize the variable for a. Display the source code of the Kiosk_
total departments. 1B.java file.

b. In the code, after the main methods open


brace, click to position the cursor.

c. Insert two new lines and type the name of


the class DepartmentType

d. Insert a space and then type the name of


the object based on the class as
paintDept

e. To instantiate the declared object, insert


a space and type = new
DepartmentType();

f. Similarly, declare and instantiate objects


to represent lumberDept and
electricalDept.

See Code Sample 1.

Code Sample 1
public class Kiosk_1B {

public static void main(String[] args) {

DepartmentType paintDept = new DepartmentType();

DepartmentType lumberDept = new DepartmentType();

DepartmentType electricalDept = new DepartmentType();

System.out.println("Welcome!");
}

Lesson 1: Programming in Java 17


LESSON 1
2. Set the value of the variable in the a. Position the cursor after the declaration
instantiated objects. statement for paintDept and insert a
new line.

b. To access the methods defined for the


paintDept, type paintDept.

c. Notice that a list appears displaying all


methods of the DepartmentType class.
From the displayed list, double-click to
select the setName(String aName) :
void method.

d. To pass a parameter for the method, type


"Paint"

e. Terminate the sentence with a semicolon.

f. Similarly, set the value of attributes of


lumberDept and electricalDept
objects to Lumber and Electrical
respectively.

See Code Sample 2.

Code Sample 2
public class Kiosk_1B {

public static void main(String[] args) {

DepartmentType paintDept = new DepartmentType();


paintDept.setName("Paint");

DepartmentType lumberDept = new DepartmentType();


lumberDept.setName("Lumber");

DepartmentType electricalDept = new DepartmentType();


electricalDept.setName("Electrical");

System.out.println("Welcome!");
}

18 Java Fundamentals (Java SE 7)


LESSON 1
3. Include code to print the department a. Position the cursor below the statement
names. that prints the Welcome message.

b. To access the methods of PrintStream,


type System.out.

c. From the displayed list of PrintStream


methods, scroll down and select the
println(Object arg0) : void PrintStream
option.

d. From the displayed list of available


objects, double-click to select the
paintDept option.

e. To access the methods of the paintDept


object, verify that the pointer is at the
end of the text paintDept and enter a
period.

f. From the displayed list of available meth-


ods, double-click to select the
getName() : String -
DepartmentType option.

g. Terminate the statement by entering a


semicolon at the end of the statement.

h. Similarly, write code to display the names


for the Lumber and Electrical depart-
ments.

See Code Sample 3.

Code Sample 3
public class Kiosk_1B {

public static void main(String[] args) {

DepartmentType paintDept = new DepartmentType();


paintDept.setName("Paint");

DepartmentType lumberDept = new DepartmentType();


lumberDept.setName("Lumber");

DepartmentType electricalDept = new DepartmentType();


electricalDept.setName("Electrical");

System.out.println("Welcome!");
System.out.println(paintDept.getName());
System.out.println(lumberDept.getName());
System.out.println(electricalDept.getName());
}

Lesson 1: Programming in Java 19


LESSON 1
4. Insert comments to describe the a. Position the cursor above the first state-
code. ment that creates an instance of the
DepartmentType class and insert two
blank lines.

b. To add a single line comment, type the


comment // Create instances of
the DepartmentType class

c. Position the cursor above the statement


that prints Welcome and insert two
blank lines.

d. To add a multi-line comment, type


/* Displays welcome message and
insert a new line.

e. Notice that the closing comment tags are


automatically entered in the following
line and then type and department
names.

5. Save and run the program to test the a. To save the file, click Save .
code entries.

b. Display the Problems tab.

c. Verify that there are no errors or warning


listed in the code.

d. To execute the application, click inside


the Text Editor area and then on the
toolbar, click Run.

e. In the Console view, view the output of


the program.

f. Close the project.

20 Java Fundamentals (Java SE 7)


LESSON 1
TOPIC C
Create and Initialize Variables
In the previous topic, you created methods and objects in a class. When Java source code con-
tains classes, you can use them to process the data stored in variables to derive useful
information. In this topic, you will create and initialize variables.
When you create applications, you need to process large amounts of various types of data,
such as text and numbers. Java allows you to create and initialize variables so that you can
dene a temporary storage space to save the data that the application needs to process.

Statements
Denition: Statements
A statement is a Java language construct that:
Contains instructions to perform specic actions.
Can incorporate multiple actions.
Must be terminated by a semicolon ( ; ).
Can span multiple lines by using a semicolon at the end of the last line of the
statement; multiple statements can also be written in a single line by terminating
each statement with a semicolon.
Can be grouped to form statement blocks.

Example:

Figure 1-10: Statements within a block of code.

Block Statements
Multiple Java statements may be grouped using braces to form a block statement.
Block statements are logical units of statements, usually associated with a specic
statement container such as a method or a loop. Java allows you to place a block state-
ment within another block statement so that you can visually format code for easy
interpretation.

System Output Statement


When programming in Java, you create numerous statements to output text onto the
computer screen. These statements use the System class, which uses static attributes
and, therefore, does not need instantiation. To create a system output statement display-
ing an item on a new line, you use the following syntax:
System.out.println("Welcome!");

Lesson 1: Programming in Java 21


LESSON 1
Keywords
Keywords Denition:
Keywords are words that:
Are reserved for use by Java.
May not be used to name Java applications or objects, such as classes, methods,
or variables.
Are case-sensitive and in lowercase.

Although null, false, and true may appear as keywords, they are not. They are constant variables
predened in Java and hold the value described by their name.

Example:

Figure 1-11: Correct keyword use.

List of Java Keywords


Some Java keywords are listed in the table.

abstract finally public


assert float return
boolean for short
break goto static
byte if strictftp
case implements super
catch import switch
char instanceof synchronized
class int this
const interface throw
continue long throws
default native transient
double new try
else package void
extends private volatile
final protected while
do

22 Java Fundamentals (Java SE 7)


LESSON 1

Identiers
An identier is a name that: Identiers
Identies a variable, class, or method.
Must begin with a letter, underscore ( _ ), or dollar sign ( $ ).
Can contain a combination of letters, numbers, underscore ( _ ), and dollar sign ( $ ).
Cannot use names reserved for Java keywords, such as new and class.

Figure 1-12: A legal identifier.

Variables
Denition: Variables
Variables are named memory locations that are:
Used for storing data items of a particular primitive type or a reference to an
object.
Conned to the scope of their denition, which can be:
At the local level inside a method.
At the object instance level when dened as a non-static attribute.
At the class level when dened as a static attribute.
Declared with a name and type of data to store.

Syntax: Variable Declaration


A variable is declared using the following syntax:
variable_type variable_name = variable_value;

Lesson 1: Programming in Java 23


LESSON 1
Example:

Figure 1-13: Variable declaration and types.

Multiple Variables
You can declare multiple variables within a single statement if variables are of the
same data type. For example, to initialize variables i, j, and k with integer values
3, 10, and 15, you can use the code int i=3, j=10, k=15;

Constants
A constant is a variable type in Java whose value does not change. Constants are
dened using the final keyword followed by the variable declaration. By conven-
tion, constant variable names are in uppercase:
final boolean LIGHT = true;

final boolean DARK = false;

Primitive Data Types


Java provides eight different predened primitive data types to store values of different for-
mats. Variables dened using primitive data types are initialized with predened values, unless
you assign a different value when they are declared.
The eight primitive data types in Java are byte, short, int, long, oat, double, char, and bool-
ean.

Primitive Data
Type Description
byte A byte-length integer that has a size of 8 bits. It has a default value of 0.
short A short integer that has a size of 16 bits. It has a default value of 0.
int An integer that has a size of 32 bits. It has a default value of 0.
long A long integer that has a size of 64 bits. It has a default value of 0L.
float A single-precision oating point value that has a size of 64 bits. It has a default
value of 0.0f.
double A double-precision oating point value that has a size of 64 bits. It has a default
value of 0.0d.
char A single character that has a size of 16 (Unicode) bits. It has a default value of
\u0000.
boolean A boolean value that carries either the value true or false. It has a default value false.

24 Java Fundamentals (Java SE 7)


LESSON 1
Enumerated Data Types
Denition: Enumerated Data Types
An enumerated data type, or enum, is a language construct in Java that:
Helps represent data sets with constant values.
Is dened using the keyword enum followed by an identier for the data set.
Contains values of the data set specied within braces following the identier.

Example:

Figure 1-14: An enumerated data type.

Literals
Denition: Literals
A literal in Java is any item that directly represents a particular value. Variables
belonging to any primitive types can also be assigned values and treated as literals.
Each variable type has a corresponding literal type, such as integer, character, string,
and boolean.

Example:

Figure 1-15: A literal in Java.

Types of Literals
There are four types of literals in Java, which are based on the types of variables present.

Lesson 1: Programming in Java 25


LESSON 1
Literal Type Description
Numeric literal Is dened any time you specically state that a variable is equal to an integer value.
You may use any integer value when declaring an integer literal. Should you require a
negative integer, simply prex the literal with a minus sign ( ). Likewise, hexadeci-
mal numbers may be used by prexing the integer literal with 0x and octal numbers
with 0.
Character lit- Is dened when there is a specic declaration of any character value. Character liter-
eral als are expressed through the use of a single character, bounded on either side by
single quotation marks. For example, a character literal for a would be expressed as
a. While you can access most character literals directly by typing them from your
keyboard, there does exist a group of character literals, specically character escape
code, that requires a special character to print or access them. For example, if you
used a single quotation mark outside of a comment, the Java compiler would not rec-
ognize it as a quotation mark, but rather as a portion of the code. Therefore, your
code would not compile successfully. To ensure that such code compiles successfully,
you need to use an escape character ( \ ) before character literals.
String literal Is dened when you represent a series of characters, often referred to simply as
strings. The characters in a string are located within a set of double quotation marks
(...). Within the quotation marks, you can use Unicode characters as well as special
character literals. To output strings, you can input spaces within the quotation marks.
boolean literal Is dened by boolean values. This is because any variable declaring a boolean value
is always equal to that valueeither true or false. For example, you can declare a
boolean variable, or boolean literal, with the following statement: boolean
day = true; Notice that because true is a variable value, it does not have
quotation marks around it. If you use quotation marks, the Java compiler will treat
the literal as a string of characters rather than a boolean value and generate an error.

Integer Literals
Examples of numeric literals are listed in the following table.

Integer Literal Data Type


178 int
8864L long
87.363F float
26.77e3 double

Escape Character Literals


Escape character literals in Java are listed in the following table.

Escape Char-
acter Literal Description
\n New line
\t Tab

26 Java Fundamentals (Java SE 7)


LESSON 1
Escape Char-
acter Literal Description
\b Backspace
\r Carriage return
\f Formfeed
\\ Backslash
\' Single quotation mark
\" Double quotation mark
\d Octal
\xd Hexadecimal
\ud Unicode character

How to Create and Initialize Variables


Procedure Reference: Create and Initialize Variables
To create and initialize a variable:
1. Open the source code of a Java program.
2. In the source code le, state the data type of the variable you want to create.
3. Type a legal identier to name the variable.
4. If necessary, assign a value to initialize the variable.

ACTIVITY 1-3
Creating and Initializing Variables
Data Files:
Kiosk_1C.jar

Before You Begin:


Import the C:\085664Data\Programming in Java\Kiosk_1C.jar project into the Eclipse IDE.

Scenario:
Your manager wants you to modify the welcome message to include the store name and print
the number of departments. You decide to use variables to store the welcome message and
number of departments so that you can easily access and print the required information.

Lesson 1: Programming in Java 27


LESSON 1
What You Do How You Do It

1. Create and initialize the variable for a. Display the source code of the Kiosk_
total departments. 1C.java file.

b. In the code, after the main methods open


brace, click to position the cursor.

c. Insert a new line and type the data type


of the variable as int

d. Insert a space and then type the variable


name as totalDepartments

e. To assign a value of 3 to the variable,


type =3;

2. Above the statement, enter a com- a. Position the cursor after the open brace of
ment to describe the variable. the main method and insert two new
lines.

b. Enter the single line comment //


Declare and initialize an
integer variable

See Code Sample 1.

Code Sample 1
// Declare and initialize an integer variable
int totalDepartments=3;

// Create instances of the DepartmentType class


DepartmentType paintDept = new DepartmentType();
paintDept.setName("Paint");

28 Java Fundamentals (Java SE 7)


LESSON 1
3. Create and initialize a constant vari- a. Position the cursor at the end of the line
able for the welcome message. where the totalDepartments variable
is initialized and insert a new line.

b. Declare the data type of the constant


variable as a string constant by typing
final String

c. Define a legal identifier for the variable


by entering a space and typing WELCOME

d. Assign a value to the variable by typing


= "Welcome to OGC Home
Improvement";

e. To write a comment to describe the


WELCOME variable, click after the state-
ment where the totalDepartments
variable is initialized and insert two new
lines.

f. Type the comment // Declare a


string constant for welcome
message

See Code Sample 2.

Code Sample 2
// Declare and initialize an integer variable
int totalDepartments = 3;
// Declare a string constant for welcome message
final String WELCOME = "Welcome to OGC Home Improvement";

// Create instances of the DepartmentType class


DepartmentType paintDept = new DepartmentType();
paintDept.setName("Paint");

4. Print the welcome message from the a. In the statement that prints the welcome
variable. message, select the "Welcome!" text
including the quotes.

b. To print the contents of the constant vari-


able that contains the welcome message,
type WELCOME

Lesson 1: Programming in Java 29


LESSON 1
5. Print the number of departments and a. Position the cursor at the end of the
comment the code. statement that prints the name of the
Electrical department and insert a new
line.

b. To print information to the screen, type


System.out.println();

c. To print the number of departments in the


store, within the parentheses, type
totalDepartments

d. Position the cursor at the end of the


statement that prints the name of the
Electrical department and insert two
lines.

e. Enter the single line comment //


Prints the number of departments

See Code Sample 3.

Code Sample 3
// Prints the number of departments
System.out.println(totalDepartments);

6. Save and run the program to test the a. Save the file.
code entries.
b. To check to see if there are any problems
in the code, below the Text Editor, select
the Problems tab to display it.

c. Verify that no errors or warnings are dis-


played.

d. To execute the application, on the


toolbar, click the Run button.

In case the program does not execute, you


need to click inside the Text Editor area before
you execute the application.

30 Java Fundamentals (Java SE 7)


LESSON 1
e. View the updated welcome message,
department names, and number of
departments.

f. Close the project.

TOPIC D
Write an Expression
In the previous topic, you used Java variables to declare and store information for use in an
application. When the Java source code contains variables, you can use the variables to create
and form expressions that generate values. In this topic, you will identify the various operators
and use them to create expressions.
Without knowing how to create accurate expressions, your code statements will not make any
sense. You will not be able to generate the necessary values needed to create the needed func-
tionality in your application.

Arithmetic Operators
Arithmetic operators are symbols used for performing operations such as addition, subtraction,
multiplication, and division. An operator requires two operands, one on either side of an
operator. The operand is the item upon which the operation is performed.

Arithmetic Operators in Java


There are ve arithmetic operators used in Java.

Arithmetic
Operator Description
+ Meaning: Addition
Syntax: x + y
Example:
7 + 9 will output 16

Lesson 1: Programming in Java 31


LESSON 1
Arithmetic
Operator Description
- Meaning: Subtraction
Syntax: x - y
Example:
8 - 6 will output 2
* Meaning: Multiplication
Syntax: x * y
Example:
4 * 3 will output 12
/ Meaning: Division
Syntax: x / y
Example:
20 / 5 will output 4
% Meaning: Modulus
The modulus, or remainder, operator returns the value of the remainder from a divi-
sion operation.
Syntax: x % y
Example:
16 % 3 will output 1, which is the remainder in this operation.

String Concatenation
When programming with strings of characters, or simply strings, the + operator may be
used to add or concatenate the strings together. Specically, concatenation refers to the
joining of two text items. For example, System.out.println("Account
Balance is" + balance); concatenates a string literal and variable balance.
Strings and variables are joined to create a logical statement for display purposes.

Automatic Type Conversion


Using arithmetic operators can easily lead to problems within the code, if they are not
used correctly. Many operations with arithmetic operators produce an int if an oper-
and uses integers. An automatic type conversion may occur regardless of the original
data type of your operands. This is common among operations using oating-point and
long type variables. To avoid automatic type conversion when it is an undesirable out-
come, you should ensure that both operands within the expression have the same type.
and automatic type conversion

Relational Operators
Relational operators are symbols used for determining relational comparisons between two
operands. All expressions created using relational operators will return a boolean value,
depending on whether the comparison is true. Expressions with relational operators have two
operands, one on either side of an operator.

Relational Operators in Java


Java provides you with six types of relational operators for use in code segments.

32 Java Fundamentals (Java SE 7)


LESSON 1
Relational
Operator Description
== Meaning: Equal
Syntax: a == b
Example: int x = 4;
int y = 5;
boolean z = (x==y); The variable z will be assigned false because the values
of x and y are not equal.
!= Meaning: Not Equal
Syntax: a != b
Example: int x = 10;
int y = 12;
boolean x = (x!=y); The variable z will be assigned false because the values
of x and y are not equal.
< Meaning: Less than
Syntax: a < b
Example: int x = 31;
int y = 20;
boolean z = (x < y); The variable z will be assigned false because the value
of x is not less than the value of y.
> Meaning: Greater than
Syntax: a > b
Example: int x = 31;
int y = 20;
boolean z = (x > y); The variable z will be assigned true because the value
of x is greater than the value of y.
<= Meaning: Less than or equal to
Syntax: a <= b
Example: int x = 8;
int y = 8;
boolean z = (x<=y); The variable z will be assigned true because the value of
x is equal to the value of y.
>= Meaning: Greater than or equal to
Syntax: a >= b
Example: int x = 8;
int y = 17;
boolean z = (x>=y); The variable z will be assigned false because the value of
x is neither greater than nor equal to the value of y.

Logical Operators
Logical operators evaluate expressions that carry boolean values. As with other operators, most
logical operators make use of two operands. The result returned by logical operators is also a
boolean value. There are three logical operators used in Java.

Lesson 1: Programming in Java 33


LESSON 1
Logical
Operator Description
! Meaning: Logical Negation
Result: Inverts a boolean.
Example: boolean y = true;
y = !y;
The variable y will be assigned false.
&& Meaning: Conditional AND
Result: Performs as an AND without evaluating the right operand, if the left operand is
false.
Example 1: boolean x = true;
boolean y = false;
boolean z = x && y;
The variable z will be assigned false.
Example 2: boolean x = true;
boolean y = true;
boolean z = x && y;
The variable z will be assigned true.
|| Meaning: Conditional OR
Result: Performs as an OR without evaluating the right operand, if the left operand is
true.
Example: boolean x = true;
boolean y = false;
boolean z = x || y;
The variable z will be assigned true.

Increment and Decrement Operators


The increment operator allows you to increase the value of a numeric variable or array ele-
ment by 1, while the decrement operator allows you to reduce the value of a numeric variable
or array element by 1. The increment and decrement operators help you to reduce the length of
statements and simplify code. The increment operator is represented by two plus signs (++),
while the decrement operator is represented by two minus signs (--). The operators can be
used either before the operand, in the prex position, or after the operand, in the postx posi-
tion.

Prex and Postx


The placement of an increment or decrement operator determines when the operation is per-
formed.

Operator
Position Description
Prex Placing the operator before the operand causes the increment or decrement to occur
before the value of the operand is used to evaluate an expression.
For example: int a=5;
int x = ++a; In this code, both x and a will have the value 6.

34 Java Fundamentals (Java SE 7)


LESSON 1
Operator
Position Description
Postx Placing the operator after the operand causes the increment or decrement operation to
occur after the value of the operand is used in an expression.
For example: int a=5;
int x = a++; In this code, x will have the value of 5 and a will have the value 6.

Operator Precedence
Denition: Operator Precedence
Operator precedence is the order in which operators are evaluated within expressions.
It usually determines the resulting value of an expression used in a program. Operators
with the same precedence are calculated in the order in which they appear in a state-
ment, from left to right. You can alter the order in which operators are evaluated by
placing the expressions to be evaluated rst in parentheses.

Order of Operator Precedence


The order of operator precedence in Java is listed in the following table.

Precedence Operators
1 . [...] (...)
2 ++ -- ! ~ instanceof
3 * / %
4 + -
5 << >> >>>
6 < > <= >=
7 == !=
8 &
9 ^
10 |
11 &&
12 ||

When in doubt, add parentheses. This will make your code more readable and robust.

Lesson 1: Programming in Java 35


LESSON 1
Example: Operator Precedence

Figure 1-16: Precedence of operators in Java.

How to Write an Expression


Procedure Reference: Write an Expression
To write an expression:
1. In the source code, state the variable name.
2. Enter the equals ( = ) sign followed by a variable name.
3. Insert an operator.
4. If necessary, follow the operator with the second variable name.

The symbol indicates the code must be entered on the same code line.

36 Java Fundamentals (Java SE 7)


LESSON 1
ACTIVITY 1-4
Writing Expressions for the Kiosk Application
Data Files:
Kiosk_1D.jar

Before You Begin:


Import the C:\085664Data\Programming in Java\Kiosk_1D.jar project into the Eclipse IDE.

Scenario:
Two more departments, Plumbing and Garden, were added to the kiosk application. Your col-
league, who added these departments, did not modify the source code to increment the number
of departments. Your manager asks you to add this functionality and verify that the Paint
department and the Lumber department are not the same. In addition, he wants to modify the
output so that a blank line appears after the welcome statement and a description text appears
along with the number of departments.

Lesson 1: Programming in Java 37


LESSON 1
What You Do How You Do It

1. Modify the code to increase the num- a. Display the source code of the Kiosk_
ber of departments and add 1D.java file.
necessary comments.
b. After the statement initializing the
gardenDept object, insert three blank
lines.

c. To enter the name of the variable that


will store the result of the expression,
type totalDepartments

d. To insert the equals operator, type =

e. To state the first operand as total depart-


ments, type totalDepartments

f. To increase the number of departments by


2, type +2;

g. To describe the code, above the expres-


sion, type the comment // Increase
number of departments by 2

See Code Sample 1.

Code Sample 1
DepartmentType plumbingDept = new DepartmentType();
plumbingDept.setName("Plumbing");

DepartmentType gardenDept = new DepartmentType();


gardenDept.setName("Garden");

// Increase number of departments by 2


totalDepartments=totalDepartments+2;

38 Java Fundamentals (Java SE 7)


LESSON 1
2. Write an expression to compare a. After the statement that prints the name
whether the Paint department is not of the Garden department, insert three
the Lumber department and com- new lines.
ment your code.
b. Add code for a system output statement
to print contents in a new line.

c. To specify the name of the first depart-


ment for comparison, in the output
statement, within the parentheses, type
paintDept

d. To enter the relational operator for com-


parison, type ==

e. To specify the other department with


which to compare, type lumberDept

f. Above the expression, write the comment


// Prints false when two
departments are not same to
document the purpose of the code.

See Code Sample 2.

Code Sample 2
System.out.println(paintDept.getName());
System.out.println(lumberDept.getName());
System.out.println(electricalDept.getName());
System.out.println(plumbingDept.getName());
System.out.println(gardenDept.getName());

// Prints false when two departments are not same


System.out.println(paintDept==lumberDept);

Lesson 1: Programming in Java 39


LESSON 1
3. Include statements to modify the a. In the statement that prints the welcome
output. message, click after the constant variable
name WELCOME.

b. To add code to enter a blank line in the


output after the welcome message, type
+"\n"

c. In the statement that prints the number


of departments, click before the variable
name totalDepartments.

d. To add text to describe the value, type


"Our store features " +

e. To complete the description, click after


the variable name and type + "
departments"

See Code Sample 3.

Code Sample 3
// Prints false when two departments are not same
System.out.println(paintDept==lumberDept);

// Prints the number of departments


System.out.println("Our store features " +totalDepartments + " departments");

4. Save and run the program to verify a. Save the file and execute the program.
the program output.
b. In the Console view, verify that the value
false appears after the department
names to indicate that the Paint depart-
ment and Lumber department are not the
same. Also, verify that the last line dis-
plays the updated message conveying the
number of departments.

c. Close the project.

40 Java Fundamentals (Java SE 7)


LESSON 1
TOPIC E
Work with Arrays
In the previous topic, you created expressions to work with data. Another way you can manage
data in Java is through the use of data structures called arrays, which hold data elements of the
same data type. In this topic, you will create and access arrays.
By using arrays, you can streamline code and create fewer individual variables. More impor-
tantly, you can treat related data elements as a list and perform list-oriented operations on an
array.

Arrays
Denition: Arrays
An array is a Java code element that:
Stores a list of items of the same primitive data type or class in numbered slots.
Accesses items using their index numbers, also known as the subscript.
Has a xed length, or a number of elements, that is dened when the array is
declared.
Can be declared and initialized in a single statement or separately in two state-
ments.
Has array items automatically initialized to a default value based on the data type
of the array, if it was not initialized during declaration. The default values are:
false for the boolean data type
0 for the numeric data type
null for the reference type

Syntax: Array Declaration


Arrays can be declared using two types of syntax structures:
ArrayType[] variableName;
or
ArrayType variableName [];
You can also use two types of syntax to initialize arrays during declaration:
ArrayType[] variableName = new ArrayType [array values];
or
ArrayType[] variableName = {array values};
For example, the code int[] arrayName1 = {1,2}; is initializing an array
called arrayName1 that stores integer values.
Because string objects can be created and initialized without the new operator, you can
also initialize strings directly when declaring an array of strings.

Lesson 1: Programming in Java 41


LESSON 1
Example:

Figure 1-17: Create and initialize arrays.

Array Reference
When assigning data to an array item, you are actually creating a reference to an
object. If you move that value within the array, the reference is reassigned.

Determining the Length of an Array


Java provides the length attribute for arrays that allows you to retrieve the length of
an array. You need to use the standard dot notation to access this attribute; for
example, arrayName.length

Multi-dimensional Arrays
Multi-dimensional Arrays Denition:
A multi-dimensional array is a Java code element that:
Comprises a collection of arrays.
Contains arrays that need not have the same length.
Is used to represent tables or data in a matrix format.

Syntax: Multi-dimensional Arrays


Multi-dimensional arrays can be declared in the same way as single dimensional
arrays. They use two types of syntax:
ArrayType[][] variableName;
or
ArrayType variableName [][];
Multi-dimensional arrays can be created and initialized simultaneously. The syntax is
as follows:
ArrayType[][] arrayName = new ArrayType[value1][value2];

42 Java Fundamentals (Java SE 7)


LESSON 1
Example:

Figure 1-18: Multi-dimensional array creation and initialization.

Array Data Access


You can access the items stored in an array using their index value. The rst element of an
array is assigned an index value of 0. Therefore, an array with ve items would have index
values of 0 to 4. You use an arrays subscript to access individual data elements in an array.
By accessing array items, you can retrieve, modify, and update the values stored in an array.

Accessing Arrays
You access multi-dimensional arrays in the same fashion as single arrays. Array access
uses the following syntax for single-dimensional arrays:
arrayname[index value];
For example, the code Math marks = StudentMarks[0]; assigns the value at
the 0th index of the array to the variable marks. For multi-dimensional arrays, the
code is Math marks = StudentMarks[0][1];

ArrayOutOfBoundsException
The array subscript is checked each time it is used to ensure that the accessed data is
actually located in the boundaries of the array. If you attempt to access an element in
an array, and your access statement requests an index that is outside the boundaries of
the array, the Java Virtual Machine generates a runtime error identied as an
ArrayOutOfBoundsException. To avoid this exception, many programmers use
the length attribute, which provides the number of elements within an array.

How to Work with Arrays


Procedure Reference: Create and Initialize an Array
To create and initialize an array:
1. In the program code, using the array declaration syntax, declare a variable to hold
an array.
2. Create an array object using the new keyword and the array type.
3. Assign values to initialize the array.

Lesson 1: Programming in Java 43


LESSON 1
Procedure Reference: Access Array Data
To access array data:
1. In the program code, state the array name being accessed.
2. State the array index value for the desired item being accessed.
3. If necessary, store the returned value in a variable.

ACTIVITY 1-5
Creating and Initializing Arrays
Data Files:
Kiosk_1E.jar

Before You Begin:


Import the C:\085664Data\Programming in Java\Kiosk_1E.jar project into the Eclipse IDE.

Scenario:
Your manager tells you that the kiosk will include all of the store departments when it is rolled
out nationwide. You review your code and notice that you have entered variables at separate
times for the different department names, and realize that you would need to make hundreds of
separate variables and increment statements for all store departments. To streamline your code,
you decide to create an array for the department names and use it to determine the total num-
ber of departments.

44 Java Fundamentals (Java SE 7)


LESSON 1
What You Do How You Do It

1. Open the source code and delete all a. Display the source code of the Kiosk_
statements referring to the 1E.java file.
totalDepartments variable and
department names.
b. Delete the statements declaring the
totalDepartments variable and its
associated comments.

See Code Sample 1.

c. Delete the statements that increment the


value of the totalDepartments variable
and its associated comments.

See Code Sample 2.

Code Sample 1
public static void main(String[] args) {

// Declare and initialize an integer variable


int totalDepartments=3;

// Declare a string constant for welcome message


final String WELCOME="Welcome to OGC Home Improvement";
Code Sample 2
DepartmentType gardenDept=new DepartmentType();
gardenDept.setName("Garden");

// increase number of departments by 2


totalDepartments=totalDepartments+2;

Lesson 1: Programming in Java 45


LESSON 1
2. Create and initialize an array for the a. To state the array type to hold the
department names. department names as String, click after
the open brace of the main method,
insert a line and type String[]

b. To define the variable name of the array,


insert a space and type
departmentNames

c. After the array name, insert an equals


sign.

d. To specify the values to initialize the


array, type {"Paint", "Lumber",
"Electrical", "Plumbing",
"Garden"};

e. Above the array, insert a comment to


document the purpose of the code.

See Code Sample 3.

Code Sample 3
// Initialize string array with department names
String[] departmentNames={"Paint", "Lumber", "Electrical", "Plumbing", "Garden"};

3. Modify the code to print the number a. In the system output statement that prints
of departments in the store. the number of departments, double-click
to select the totalDepartments vari-
able.

b. Type departmentNames.

See Code Sample 4.

c. From the displayed list, double-click to


select the length : int - String [] option.

Code Sample 4
// Displays welcome message and department names
System.out.println(WELCOME + "\n");
System.out.println("Our store features " + departmentNames. + " departments.");

4. Save and run the program to verify a. Save the file and execute the program.
the output.
b. Verify the output of the program.

46 Java Fundamentals (Java SE 7)


LESSON 1
ACTIVITY 1-6
Accessing Data from Arrays
Before You Begin:
The Kiosk_1E.jar project is open in the Eclipse IDE.

Scenario:
After reviewing your code changes, your manager is pleased with the increased efficiency and
ease with which the code can be updated. With the arrays exchanged for separate variables,
your manager wants the department names to be listed in conjunction with the number for the
departments to inform users of which number to enter to select a department.

Lesson 1: Programming in Java 47


LESSON 1
What You Do How You Do It

1. Create an array for the total number a. Delete the statements used to declare and
of departments and comment your initialize instances of the
code. DepartmentType class.

See Code Sample 1.

b. To state the array type to hold the total


departments array, type
DepartmentType[]

c. To define the name of the array, enter a


space and type departments;

d. Above the statement declaring the array,


modify the comment to Declare an
array of departments

See Code Sample 2.

Code Sample 1
// Declare a string constant for welcome message
final String WELCOME="Welcome to OGC Home Improvement";

// Create instances of DepartmentType class


DepartmentType paintDept=new DepartmentType();
paintDept.setName("Paint");

DepartmentType lumberDept=new DepartmentType();


lumberDept.setName("Lumber");

DepartmentType electricalDept=new DepartmentType();


electricalDept.setName("Electrical");

DepartmentType plumbingDept=new DepartmentType();


plumbingDept.setName("Plumbing");

DepartmentType gardenDept=new DepartmentType();


gardenDept.setName("Electrical");
Code Sample 2
// Initialize string array with department names
String[] departmentNames{"Paint","Lumber","Electrical","Plumbing","Garden"};

// Create instances of DepartmentType class


Declare an array of departments
DepartmentType[] departments;

48 Java Fundamentals (Java SE 7)


LESSON 1
2. Initialize the array to store the a. In the statement where the array is
names of departments. declared, place the cursor before the
semicolon and insert an equals sign.

b. After the equals sign, insert a space and


type the new keyword.

c. To state the array needs to store five val-


ues, enter a space and type
DepartmentType[5]

See Code Sample 3.

Code Sample 3
// Declare an array of departments
DepartmentType[] departments = new DepartmentType[5];

Lesson 1: Programming in Java 49


LESSON 1
3. Include statements to initialize the a. After the array declarations, insert two
departments array to store the lines, insert the comment //
names of departments. Initialize array elements

b. To state that the first element of the


array to be created, insert a new line and
type departments[0]= new
DepartmentType();

See Code Sample 4.

c. To initialize the first value of the array to


Paint, insert a new line and type
departments[0].setName(departmentNames[0]);

See Code Sample 5.

d. Similarly, create and initialize other ele-


ments of array to store values for
Lumber, Electrical, Plumbing, and
Garden departments.

See Code Sample 6.

Code Sample 4
DepartmentType[] departments = new DepartmentType[5];

departments[0] = new DepartmentType();

Code Sample 5
DepartmentType[] departments = new DepartmentType[5];

departments[0] = new DepartmentType();


departments[0].setName(departmentNames[0]);
Code Sample 6
DepartmentType[] departments = new DepartmentType[5];

departments[0] = new DepartmentType();


departments[0].setName(departmentNames[0]);

departments[1] = new DepartmentType();


departments[1].setName(departmentNames[1]);

departments[2] = new DepartmentType();


departments[2].setName(departmentNames[2]);

departments[3] = new DepartmentType();


departments[3].setName(departmentNames[3]);

departments[4] = new DepartmentType();


departments[4].setName(departmentNames[4]);

50 Java Fundamentals (Java SE 7)


LESSON 1
4. Modify the system output statement a. In the system output statement that prints
to print department names from the the Paint department name, double-click
array. to select the paintDept object name.

b. To update the array name, type


departments[0]

c. Similarly, update the print output state-


ments to print the name of other
departments from the departments
array.

See Code Sample 7.

Code Sample 7
System.out.println("Our store features " +
departments.length + " departments:");
System.out.println(departments[0].getName());
System.out.println(lumberDept
departments[1].getName());
System.out.println(ElectricalDept
departments[2].getName());
System.out.println(PlumbingDept
departments[3].getName());
System.out.println(GardenDept
departments[4].getName());

5. Update the variable that displays the a. In the output statement for the number of
number of departments. departments, double-click to select the
departmentNames variable.

b. To enter the array name, type


departments

6. Save and run the program to verify a. Save the file and execute the program.
the output.
b. Verify the output of the program. Then,
close the project.

Lesson 1: Programming in Java 51


LESSON 1
Lesson 1 Follow-up
In this lesson, you created, compiled, and executed a simple Java application using basic code
components such as expressions, objects, variables, methods, and arrays. This fundamental
knowledge will serve as the foundation upon which you build the knowledge to create func-
tional and efficient Java applications.
1. Will you use an IDE to develop programs in Java? Why?
Answers will vary, but reasons to use an IDE may include the fact that it provides a user-
friendly interface to code and compile programs easily, IDEs provide plug-ins that enable
developers to write code for developing a particular type of application, and IDEs enable
developers to easily integrate different components of an application which are devel-
oped in various stages.
2. How would you use different types of comments in your code when you are developing
a program?
Answers will vary, but may include using a single line comment when describing the spe-
cific purpose of a single line or block of code or describing the purpose of a variable,
using multiline code when describing in detail the purpose of a class, and using computer-
readable javadoc code when explaining a class or method for documentation purposes.

52 Java Fundamentals (Java SE 7)


LESSON 2

LESSON 2 Lesson Time


4 hour(s), 30 minutes

Controlling Program Flow


In this lesson, you will control program ow by writing code to respond to specic situations
and produce appropriate results.
You will:
Write if statements.
Write a switch statement.
Write for loops.
Write while and do...while loops.

Lesson 2: Controlling Program Flow 53


LESSON 2
Introduction
In the previous lesson, you created simple programs in Java. In order for you to write pro-
grams which involve complex logic, you would need the help of statements that control the
ow of the program. In this lesson, you will control the ow of your program.
In real-life situations, computer programs accept input from users and process it to produce a
result. The input data may need to be processed in various ways based on data entered, busi-
ness requirements, logical analysis of data, or technical validity of the input. The Java
programming language provides several options to dene how programs can process data so
that you can incorporate features such as decision making and interaction in your programs.

TOPIC A
Write If Statements
In this lesson, you will use various methods to control program ow. Perhaps the simplest and
most common ow-control situation is when a program contains a set of code that will be
executed only if a specic condition is satised. In this topic, you will write if statements.
Suppose you develop a program that prints the names of all employees aged over 50, to
inform them about a new retirement plan. To ensure that the program prints the correct infor-
mation, you need to include code to check to see if the age of each employee meets the
required criteria. An if statement enables you to check for such conditions and process data
based on the result of the condition.

The If Statement
The If Statement Denition:
An if statement is a type of Java ow control statement that:
Uses a single selection to determine a course of action.
Is declared with the if keyword.
Contains a boolean test expression within parentheses.
Can include multiple action statements within braces.

Syntax: If Statement
When writing ow control statements, the second line of code is often indented. This
is optional, but a recommended practice for structuring the code for readability. The
if statements use the following syntax:
if (test expression) {
//...action statements
}

54 Java Fundamentals (Java SE 7)


LESSON 2
Example:

Figure 2-1: An if statement.

Control Flow Through If Statements


The ow of program moves through the if statement based on the test expression. When the Control Flow Through If
test expression returns true, the action statements contained in the if block are executed and Statements
then the control passes to the code following the if block. When the test expression returns
false, the ow of program bypasses the if block and executes the code following the if
block.

Figure 2-2: Control flow through an if statement.

The If...Else Statement


Denition: The If...Else Statement
An ifelse statement is a type of Java ow control statement that:
Uses a double selection to choose between two alternative courses of action.
Is formed by using the if and else keywords.
Contains a boolean test expression within parentheses.
Can have multiple action statements for each selection within braces.

Syntax: If... Else Statement


If...else statements use the following syntax:

Lesson 2: Controlling Program Flow 55


LESSON 2
if (test expression) {
//..action statements
} else {
//..action statements
}

Example:

Figure 2-3: An if...else statement.

Control Flow Through If...Else Statements


Control Flow Through If...Else
The programs control moves through the if..else statement based upon the test expres-
Statements sion. When the test expression returns true, the action statements in the if block are executed,
the code in the else block is bypassed, and then the control passes to the code following the
else block. Conversely, when the test expression returns false, the control bypasses the if
block, executes the action statements in the else block and then the control passes to the
code following the else block.

Figure 2-4: Control flow through an if...else statement.

Nested If Statements
Nested If Statements Denition:
A nested if statement is a type of if statement that:

56 Java Fundamentals (Java SE 7)


LESSON 2
Is placed inside the if block of another if statement.
Is declared in the same fashion as other if statements: with the if keyword, a
test expression, and action statements.
Contains action statements which are nested within the if block of the outer if
statement.

Syntax: Nested If Statement


Nested if statements have the following syntax:
if (test expression) {
//..action statements
if (test expression) {
//..action statements
}
}

Example:

Figure 2-5: A nested if statement.

Nesting Multiple If Statements


You can nest as many if statements as necessary to create complex decision-making
programs. Nested if statements reect how one choice may affect the decision-making
process. Nesting if statements can supplement other ow control statements to
develop efficient decision-making programs.

Syntax: Nested If...Else Statement


Nested if...else statements contain action statements which are nested within the
else block of the outer if statement. Nested if...else statements have the fol-
lowing syntax:
if (test expression) {
//..action statements
} else {
if (test expression) {
//..action statements
} else {
//..action statements
}
}

Lesson 2: Controlling Program Flow 57


LESSON 2
Control Flow Through Nested If Statements
Control Flow Through Nested
In nested if statements, the control ows through the outer if statement based on the test
If Statements expression. When the test expression returns true, the control ow moves to the nested if
statement. When the test expression of the nested if statement returns true, the action state-
ments contained in the nested if block are executed and then the control passes to the code
following the nested if block. If the test expression of the nested if statement returns false,
the ow of program bypasses the nested if block and executes the code following the nested
if block but within the outer if block.

Figure 2-6: Flow of control through a nested if statement.

How to Write If Statements


Procedure Reference: Write If Statements
To write if statements:
1. In the code, insert the if keyword.
2. State the test expression within parentheses.

You can check for multiple conditions in the test expression by using appropriate relational and
logical operators.

3. In the body of the if statement, insert the action statements.


4. If necessary, insert the else keyword and corresponding action statements.

58 Java Fundamentals (Java SE 7)


LESSON 2
ACTIVITY 2-1
Creating Conditional Output Statements for the Kiosk
Application
Data Files:
Kiosk_2A.jar

Before You Begin:


Import the C:\085664Data\Controlling Program Flow\Kiosk_2A.jar project into the Eclipse
IDE.

Scenario:
Now that you have all the departments of the store coded into your application, your manager
wants you to create functionality for the kiosk application that will print the names of all
departments. Your manager also wants you to add a help function that tells users to select a
number for a corresponding department. Finally, he wants the kiosk application to output an
error message if a user inputs a number that does not correspond to any department.

What You Do How You Do It

1. Display a message to prompt the user a. Display the source code of the Kiosk_
to enter an input. 2A.java file.

b. After the last system output statement


that prints the name of the Garden
department, insert two new lines.

c. To display a message, type System.out.

d. From the displayed list, select


print(String arg0) : void - PrintStream.

e. To prompt the user to input a value, type


"\nEnter a department number :
"

f. Terminate the statement with a semico-


lon.

Lesson 2: Controlling Program Flow 59


LESSON 2
2. Create and initialize a variable to a. Insert two new lines and declare c as an
represent user input. integer type variable.

b. To initialize the variable to the user input


value, type =System.in.read();

See Code Sample 1.

c. The number that will be entered by the


user will be stored in the variable c in
ASCII format and converted. Above the
variable, write a comment to document
the purpose of the code.

See Code Sample 2.

Code Sample 1
System.out.print("\nEnter a department number: ");
int c=System.in.read();

Code Sample 2
System.out.print("\nEnter a department number : ");

// Read a character from the keyboard


int c=System.in.read();

60 Java Fundamentals (Java SE 7)


LESSON 2
3. Define the control flow statement. a. After the statement that reads system
input, insert two new lines and type
if ()

b. To check to see if the keyboard input


stored in the variable c is between 1 and
5, within parentheses, type (c>='1')
&& (c<='5')

c. After the close parenthesis, insert a


space, an open brace for writing the code
for the method body, and then press
Enter.

d. Notice that the closing brace for the if


statement code block is automatically
entered. Enter a system output state-
ment.

e. From the displayed list, double-click


println(String arg0) : void - PrintStream

f. Within parentheses, type "You


selected "
+departments[c-'1'].getName()

g. Terminate the statement using a semico-


lon.

h. Above the output statement, write a com-


ment to document the purpose of the
code.

See Code Sample 3.

Code Sample 3
// Read a character from the keyboard
int c=System.in.read();

if ((c>='1') && (c<='5')) {


// Show the name of the selected department
System.out.println("You selected " +departments[c-'1'].getName());

4. Insert the else statement block. a. After the if statement code blocks clos-
ing brace, type else {

b. To specify the else statements code


block, insert a new line.

Lesson 2: Controlling Program Flow 61


LESSON 2
5. Insert the if code block of the a. To specify a condition for the nested if
nested if...else statement. statement, type if ()

b. To insert a test expression to check to see


if ? is the user input, within parentheses,
type c=='?'

c. Insert the opening and closing braces for


the nested if statement.

d. To print text in a new line, type


System.out.

e. From the displayed list, select


println(String arg0) : void - PrintStream.

f. Within parentheses, type "To select


a department, type its number
and then press Enter"

See Code Sample 4.

g. Terminate the statement using a semico-


lon.

Code Sample 4
if (c=='?') {
System.out.println("To select a department, type its number and then
press Enter");
}

62 Java Fundamentals (Java SE 7)


LESSON 2
6. Insert the else code block of the a. After the closing brace for the
nested if...else statement. else...if statement, insert a space,
type else { and press Enter.

b. Enter a system output statement to print


text in a new line.

c. Within parentheses, type "Invalid


department number"

d. Terminate the statement using a semico-


lon.

e. Above the output statements, write a


comment to document the purpose of the
code.

See Code Sample 5.

Code Sample 5
} else {
if (c==?) {
// Show help and invalid input messages
System.out.println("To select a department, type its number, and
then press Enter");
} else {
System.out.println("Invalid department number");
}
}

7. Save and run the program to verify a. Save the file and execute the program.
the output.
b. Verify the output of the program.

c. The program displays the menu and waits


for user input. At the prompt, type 1 and
press Enter.

d. Notice that the program displays the mes-


sage with the department name.

Lesson 2: Controlling Program Flow 63


LESSON 2
8. Provide different inputs to check the a. Execute the program again.
program.
b. At the prompt, type ?

c. Notice that the program displays the help


message.

d. Execute the program again.

e. At the prompt, type 9

f. Notice that the program displays the


Invalid department number message.

g. Close the project.

TOPIC B
Write a Switch Statement
In the previous topic, you used if...else statements to select between two alternative
courses of action based on a test expression. Sometimes your programs may need to incorpo-
rate decision-making code that chooses an appropriate course of action from among multiple
actions based on a test expression. In this topic, you will write switch statements.
Suppose you are creating a program which requires users to enter a product, and based on the
input, prints the details of the product. If you use an if statement, then the code becomes
lengthy and cumbersome to maintain. By using switch statements, you can quickly create
decision-making code that will be easy to maintain.

Switch Statements
Switch Statements Denition:
A switch statement is a type of Java ow control statement that:
Is used to create a multiple selection structure.
Transfers control ow to a specic block of code based on the value of the test
expression, which can be a variable or an expression.
Is declared with the switch keyword.
Has multiple case statement blocks, which are declared with the case keyword,
and lists a set of actions for a specic value.
Checks the test expression with the constant value of each of the dened cases
and transfers the control ow to the case block that matches the value of the test
expression.

64 Java Fundamentals (Java SE 7)


LESSON 2
Includes a default block, which is declared with the default keyword, to
execute the default action when the test expression does not match any of the
cases.
Includes a break statement at the end of each case block to transfer the con-
trol ow to the statement following the switch statement block.

Syntax: Switch Statement


A switch statement uses the following syntax:
switch (expression) {
case caseExpression1:
//..action statements
break;
case caseExpression2:
//..action statements
break;
case caseExpression3:
//..action statements
break;
default:
//..action statements
}

Example:

Figure 2-7: A switch statement.

Data Types Supported by Switch Statements


Switch statements work with all primitive data types such as byte, short, char, and
int data types. It also works with enumerated types, the String class, and some spe-
cial classes such as Character, Byte, Short, and Integer, that wrap primitive data types.

The Break Statement


A break is a Java code statement that:
Is declared with the break keyword.

Lesson 2: Controlling Program Flow 65


LESSON 2
Halts the execution of code and passes the control to the statement that immediately fol-
lows the control ow code block in which the break statement is used.

In a switch statement, at the end of a case code block, if there is no break statement, then the control ows
to the following case or default code block.

Executing a Statement Block for Multiple Cases


If the same set of statements needs to be executed for a set of case blocks, you can
dene the set of statements at the end of the last case block of that set. Remember to
include the break statement only at the end of the last case statement of that set.
switch (expression) {
case caseExpression1:
case caseExpression2:
case caseExpression3:
//..action statements
break;
case caseExpression4:
//..action statements
break;
default:
//..action statements
}

Control Flow Through Switch Statements


Control Flow Through Switch
A switch statements ow begins with the test expression evaluating cases. The rst case
Statements that returns a true value performs its action statements and passes to a break statement. Then,
ow exits the switch statement. Otherwise, a returned false value moves the test expression
to the next case. If no case returns true, control passes to the default statement, performing
its actions and passing control out of the switch.

Figure 2-8: Flow of control through a switch statement.

66 Java Fundamentals (Java SE 7)


LESSON 2
Switch Statement with Enum
You can use a switch statement to create a multiple selection structure, based on the enumer- Switch Statement with Enum
ated data type. It begins with the test expression that evaluates and transfers control ow to the
appropriate case. After executing the case statements, the control exits the switch state-
ment. If no case returns true, control passes to the default statement, performing its
actions and then passing the control out of the switch statement.

Figure 2-9: A switch statement with enum.

How to Write a Switch Statement


Procedure Reference: Write a Switch Statement
To write a switch statement:
1. In the source code, insert the switch keyword.
2. Specify the test expression within parentheses.
3. In the body of the switch statement, declare cases using the case keyword and
specify the corresponding values for each case followed by a colon.
4. After each case, write a statement or statements to be performed when the case is
true.
5. At the end of each case statement, include a break statement with the break
keyword.
6. In the body of the switch, after all cases are included, insert the default state-
ment using the default keyword followed by a colon.
7. After the default, write the default statement to be performed when no case is
true.

Lesson 2: Controlling Program Flow 67


LESSON 2
ACTIVITY 2-2
Creating a Switch Statement for the Kiosk Application
Data Files:
Kiosk_2B.jar

Before You Begin:


Import the C:\085664Data\Controlling Program Flow\Kiosk_2B.jar project into the Eclipse
IDE.

Scenario:
Your manager is happy with the new features used in the kiosk application. However, you
know that you can increase your code efficiency by replacing the nested if...else state-
ment with a switch statement to accomplish the programming requirements.

What You Do How You Do It

1. Open the source code and delete the a. Display the source code of the Kiosk_
code for the if...else statement. 2B.java file.

b. Delete the code for the if...else state-


ments that output department names,
help, and invalid input messages.

See Code Sample 1.

Code Sample 1
System.out.print("\nEnter a department number : ");
// Read a character from the keyboard
int c=System.in.read();

if ((c>='1') && (c<='5')) {


// Show the name of the selected department
System.out.println("You selected "+departments[c-'1'].getName());
} else {
// Show help and invalid input message
if (c=='?') {
System.out.println("To select a department, type its number and
then press Enter");
} else {
System.out.println("Invalid department number");
}
}

68 Java Fundamentals (Java SE 7)


LESSON 2
2. Write a switch statement to output a. To enter the switch statement, type
department names. switch

b. To specify that the user input in the vari-


able c be used as the value to switch,
insert a space and type (c)

c. To define the code block for the switch


statement, insert a space, enter an open
brace, and press Enter.

d. To define the case block for the first


department, in the body of the switch
code block, type case '1':

e. To define the case block for the second


department, in the body of the switch
code block, insert a new line and type
case '2':

f. Similarly, define the case block for values


of other departments.

See Code Sample 2.

g. To specify the message that will be dis-


played when that case is true, in a new
line, type System.out.println("You
selected the "+
departments[c-'1'].getName()+ "
department");

h. To break out of the switch statement, in


the next line, type break;

Code Sample 2
switch (c) {
case '1':
case '2':
case '3':
case '4':
case '5':

Lesson 2: Controlling Program Flow 69


LESSON 2
3. Write a switch statement to output a. To write a case for the help statement,
help information. create a new line after the last break
statement and type case '?':

b. In the next line, insert a system output


statement to print text in a new line.

c. Within parentheses, specify the help mes-


sage in quotes "To select a
department, type its number and
then press Enter"

d. To break out of the switch statement, in


the next line, type break;

e. To document the purpose of the code,


above the system output statement for
the help message, insert the comment
// Display help information

See Code Sample 3.

Code Sample 3
case '?':
// Display help information
System.out.println("To select a department, type its number and
then press Enter");
break;

70 Java Fundamentals (Java SE 7)


LESSON 2
4. Write a default statement to display a. To write the default statement, after the
the error message. last break statement, type default:

Notice that the default statement may not be


indented correctly and you may need to manu-
ally indent it.

b. In a new line, insert a system output


statement to print text in a new line.

c. Within parentheses, type the error mes-


sage "Invalid department number"

d. To document the purpose of the code,


above the system output statement for
displaying the error message, insert the
comment // Display error
message for invalid entry

See Code Sample 4.

Code Sample 4
default:
// Display error message for invalid entry
System.out.println("Invalid department number");

5. Save and run the program to verify a. Save the file and execute the program.
the output.
b. To view the program output completely,
expand the Console view.

c. In the Console view, verify the output of


the program. Notice that the program lists
the menu and waits for user input.

d. At the prompt, type 3 and press Enter.

e. Notice that the program displays the mes-


sage You selected the Electrical
department.

Lesson 2: Controlling Program Flow 71


LESSON 2
6. Provide different inputs to check the a. Execute the program again.
program.
b. At the prompt, input the value ?

c. Notice that the program displays the help


message.

d. Execute the program again.

e. At the prompt, input the value 8

f. Notice that the program displays an error


message.

g. Execute the program and input other val-


ues, such as letters and numbers, to check
the program.

h. Close the project.

TOPIC C
Write a For Loop
In the previous topic, you worked with switch statements to make decisions when executing
a program. The next step would be to reuse specic statements which enable you to reduce the
code you write for performing repetitive tasks. In this topic, you will write for loops.
Suppose you need to print the names of employees stored in an array. You need to access each
member of the array and then print it. This would involve a lot of coding and will complicate
the entire code. By using the for loop, you can perform such repetitive tasks by using a
single statement or a statement block.

For Loops
For Loops Denition:
A for loop is a type of Java ow control statement that:
Repeats execution of a single statement or a block of statements until the condi-
tion specied in the test expression is true.
Contains four partsinitialization, boolean test expression, increment or other
action, and action statements.
Is declared with the for keyword.
Contains a variable that is inaccessible outside the loop if it is initialized inside
the for loop.

72 Java Fundamentals (Java SE 7)


LESSON 2
Syntax: For Loop
A best programming practice is to use the for loop for a specic number of iterations.
A semicolon should not be used at the end of the for portion in a loop because it
negates the body of the loop. For loops use the following syntax:
for (initialization; test expression; increment) {
//..action statements
}

Example:

Figure 2-10: A for loop.

Optional Parts of a For Loop


The initialization, test expression, and increment parts of a for loop are optional. You
may include only the test expression, and not the initialization or increment part, to
execute the for loop code block repeatedly until the test condition is true. When you
do not include a boolean test expression in a for loop, the for loop becomes an in-
nite loop. You can use a break statement based on a conditional statement to break
out of innite loops.

Innite Loops
An innite loop is a type of loop, containing a set of statements, that is executed end-
lessly because either the test expression used to check for termination of the loop is
not specied or contains conditions that cannot be met.

Counters in a For Loop


For loops usually use a counter to track the number of times a loop has executed.
Typically, the initialization part of the for loop is used to declare and initialize the
counter. The test expression of the for loop checks whether the counter meets the
specied condition and returns a boolean value. The increment part of the for loop
updates the value of the counter after the body of the loop is executed.

Control Flow Through For Loops


The initialization statement of the for loop is executed upon entering the loop. The initializa- Control Flow Through For
tion statement is used to create and initialize a variable for the counter used in the loop. It is Loops
executed only once when the control ows into the for loop. After the initialization part is
executed, the test expression which includes the counter is checked. If the test expression is
true, the control ows to the body of the for loop and executes the code statements. Finally,
the increment part of the for loop is executed to update the counter and then rechecks the test
expression. If the test expression is true, the loop continues execution; or else the loop termi-
nates and the control ows to the code statement following the for loop.

Lesson 2: Controlling Program Flow 73


LESSON 2

Figure 2-11: Flow of control through a for loop.

Nested For Loops


Nested For Loops Denition:
A nested for loop is a type of for loop that:
Is placed inside the code block of another for loop.
Is declared in the same fashion as other for loops: with the for keyword, ini-
tialization, test expression, increment, and action statements.

Syntax: Nested For Loop


Nested for loops use the following syntax:
for (initialization; test expression; increment) {
//..action statements
for (initialization; test expression; increment) {
//..action statements
}
}

74 Java Fundamentals (Java SE 7)


LESSON 2
Example:

Figure 2-12: A nested for loop.

Break Statement in Nested Loops


If a break statement exists within a single or outer loop, the loop will pass control
directly to the statement immediately following the loop. However, if the break state-
ment is located in a nested or inner loop, control passes to the outer loop, which
continues to run until its test expression is true.

Control Flow Through Nested For Loops


Upon entering the outer loop, the initialization statement of the for loop is executed. After Control Flow Through Nested
the initialization part is executed, the test expression is checked and, if true, the body of the For Loops
loop is executed and the control passes to the initialization statement of the nested for loop.
Then, the test expression is checked and, if true, the body of the nested loop is executed. Next,
the increment part of the nested for loop is executed and the test expression is rechecked. If
the test expression is true, the nested loop continues execution; or else the loop terminates and
the control ows to the body of the outer for loop and then to the increment part of the outer
for loop. Following the increment, the test expression is checked and, if true, the body of the
loop is executed. The control passes to the nested for loop again and continues execution
until the test expression returns false. When the test expression of the outer for loop returns
false, the loop terminates and the control passes to the code statement following the outer loop.

Figure 2-13: Flow of control through a nested for loop.

Lesson 2: Controlling Program Flow 75


LESSON 2
The Continue Statement
A continue statement is a type of Java code statement that is declared with the continue
keyword. It causes a loop to skip any remaining statements within the body of the loop and
transfer the control ow to the test expression. In a for loop, the continue statement bypasses
execution of the rest of the statements in the loop and passes the control to the increment part
of the for statement. After the increment part is executed, the test expression is rechecked,
and if the expression returns true, the body of the for loop is executed.

Syntax: Continue Statement


for (initialization; test expression; increment) {
//..action statements
if (test expression == false) {
continue;
}
}

ForEach Loops
ForEach Loops Denition:
The for...each loop is a type of Java ow control statement that:
Is used to sequentially access individual values in an array.
Is declared with the for keyword.
Contains a special expression inside parentheses after the for keyword.
Provides functionality similar to the for loop, but is easier to use when you need
to access data from an array.
Requires an array name from which values will be accessed and the variable ini-
tialized to store the values.

Syntax: For...Each Loop


A for...each loop uses the following syntax:
for (dataType variableName : arrayName) {
//..action statements
}

Example:

Figure 2-14: A for...each loop.

76 Java Fundamentals (Java SE 7)


LESSON 2
Accessing Other Data Types
You can also use for...each loops to access content from objects, such as collec-
tions, that implement the java.lang.Iterable interface.

Accessing Array Data Using For Each Loops


Initially, the variable is assigned the rst value from the array. Once the action statements
specied in the for loops body are executed, the next value from the array is assigned to the
variable. Similarly, all values from the array are assigned to the variable in sequence and the
body of the loop is executed for each value of the array. After the loops body is executed
with the last value from the array, the control exits the for...each loop.

How to Write a For Loop


Procedure Reference: Write a For Loop
To write a for loop:
1. In the code, insert the for keyword followed by an open parenthesis.
2. Write the initialization statement followed by a semicolon.
3. Write the test expression followed by a semicolon.
4. Write the increment statement and insert a close parenthesis.
5. In the body of the for loop, insert the statements to be executed repeatedly until
the test expression returns true.

Procedure Reference: Write a For...Each Loop


To write a for...each loop:
1. In the code, insert the for keyword followed by parentheses.
2. Inside the parentheses, write the initialization statement including the data type,
the variable name followed by a colon, and the variable representing an array or a
collection.
3. In the body of the for loop, insert the statements to be executed repeatedly when
the test expression returns true.

Lesson 2: Controlling Program Flow 77


LESSON 2
ACTIVITY 2-3
Initializing an Array Using For Loops
Data Files:
Kiosk_2C.jar

Before You Begin:


Import the C:\085664Data\Controlling Program Flow\Kiosk_2C.jar project into the Eclipse
IDE.

Scenario:
After reviewing the increased functionality of your kiosk program, your manager is pleased
with the progress of the project. You review your code and see that you can access your
department name arrays more efficiently with for loops. To streamline your code, you decide
to write a for loop to initialize the department array with the department names.

What You Do How You Do It

1. Open the source code file and delete a. Display the source code of the Kiosk_
the code that is used to initialize 2C.java file.
array elements to store department
names.
b. Delete the statements used to assign
instances of the DepartmentType class
to each element of the array.

See Code Sample 1.

Do not delete the comment above the state-


ments.

Code Sample 1
// Initialize array elements
departments[0]=new DepartmentType();
departments[0].setName(departmentNames[0]);

departments[1]=new DepartmentType();
departments[1].setName(departmentNames[1]);

departments[2]=new DepartmentType();
departments[2].setName(departmentNames[2]);

departments[3]=new DepartmentType();
departments[3].setName(departmentNames[3]);

departments[4]=new DepartmentType();
departments[4].setName(departmentNames[4]);

78 Java Fundamentals (Java SE 7)


LESSON 2
2. Define a for loop. a. Below the comment for assigning depart-
ment names, type for()

b. Within parentheses, write the initializa-


tion statement to initialize the counter
variable i of integer data type to zero.

c. To enter the test expression to check to


see if the counter variable is less than the
length of the departments array, type
i < departments.length;

d. To increase the counter variable by 1, in


the increment part, type i++

See Code Sample 2.

e. To specify the for loop code block, after


the close parenthesis, insert an open
brace and press Enter.

Code Sample 2
// Initialize array elements
for (int i=0;i<departments.length;i++)

3. Assign instances of the a. Initialize each department name in the


DepartmentType class to each ele- array to the DepartmentType class.
ment of the array.
See Code Sample 3.

b. Set all department names to the respec-


tive values from the departmentNames
array.

See Code Sample 4.

Code Sample 3
// Initialize array elements
for (int i=0;i<departments.length;i++) {
departments[i] = new DepartmentType();
}
Code Sample 4
// Initialize array elements
for (int i=0;i<departments.length;i++) {
departments[i] = new DepartmentType();
departments[i].setName(departmentNames[i]);
}

Lesson 2: Controlling Program Flow 79


LESSON 2
4. Save and run the program to verify a. Save the file and execute the program.
the output.
b. Verify that the program displays the
department names correctly.

c. To check the output of the program, at


the prompt, input the value 5

ACTIVITY 2-4
Accessing Array Data Using For...Each Loops
Before You Begin:
The Kiosk_2C.jar project is open in the Eclipse IDE.

Scenario:
In addition to using a for loop to streamline your code, you want to use the for...each
loop to access the items stored in the departments array. This will remove the extra clutter you
have in your code making your program easier to read.

80 Java Fundamentals (Java SE 7)


LESSON 2
What You Do How You Do It

1. Delete the statement used for dis- a. Delete the system output statements used
playing the department names and to print the department names.
initialize a variable for displaying
department numbers. See Code Sample 1.

b. Below the statement that prints the num-


ber of departments, declare an integer
type variable j and initialize it to zero.

See Code Sample 2.

Code Sample 1
System.out.println(WELCOME+"\n");
System.out.println("Our store features "+departments.length+
" departments\n");

System.out.println("1 - " + departments[0].getName());


System.out.println("2 - " + departments[1].getName());
System.out.println("3 - " + departments[2].getName());
System.out.println("4 - " + departments[3].getName());
System.out.println("5 - " + departments[4].getName());

System.out.print("\nEnter a department number : ");


Code Sample 2
System.out.println(WELCOME+"\n");
System.out.println("Our store features "+departments.length+
" departments\n");

int j = 0;

System.out.print("\nEnter a department number : ");

2. Define a for...each loop. a. In a new line, type for()

b. Within parentheses, to define and initial-


ize the iterator to the departments
array, type DepartmentType d :
departments

See Code Sample 3.

c. To specify the code block for the loop,


after the close parenthesis, insert an open
brace and press Enter.

Code Sample 3
int j = 0;
for(DepartmentType d : departments)

Lesson 2: Controlling Program Flow 81


LESSON 2
3. Display the names of each depart- a. Write a system output statement to print
ment from the array. text in a new line.

b. To display the number for each depart-


ment, within parentheses, type ++j +
" - "

c. To specify that the department names


from the array be printed, type
+d.getName()

See Code Sample 4.

Code Sample 4
int j = 0;
for(DepartmentType d : departments) {
System.out.println(++j + " - "+d.getName());
}

4. Save and run the program to verify a. Save the file and execute the program.
the output.
b. Verify that the department names appear
correctly and at the prompt, input the
value 4

c. Verify the message displayed and close


the project.

TOPIC D
Write While and Do...While Loops
In the previous topic, you created for loops to execute one or more statements. Though you
can use for loops for executing repetitive tasks, there are other looping statements which pro-
vide you with similar functionality with few differences in usage. In this topic, you will write
while and do...while loop statements.
While writing certain programs, you may be required to write code to perform repetitive tasks.
The Java programming language provides multiple loop statements to handle this requirement.
By using while and do...while loops, you can minimize the code statements you need to
write to execute effective ow control for your application.

82 Java Fundamentals (Java SE 7)


LESSON 2
The While Loop
Denition: The While Loop
A while loop is a type of Java ow control statement that:
Executes a code block until a specic condition is true.
Is declared with the while keyword.
Includes a boolean test expression contained within parentheses.

Syntax: While Loop


A while loop uses the following syntax:
while (test expression) {
//..action statements
}

Example:

Figure 2-15: A while loop.

Continue Statement in While Loops


In while and do..while loops, the continue statement passes the control ow
to the test expression. However, in while and do..while loops where the incre-
ment statement follows the continue statement, the increment statement does not
execute.

Difference Between While and For Loops


The while loop differs from the for loop because it does not use a counter; only the
condition has to be changed to exit the loop.

Nested While Loops


You may nest while loops in the same manner as a nested for loop. A nested
while loop is a while loop that is placed within another while loops code block.
The nested loop is declared similar to other while loops using the while keyword
and boolean test expression within parentheses.

Lesson 2: Controlling Program Flow 83


LESSON 2
Syntax: Nested While Loop
Nested while loops use the following syntax:
while (test expression) {
//..action statements
while (test expression) {
//..action statements
}
}

Control Flow Through While Loops


Control Flow Through While
The while loop rst checks the test expression. If the boolean test expression returns true, the
Loops statements in the body of the while loop are executed. Then, the ow returns to check the
test expression. Until the test expression returns true, the loops body is executed. When the
test expression returns false, the loop terminates and ow moves to the code following the
loop.

Figure 2-16: Flow of control through a while loop.

Do...While Loops
Do...While Loops Denition:
A do...while loop is a Java ow control statement that:
Is declared with the do and while keywords.
Executes the loops body rst and then checks the test expression.
Continues executing the loops body until the test expression returns true.
Exits the loop if the test expression returns false.

Syntax: Do...While Loop


A do...while loop uses the following syntax:
do {
// action statements
} while (test expression);

84 Java Fundamentals (Java SE 7)


LESSON 2
Example:

Figure 2-17: A do...while loop.

Control Flow Through Do...While Loops


The do..while loop ow begins with the execution of statements in the loops body. Then, Control Flow Through Do...
control ow moves to the test expression. When the test expression returns true, the statements While Loops
in the loops body are executed again. When the test expression returns false, the loop ends
and passes control to the code following the loop. This type of loop ensures that the statements
in the loops body are executed at least once, even if the test condition is false from the start
of the loop.

Figure 2-18: Flow of control through a do...while loop.

How to Write While and Do...While Loops


Procedure Reference: Write While Loops
To write a while loop:
1. In the code, insert the while keyword.
2. Within parentheses, write the test expression.

Lesson 2: Controlling Program Flow 85


LESSON 2
3. In the body of the while loop, insert the statements to be executed when the test
expression returns true, and include a statement to change the loop condition to
make sure the loop exits logically.

Procedure Reference: Write Do...While Loops


To write a do...while loop:
1. In the code, insert the do keyword.
2. In the body of the loop, insert the statements to be performed for the rst time
and when the test expression returns true. Also, include a statement to change the
loop condition to make sure the loop exits logically.
3. Outside the body of the do loop, insert the while keyword.
4. Within parentheses, write the test expression.

ACTIVITY 2-5
Displaying the Menu Continually Using Loops
Data Files:
Kiosk_2D.jar

Before You Begin:


Import the C:\085664Data\Controlling Program Flow\Kiosk_2D.jar project into the Eclipse
IDE.

Scenario:
Your manager is pleased with the development of the kiosk application and informs you that
the marketing department will conduct consumer testing to see how users like the features and
functionality of the program. After doing some sample consumer testing, management has
determined that the kiosk users were not entering the correct options, and could not view the
output. Therefore, the program needs to be modied to display an error message and request
user input until a valid department number is entered.

Students can do this activity


individually or as a group.

86 Java Fundamentals (Java SE 7)


LESSON 2
What You Do How You Do It

1. Open the source code file and define a. Display the source code of the Kiosk_
a variable to check for a loop condi- 2D.java file.
tion.
b. Below the statement that prints depart-
ment names, declare a boolean type
variable isValid and initialize it to
false.

See Code Sample 1.

Code Sample 1
for(DepartmentType d : departments) {
System.out.println(++j + " - " + d.getName());
}

boolean isValid = false;

2. Write a while loop. a. To insert a while loop, in a new line,


type while()

b. To specify a test expression, within paren-


theses, type isValid == false

c. To specify the code block for the loop,


insert an open brace after the close
parenthesis and press Enter.

3. Move the statements that process a. Scroll down to select the statements that
user input into the while loop code process user input.
block.
b. Cut the selected statements.

c. Paste the copied statements in the while


loops code block.

Lesson 2: Controlling Program Flow 87


LESSON 2
4. Update the value of the isValid a. After the system output statement for
variable if the user enters an accept- case 5, insert a statement to reassign
able value. the value of the isValid variable to
true.

b. To reset the system input stream, position


the cursor after the closing brace of the
switch statement block, and insert the
while keyword.

c. To check to see if there are additional


characters in the user input, enter the
test expression
(System.in.available() > 0 )

See Code Sample 2.

d. To specify the code block for the while


loop, after the close parenthesis, insert
an open brace and press Enter.

e. To read out the characters, type


System.in.read();

Code Sample 2
default:
// Display error message for invalid entry
System.out.println("Invalid department number");
}
while(System.in.available() > 0)

5. Save and run the program to verify a. Save the file and execute the program.
the output.
b. Verify that the department names appear
correctly.

c. At the prompt, input the value 4

d. Notice that the program displays the mes-


sage with the department name.

88 Java Fundamentals (Java SE 7)


LESSON 2
6. Provide different inputs to check the a. Execute the program again.
program.
b. At the prompt, input the value 9

c. Notice that the program displays an error


message and asks for input again.

d. At the prompt, input the value ?

e. Notice that the program displays the help


message and asks for input again.

f. To display the message with the depart-


ment name and exit the program, at the
prompt, type 1

ACTIVITY 2-6
Executing Do While Loops
Before You Begin:
The Kiosk_2D.jar project is open.

Scenario:
The kiosk application is working ne, with one exception. Every time a user wants to view the
menu, the program needs to be executed. Management nds this to be unintuitive and suggests
that the menu be displayed to the user until the user exits the program.

Lesson 2: Controlling Program Flow 89


LESSON 2
What You Do How You Do It

1. Define a variable to check for a loop a. Below the statement that initializes
condition. department names, declare a boolean
type variable displayMenu and initialize
it to true.

b. Above the statement, add a comment to


describe the purpose of the variable.

See Code Sample 1.

Code Sample 1
for (int i=0;i<departments.length;i++) {
departments[i]=new DepartmentType();
departments[i].setName(departmentNames[i]);
}

// Variable to display menu until user enters '0'


boolean displayMenu = true;

2. Write a do...while loop to display a. To insert a do...while loop, in a new


the menu until the user presses the line, after the statement that initializes
exit hot key. the displayMenu variable, type do {

b. To specify the end of the loop and check


for the test expression, position the cursor
after the closing brace of the while
statement block, insert a new line, and
type } while();

c. To check to see if the value of the


displayMenu variable is true, within
parentheses, enter the test expression
displayMenu

90 Java Fundamentals (Java SE 7)


LESSON 2
3. Reassign the value of the variable a. After the break statement in the case
displayMenu based on user input. block for help, insert a new line.

b. Enter a case to check to see if the user


entered the exit hot key 0.

See Code Sample 2.

c. Insert a new line and add a statement to


reassign the value of the displayMenu
variable to false.

See Code Sample 3.

d. In the next line, specify that this is a valid


entry by assigning true to the isValid
variable.

e. In the next line, break out of the loop.

See Code Sample 4.

Code Sample 2
case '?':
// Display help information
System.out.println("To select a department, type its number and
press Enter");
break;
case '0':
default:
// Display error message for invalid entry
Code Sample 3
case '0':
displayMenu = false;
default:
Code Sample 4
case '0':
displayMenu = false;
isValid = true;
break;
default:

Lesson 2: Controlling Program Flow 91


LESSON 2
4. Include a help message for the exit a. In the system output statement that prints
hot key. the help message, insert a + operator
after the closing quote of the text.

b. Insert a new line and type "\nPress


'0' to exit"

See Code Sample 5.

Code Sample 5
case '?':
// Display help information
System.out.println("To select a department, type its number and press
Enter"+
"\nPress '0' to exit");
break;

5. Indent the code to ensure better a. Select the do...while code block.
readability.
b. To indent the code, press Tab.

6. Save and run the program to verify a. Save the file and execute the program.
the output.
b. Verify that the department menu is dis-
played.

c. At the prompt, input 2

d. Notice that the program displays the mes-


sage with the department name and the
menu is displayed again.

e. At the prompt, input ?

f. Notice that the program displays the


updated help message and asks for input
again.

g. To test the program, at the prompt, input


other values.

h. At the prompt, input 0

i. Notice that the program terminates.

j. Close the project.

92 Java Fundamentals (Java SE 7)


LESSON 2
Lesson 2 Follow-up
In this lesson, you controlled the ow of your program. Controlling program ow using condi-
tional branching and looping statements enables you to create programs that process data in
various ways so that you can incorporate decision making and interaction features in your pro-
grams.
1. In what situations will you prefer to use switch statements to control program flow?
Answers will vary, but may include situations such as when you need to branch out to one
of several code blocks based on the value, specify a default action when a variable does
not match any of the case values, or streamline code instead of writing multiple
if...else code blocks.
2. How do think you can use the various conditional looping statements provided by Java?
Answers will vary, but may include using for loops when you need to initialize local vari-
ables, check for a condition and execute a block of statements, and change the value of
local variables after the loop is complete; using while statements to run a block of code
until the condition is true; and using do...while statements to execute the loops body
at least once even if the condition is false.

Lesson 2: Controlling Program Flow 93


NOTES

94 Java Fundamentals (Java SE 7)


LESSON 3

LESSON 3 Lesson Time


3 hour(s)

Working with Java Class


Libraries
In this lesson, you will work with Java class libraries to instantiate objects from Java classes.
You will:
Use the Java class library.
Invoke attributes of an object.

Lesson 3: Working with Java Class Libraries 95


LESSON 3
Introduction
In the previous lesson, you controlled the ow of your program which enabled you to create
applications that dynamically process data based on specic criteria. In addition to control ow
statements, Java provides built-in classes that you can use to develop dynamic applications
quickly. In this lesson, you will use Java class libraries.
When creating applications in Java, you may need to add several capabilities in the program.
Instead of coding for each of these capabilities, Java provides libraries that contain pre-
congured capabilities that you can use. These pre-congured capabilities are provided by
classes in Java libraries and you can import these libraries and use the required capabilities in
your application.

TOPIC A
Use the Java Class Library
In this lesson, you will instantiate objects based on Java class libraries to perform various
tasks. Java provides several pre-congured classes which contain predened capabilities that
you can use in your applications. In this topic, you will use a Java class library to perform
specic actions by importing built-in Java classes.
As a developer, you may come across instances where you need to perform mathematical and
text manipulations in your application. Then, you may have to declare and dene the methods
of these operations. Java contains a rich set of libraries which enable you to reuse the code
required for mathematical and string operations.

Constructors
Constructors Denition:
A constructor is a method that:
Is dened in a Java class using the same name as that of the class.
Is invoked when the new keyword is used to instantiate an object and initialize
instance variables or perform tasks at object instantiation.
Does not have a return type in its declaration, because it does not explicitly return
any value, but always implicitly returns an instance of the object when called with
the new keyword.
Can take arguments within parentheses.

Syntax: Constructors
The syntax for dening a constructor:
class ClassName {
ClassName (dataType1 arg1, dataType2 arg2, dataType3 arg3) {
dataType1 x = arg1;
dataType2 y = arg2;
dataType3 z = arg3;
}
}

96 Java Fundamentals (Java SE 7)


LESSON 3
Example:

Figure 3-1: A constructor method.

Java Class Libraries


Java class libraries are groups of predened classes, which are categorized and arranged into
packages, and are called at runtime.
Java comes with hundreds of predened classes that are organized in packages such as java
and javax. These packages contain directories and subdirectories of classes. For example, the
fundamental package, java.lang, contains all the necessary language classes, such as
Object, String, and Thread, that you can use to program Java applications.

Import calls for using other


Packages in the Java Class Library packages contained within the
Java class library are
A package in a Java class library consists of a group of related classes that are organized in a discussed later in the course.
folder hierarchy.

Package Description
java.applet Applet support.
java.awt Abstract Window Toolkit, for developing graphical user interfaces (GUIs).
java.bean JavaBean components.
java.io Java Input/Output, for processing input and output data.
java.lang Java language, containing language specications.
java.net Java networking support.
java.security Java security architecture.
java.util Java utilities, general utility classes.

The Math Class


Denition: The Math Class
The Math class is a Java class that:

Lesson 3: Working with Java Class Libraries 97


LESSON 3
Contains methods and constants used for performing common mathematical calcu-
lations.
Is located in the java.lang package.
Contains constants such as E, which represents the value closest to the base of the
natural logarithms, and PI, represents the value closest to the actual value of pi.

Example:

Figure 3-2: The Math class.

The String Class


The String Class Denition:
The String class is a Java class that:
Is dened in the java.lang package.
Represents an object that is passed by reference to methods.
Is immutable, or cannot be altered after creation.
Has a number of useful built-in methods that help in string manipulations and
operations.

A class isnt passed; it only appears to be passed by value. In reality, it is still an object passed by ref-
erence, but it is immutable; therefore, it behaves as if passed by a value.

Syntax: String
The syntax for String declaration is as follows:
String variable = "value";

Immutability
Java stores the object reference in the variable dened within the String class. If
you declare another value for the same variable at a later point within your code, your
rst variable remains the same.

Example:

Figure 3-3: Objects based on the String class.

98 Java Fundamentals (Java SE 7)


LESSON 3
The StringBuffer Class
Denition: The StringBuffer Class
The StringBuffer class is a Java class that:
Is dened within the java.lang package.
Provides alterable, or mutable, string objects.
May be combined using the Append() method.
Requires the new keyword for creation.

Syntax: StringBuffer
The syntax for the StringBuffer declaration is as follows:
StringBuffer name = new StringBuffer(value);

Example:

Figure 3-4: A StringBuffer class.

How to Use a Java Class Library


Procedure Reference: Create a New Object from a Java Class Library
To create a new object from a Java class library:
1. In the source code, state the name of the Java class that you want to dene.
2. Name the new variable.
3. Instantiate the new object.

Lesson 3: Working with Java Class Libraries 99


LESSON 3
ACTIVITY 3-1
Displaying Text Using a StringBuffer Object
Data Files:
Kiosk_3A.jar

Before You Begin:


Import the C:\085664Data\Working with Java Class Libraries\Kiosk_3A.jar project into the
Eclipse IDE.

Scenario:
A colleague analyzed the code of your application. She suggests that you can enhance its effi-
ciency through object reuse. After reviewing your code, you agree with her assessment. You
decide to use a StringBuffer object for displaying messages on the screen.

Students can do this activity


individually or as a group.

100 Java Fundamentals (Java SE 7)


LESSON 3
What You Do How You Do It

1. Open the source code and delete the a. Display the source code of the Kiosk_
statements that print the message 3A.java file.
based on user input.
b. After the case '5': statement, delete
the system output statement that prints
the name of the selected department.

See Code Sample 1.

c. Delete the system output statement that


prints the help information along with its
comment.

See Code Sample 2.

d. Delete the system output statement that


prints a message when the user provides
an invalid entry.

See Code Sample 3.

Code Sample 1
case '5':
System.out.println("\nYou selected the " + departments[c-'1'].getName()

+ " department");
isValid = true;
break;

Code Sample 2
case '?':
// Display help information
System.out.println("To select a department, type its number and
press Enter"+
"\nPress '0' to exit");
break;
Code Sample 3
default:
// Display error message for invalid entry
System.out.println("Invalid department number");

Lesson 3: Working with Java Class Libraries 101


LESSON 3
2. Declare a StringBuffer object to a. Click after the close brace of the for loop
store system output messages. that displays the department names and
insert two new lines.

b. After the for loop that initializes the


departments array, declare sbMessage
as a StringBuffer object and initialize
it to null.

c. To describe the purpose of the code,


above the statement, insert the comment
// Variable to store a message
based on the user input

See Code Sample 4.

Code Sample 4
// Variable to store a message based on the user input
StringBuffer sbMessage = null;

3. Initialize the sbMessage object to a. In the switch statement code block, in


store the output message when the the blank line after case '5': type
user selects a department. sbMessage

b. To instantiate the object, enter a space


and type = new StringBuffer();

c. To specify the message to store in the


object, within the parentheses, type
"You selected the " +
departments[c -'1'].getName() +
" department"

4. Initialize the sbMessage object to a. In the switch statement code block, in


store the help message. the case '?': code block, type
sbMessage

b. To instantiate the object, enter a space


and type = new StringBuffer();

c. To specify the message to store in the


object, within the parentheses, type
"To select a department, type
its number and press Enter
\nPress '0' to exit"

102 Java Fundamentals (Java SE 7)


LESSON 3
5. Initialize the sbMessage object to a. In the switch statement code block, in
store the invalid entry message when the default code block, below the com-
the user provides an invalid entry and ment, in the blank line, type sbMessage
no message when the user termi-
nates.
b. To instantiate the object, enter a space
and type = new
StringBuffer("Invalid
department number");

c. In the switch statement code block, in


the case '0' code block, in a new line
type sbMessage

d. To enter a blank line when the user


selects 0, type = new
StringBuffer("");

6. Write an output statement to display a. After the close brace of the switch
the message from the statement, press Enter and write a system
StringBuffer object. output statement to print a new line.

b. To access the methods of the sbMessage The toString method is


object, within the parentheses, type called here to clarify that the
sbMessage. output is a string.

c. From the displayed list, select the


toString() : String - StringBuffer option.

d. Above the system output statement, in a


new line, write the single-line comment
// Display the output message

See Code Sample 5.

Code Sample 5
// Display the output message
System.out.println(sbMessage.toString());

Lesson 3: Working with Java Class Libraries 103


LESSON 3
7. Save and run the program to verify a. Save the file.
your code entries.
b. To execute the application, click the Run
button.

c. To test the application, input 9

d. View the invalid message displayed. To


seek help, input ?

e. View the help message displayed. Then to


view the department number and its
description, input 2

f. View the department number and mes-


sage displayed. Then, to exit the program,
input 0

g. Close the project.

TOPIC B
Invoke Attributes of an Object
In the previous topic, you created a new object based on a Java class library. Though Java
objects dene instances of classes, they are not very useful by themselves. They need to
receive messages to be able to perform operations. In this topic, you will call methods for the
Math, String, and StringBuffer classes to create functionality for your application.
Imagine receiving a new computer and discovering that it was not equipped with a keyboard.
Unfortunately, you dont have a device which you can use for inputting values to the com-
puter. The same logic applies when working with classes in Java. You need to use an operator
or a medium which enables you to access the attributes and methods dened in a class.

Dot Notation for Attributes and Methods


Dot Notation for Attributes and Denition:
Methods
A dot notation is normally used with attributes and methods to access:
The methods of an object.
The attributes of an object indirectly and return its value, thereby implementing
encapsulation.

104 Java Fundamentals (Java SE 7)


LESSON 3
Example:

Figure 3-5: Dot notation for attributes and methods.

Syntax: Dot Notation for Attributes and Methods


The syntax for dot notation to get the value of an objects variable is as follows:
objectName.variable;
The syntax for dot notation to set the value of an objects variable is as follows:
objectName.variable = value;

Method Arguments
Denition: Method Arguments
Method arguments are Java code elements that:
Are passed by a method.
Are contained within parentheses following the method name.
Form a part of the method signature.
Are passed by value, if they are primitive data type arguments.
Are passed by reference, when objects are passed as arguments.

Example:

Figure 3-6: Method arguments.

Lesson 3: Working with Java Class Libraries 105


LESSON 3
Pass by Value vs. Pass by Reference
Method parameters dene arguments from the receiving methods perspective. When
passing arguments by value, the receiving method receives the value of the variable
passed to it. The receiving method can process the value passed to it, but cannot
change the value of the variable passed by the calling method. When passing argu-
ments by reference, the receiving method has access to the object passed to it.
Therefore, the receiving method can modify the value of the passed object and the
updated value can be accessed from the calling method.

Execution of a Method
Methods execute when the program ow goes from the calling method to the receiving
method. Within the method, statements execute in the order they appear, taking into
consideration any control ow statements. A method ceases execution when execution
reaches the last statement, a return statement is executed, or an exception that is not
handled by the program is thrown.
Depending on the requirements of the program, your methods may need to return mul-
tiple results. To accomplish this goal, you can use parameters that are references to
objects that store multiple values or return an array containing the results.
Return statements can also be used in void methods in certain cases wherein you may
want to exit a method even before the end of the method.

A return statement before the end of the method is an example of a pseudo-goto statement, which vio-
lates the single entry-single exit best programming practice.

Calling Multiple Methods


When working with objects, you can call multiple methods of an object within a single
statement. These method names must be preceded with a dot notation. When the state-
ment is executed, the call to methods is evaluated from left to right. For example, you
can call multiple methods on the object titleName using objectName.setName()
.getName().

Methods of the Math Class


The methods of the Math class perform common mathematical calculations, such as absolute
value, cosine functions, and square root. The methods use normal oating-point syntax in radi-
ans.

Method Description
abs(z) Meaning: Absolute value of z (also used as float, int, and long).
Example:
abs(18.5) is 18.5
abs(0) is 0.0
abs(-18.5) is 18.5
ceil(z) Meaning: Rounds z to the smallest integer greater than or equal to z.
Example:
ceil(18.7) is 19.0
ceil(-18.2) is -18.0

106 Java Fundamentals (Java SE 7)


LESSON 3
Method Description
cos(z) Meaning: Cosine of z.
Example:
cos(0.0) is 1.0
exp(z) Meaning: Exponential z.
Example:
exp(3) is 20.08554
floor(z) Meaning: Rounds z to the largest integer less than or equal to z.
Example:
floor(18.2) is 18
floor(-18,7) is -19.0
log(z) Meaning: Natural logarithm of z.
Example:
log(18.5) is 2.91778
max(z, w) Meaning: Larger value of z and w (also used as float, int, and long).
Example:
max(4.2, 18.5) is 18.5
min(z, w) Meaning: Smaller value of z and w (also used as float, int, and long).
Example:
min(4.2, 18.5) is 4.2
pow(z, w) Meaning: Value of z to the power of w.
Example:
1 pow(2.1, 3.0) is 9.261
sin(z) Meaning: Sine of z.
Example:
sin(3.1) is 0.041581
sqrt(z) Meaning: Square root of z.
Example:
sqrt(18.5) is 4.301163
tan(z) Meaning: Tangent of z.
Example:
1 tan(3.1) is -0.041617

Accuracy of Math Class Methods


The accuracy of Math class mathematical calculations is determined by the units in
last place (ulp) or the difference between the two float values nearest to the result.
When a method has a ulp of less than 0.5, then it is said to represent the value closest
to the exact calculation. When a method has 0.5 ulp or more, the mathematical func-
tion must be semi-monotonic. This means that the result and the float approximation
must both round, either up or down.

Methods of the String Class


The String class provides methods for working with the characters in a string. These meth-
ods provide for actions, such as string comparison, string search, substring extraction, and
casing of strings. String conversions are done through the toString method and dened in
the Object class.
There are several methods dened in the String class. Some of the commonly used methods
are listed here.

Lesson 3: Working with Java Class Libraries 107


LESSON 3
Method Description
charAt(int index) Returns the character at the specied
index.
equals(Object thisObject) Compares a string to an object.
equalsIgnoreCase(String1, String2) Compares String1 to String2, ignoring
case.
indexOf(int ch) Returns the index within the string of
the rst instance of the indicated charac-
ter.
indexOf(String str) Returns the index within the string of
the rst instance of the indicated
substring.
length() Returns the length of the string.
substring(int beginIndex, int endIndex) Returns a new string that is a substring
of this string.
valueOf() Returns the string representation of the
argument.
indexOf(String str) Returns the index within the string of
the rst instance of the indicated
substring.
length() Returns the length of the string.
substring(int beginIndex, int endIndex) Returns a new string that is a substring
of this string.
valueOf() Returns the string representation of the
argument.

Methods of the StringBuffer Class


The StringBuffer class principal methods allow you to accomplish append and insert
actions. Every StringBuffer has a capacity. As long as you stay within that capacity, you are
not required to add a new internal buffer array. Should the internal buffer overow, it will
automatically enlarge.
There are seven methods in the StringBuffer class.

Method Description
append(Type Appends the string representation of the type argument to the StringBuffer.
Argument)
capacity() Returns the current capacity of the StringBuffer.
indexOf(String Returns the index within the string of the rst instance of the indicated
str) substring.
insert(int Inserts the string representation of the type argument into this StringBuffer.
offset, Type
Argument)
length() Returns the length of the StringBuffer.

108 Java Fundamentals (Java SE 7)


LESSON 3
Method Description
setLength(int Sets the length of the StringBuffer.
newLength)
toString() Converts the data in the StringBuffer to a string.

How to Call Methods


Procedure Reference: Call Methods
To call methods:
1. In the source code, state the name of the object that contains the method, fol-
lowed by dot notation.
2. State the method name.
3. In parentheses following the method name, state the method arguments.

ACTIVITY 3-2
Calling Methods for the Kiosk Application
Data Files:
Kiosk_3B.jar

Before You Begin:


Import the C:\085664Data\Working with Java Class Libraries\Kiosk_3B.jar project into the
Eclipse IDE.

Scenario:
You have written code with a single variable and three separate objects for each message. You
feel its better to further streamline your code by using a single instance of the
StringBuffer class and then manipulate it within the switch block by calling methods.
You also make sure that department names are displayed in uppercase.

Students can do this activity


individually or as a group.

Lesson 3: Working with Java Class Libraries 109


LESSON 3
What You Do How You Do It

1. Open the source code and delete the a. Display the source code of the Kiosk_
instances of the sbMessage object 3B.java file.
used for storing messages based on
user input.
b. Delete the instance and the comment for
the sbMessage object that is used to
store the department names.

See Code Sample 1.

c. Delete the instance for the sbMessage


object that is used to store the help mes-
sage along with its comment.

See Code Sample 2.

d. Delete the instance for the sbMessage


object that is used to display a blank line
when the user inputs 0.

See Code Sample 3.

e. Delete the instance and the comment for


the sbMessage object that is used to
store the invalid message.

See Code Sample 4.

f. Delete the output statement for display


messages depending on the user input.

See Code Sample 5.

g. To initialize the sbMessage to a default


value, in the statement that initializes the
sbMessage variable, double-click the
null value and type new
StringBuffer()

Code Sample 1
case '5':
// Stores the output message when the user selects a department
sbMessage=new StringBuffer("You selected the" +
departments[c - '1'].getName() + " department");
isValid = true;
break;
Code Sample 2
case '?':
// Stores the help message when the user selects help
sbMessage=new StringBuffer("To select a department, type its number
and press Enter \nPress '0' to exit");
break;

110 Java Fundamentals (Java SE 7)


LESSON 3
Code Sample 3
case '0':
sbMessage = new StringBuffer("");
Code Sample 4
default:
// Display error message for invalid entry
sbMessage=new StringBuffer("Invalid department number");
Code Sample 5
default:

}
// Display the output message
System.out.println(sbMessage.toString());

2. Append the message to the a. Below the switch case condition for 5,
sbMessage object. insert a new line and type sbMessage.

b. From the displayed list, select the


append(String arg0):StringBuffer option.

c. Within parentheses, type the message


"You selected" and terminate the
statement with a semicolon.

d. Above the append method statement,


write the single-line comment // Use
the append method to show
invalid input

See Code Sample 6.

Code Sample 6
// Use the append method to show invalid input
sbMessage.append("You selected ");

Lesson 3: Working with Java Class Libraries 111


LESSON 3
3. Display the department names in a. Insert two new lines after the append
uppercase. method call, and create a string for the
selected department as String
selectedDepartment =

b. In the string instantiation, to set the


selectedDepartment equal to the
departments array, with an index value,
type departments[c-'1'].

c. From the displayed list, select the


getName():String-DepartmentType
option and enter the dot notation.

d. From the displayed list, select the


toUpperCase():String-String option and
terminate the statement with a semico-
lon.

e. Press Enter and specify the sbMessage.

f. From the displayed list, select the


append(String arg0):StringBuffer option.

g. From the displayed list, select the


selectedDepartment option and termi-
nate the statement with a semicolon.

h. Above the statement, write the single-line


comment // Use getName and
toUpperCase methods to return
String

See Code Sample 7.

Code Sample 7
// Use the append method to show invalid input
sbMessage.append("You selected");
// Use getName and toUpperCase to return String
String selectedDepartment = departments[c-'1'].getName().toUpperCase();
sbMessage.append(selectedDepartment);

112 Java Fundamentals (Java SE 7)


LESSON 3
4. Append the help message to the a. In the case statement for ?, insert a new
sbMessage object. line and type sbMessage.

b. From the displayed list, select the


append(String arg0):StringBuffer option.

c. Within parentheses, type the message


"To select a department, type
its number, then press Enter
\nPress '0 to exit" and terminate
the statement with a semicolon.

d. Above the append method statement,


insert a new line and write the single-line
comment // Use the append
method to show help

See Code Sample 8.

Code Sample 8
// Use the append method to show help
sbMessage.append("To select a department, type its number, then press
Enter \nPress '0' to exit");

5. Append the invalid input message to a. Below the default: condition state-
the sbMessage object. ment, insert a new line and type
sbMessage.

b. From the displayed list, select the


append(String arg0):StringBuffer option.

c. Within parentheses, type the message


"Invalid department number" and
terminate the statement with a semico-
lon.

d. Above the append method statement,


write the single-line comment // Use
the append method to show
invalid input

See Code Sample 9.

Code Sample 9
// Use the append method to show invalid input
sbMessage.append("Invalid department number");

Lesson 3: Working with Java Class Libraries 113


LESSON 3
6. Write code to output the various dis- a. After the close brace of the switch
play messages and clear the loop for statement, press Enter.
iterations.
b. To access methods of the print stream,
type System.out.

c. From the displayed list, select


println(String arg0) : void - PrintStream

d. To display the string object messages, in


the output statement, type sbMessage.

e. From the displayed list, select


toString():String-StringBuffer, and termi-
nate the statement with a semicolon.

f. Above the statement, write a comment to


document what the code is for.

See Code Sample 10.

g. To clear the messages stored in the loop,


place the cursor before the switch state-
ment and type sbMessage.

h. From the displayed list, select


setLength(int arg0):void StringBuffer.

i. From the displayed list, select 0 and ter-


minate the statement with a semicolon.

j. Above the statement, write a comment to


document the purpose of the code.

See Code Sample 11.

Code Sample 10
// Display the message
System.out.println(sbMessage.toString());

Code Sample 11
while(isValid==false) {
System.out.print("\nEnter a department number : ");
// Read a character from the keyboard
int c=System.in.read();
// Clear any message from loop iterations
sbMessage.setLength(0);

114 Java Fundamentals (Java SE 7)


LESSON 3
7. Save and run the program to verify a. Save the file and execute the program.
the output.
b. Verify the output of the program and at
the prompt, input 1

c. Notice that the program displays the mes-


sage with the department name in
uppercase. Then, input 0

d. Close the project.

Lesson 3 Follow-up
In this lesson, you explored the Java class library structure, worked with constructors to create
new objects, and called methods of an object. You can now develop Java applications using
pre-congured capabilities provided by classes in Java libraries, instead of writing code for
each capability in your program.
1. Why do you think you will use Java packages when programming a Java application?
Answers will vary, but may include, classes and methods contained within Java packages
enable you to avoid re-creating structures, allow you to create objects of that package,
and group related classes together.
2. Why would you define your own methods instead of using the methods predefined in
Java?
Answers will vary, but may include the following: When programming, to save time and
memory, you can use predefined methods. However, your programming requirements can-
not always be met by using ready-made methods. Defining your own methods allows you
the freedom to declare a behavior that addresses your specific needs.

Lesson 3: Working with Java Class Libraries 115


NOTES

116 Java Fundamentals (Java SE 7)


LESSON 4

LESSON 4 Lesson Time


7 hour(s)

Creating Classes
In this lesson, you will create classes.
You will:
Dene methods.
Overload a method.
Dene constructors.
Create static class members.
Use command-line arguments.
Use the getter and setter methods in a JavaBean class.

Lesson 4: Creating Classes 117


LESSON 4
Introduction
You developed Java applications using pre-congured capabilities provided by classes in Java
libraries. Now that this course is moving a little deeper into programming, you will learn to
dene methods that let you perform a series of tasks based on the input given by the user. In
this lesson, you will implement methods of a Java class.
The Java programming language allows you to simplify code by implementing methods that
perform a series of actions to yield a desired result. These methods help in streamlining code
and also increase your efficiency by allowing the reuse of certain code elements in the applica-
tion.

TOPIC A
Dene Methods
In Java, you work with methods that are predened and associated with existing classes. When
addressing specic programming requirements, you will determine a list of methods needed to
be readily available in the dened class. In this topic, you will dene methods.
Without methods, your objects would consist of only attributes that you can neither access nor
use. Methods are required to cause your objects to perform actions. By dening methods to
tackle your specic requirements, you can streamline your code and create more functionality
and efficiency within your program.

Method Declaration
Method Declaration
A method declaration is a Java code element that:
Consists of the following elements: access modier, return type, method name, arguments,
and method body.
Will not return any value if it is declared void.
Has its return value explicitly called in its body using the return keyword.
Cannot be declared inside another method.

Figure 4-1: A method declaration.

118 Java Fundamentals (Java SE 7)


LESSON 4
The Method Declaration Header
The method declaration header consists of access modiers and the return type of the
method. If the header of a method declaration exceeds a line, then you may be com-
bining too many tasks. Consider separating the method into smaller methods to
separate tasks. If a method declaration includes a return type that is an array, you may
place the array braces on either side of the return type.

Syntax: Method Declaration


Method declaration uses the following syntax:
accessModifier returnType methodName (arguments) {
//..method body . . .
return objectOfReturnType;
}

Local Variables
Denition: Local Variables
A local variable is a variable that:
Is passed as a method parameter or declared in the body of a method.
When located in the method body, receives its value during method execution.
Can only be used in the same block in which it is declared.
Does not exist outside the method.

Variable Scope
Variable scope is a block of code in which a variable may be used. The scope of a
local variable is limited to the method in which it is declared, or a block within the
method, if it is declared within it. When working with methods, if a variable is dened
in an outer code block and then dened in an inner block with the same name, a syn-
tax error will occur during compilation. However, if a local variable has the same
name as an instance variable, the instance variable will be hidden during execution of
the block of code containing the local variable, unless specically referenced using the
dot notation.

Example:

Figure 4-2: A local variable.

Lesson 4: Creating Classes 119


LESSON 4
How to Dene Methods
Procedure Reference: Dene Methods
To dene methods:
1. In the source code, state the method return type.
2. Specify a method name.
3. If necessary, after the method name and in parentheses, insert the argument types
and names for the method.
4. Insert the body of the method.

ACTIVITY 4-1
Dening Methods to Get and Set Department
Descriptions for the Kiosk Application
Data Files:
Kiosk_4A.jar

Before You Begin:


Import the C:\085664Data\Creating Classes\Kiosk_4A.jar project into the Eclipse IDE.

Scenario:
Your manager describes a new kiosk feature. If a user selects a department, a description of
the department should display. You and your colleague decide that she will rst input the infor-
mation for the description of each department. Youll then use that code and create the desired
functionality by dening and implementing methods to handle getting and setting the descrip-
tions for each department.

What You Do How You Do It

1. Open the source code and declare an a. Display the source code of the
attribute for storing the depart- DepartmentType.java file.
ments description.
b. To define a variable to store the descrip-
tion, after the declaration of the name
variable, insert a new line and type
private String description;

See Code Sample 1.

Code Sample 1
private String name;
private String description;

120 Java Fundamentals (Java SE 7)


LESSON 4
2. Generate the getter and setter meth- a. To add the getter and setter methods,
ods for the department description choose SourceGenerate Getters and
variable. Setters.

b. In the Generate Getters and Setters dia-


log box, in the Select getters and setters
to create list box, select description.

c. At the bottom of the Generate Getters


and Setters dialog box, check the Gener-
ate method comments check box and
click OK.

d. Save the DepartmentType.java file.

3. Add code to set department descrip- a. Display the source code of the Kiosk_
tions along with department names. 4A.java file.

b. In the for loop for initializing the array A warning may appear in the
elements, after the statements that set source code with the
the department names, insert a new line information that the variable
departmentDescription
and type departments[i].
is not used. This variable will
be used during the activity
See Code Sample 2.
and therefore you can ignore
the warning.
c. From the displayed list, select the
setDescription(String description) : void
- DepartmentType option.

d. Within parentheses, type


departmentDescriptions[i] and ter-
minate the statement with a semicolon.

See Code Sample 3.

Code Sample 2
for (int i=0;i<departments.length;i++) {
departments[i]=new DepartmentType();
departments[i].setName(departmentNames[i]);
departments[i].
}

Code Sample 3
departments[i].setName(departmentNames[i]);
departments[i].setDescription(departmentDescriptions[i]);

Lesson 4: Creating Classes 121


LESSON 4
4. Write code to get the department a. In the case '5' code block, after the
descriptions and add it to the statement that adds the word depart-
StringBuffer object. ment to the StringBuffer object,
insert a line and type sbMessage.

b. From the displayed list, select the


append(String arg0) : StringBuffer -
StringBuffer option.

c. To access the methods of the


DepartmentType class, within parenthe-
ses, type departments[c-'1'].

d. From the displayed list, select the


getDescription() : String -
DepartmentType option.

e. Add code to print two blank lines and then


terminate the sentence with a semicolon.

See Code Sample 4.

f. Above the statement, insert the comment


// Use the append method to get
the description of the
department

See Code Sample 5.

Code Sample 4
sbMessage.append(selectedDepartment);
sbMessage.append(departments[c - '1'].getDescription()+ "\n\n");
Code Sample 5
// Use the append method to get the description of department
sbMessage.append(departments[c - '1'].getDescription());

122 Java Fundamentals (Java SE 7)


LESSON 4
5. Save and run the program to verify a. Save the file and execute the program.
the output.
b. At the prompt, input 1

c. Notice that the department name and the


description are displayed.

d. Provide other inputs to view the descrip-


tions of other departments.

e. At the prompt, input 0

f. Close the project.

TOPIC B
Overload a Method
When programming with Java, you often encounter the question of whether to work with pre-
dened objects or to create your own. However, dening classes and methods can be tricky
and lead to several sets of code relating to the same context repeated several times in the pro-
gram. Fortunately, Java provides another alternative when working with methods. In this topic,
you will overload methods.
When your programming requirements necessitate methods to perform similar tasks using dif-
ferent numbers or types of variables, you could declare as many methods as needed. However,
in doing so, you add unnecessary complexity to your code by creating more methods to be
remembered and dealt with. To maintain consistency with naming conventions and to eliminate
the need for dening entirely different methods that do the same thing, you can use method
overloading.

Method Overloading
Denition: Method Overloading
Method overloading is a form of polymorphism that:
Refers to an objects ability to behave differently depending on the inputs.
Is implemented by declaring multiple methods of the same name in the same
class, but with different arguments.
Java implements polymorphism when an overloaded method is called, where the Java
compiler matches the passed arguments with signatures of the overloaded method and
selects the appropriate method to execute.

Method overloading is a form of polymorphism, which refers to an objects ability to behave differently
depending on the arguments passed to it. Polymorphism provides a powerful means to extend objects.

Lesson 4: Creating Classes 123


LESSON 4
Issues with Method Overloading
You may use method overloading to create methods that perform similar functions on
different objects. However, when you change only the return type of methods, the Java
compiler does not distinguish between methods using the return type leading to compi-
lation failure. The Java compiler does not consider variables used within a method;
therefore, you can use any names for the variables within a method to fulll your pro-
gramming requirements.

Dynamic or Runtime Polymorphism


Java allows you to override a method in the base class by using a method of the same
name and signature in the derived class. Java Virtual Machine (JVM) determines which
method needs to be called during the runtime. This is also known as dynamic or
runtime polymorphism.

Example:

Figure 4-3: Method overloading.

How to Overload a Method


Procedure Reference: Overload a Method
To overload a method:
1. In the source code, if necessary, dene a method for a class.
2. Dene additional methods with the same name as the rst method, but with a dif-
ferent set of arguments.

124 Java Fundamentals (Java SE 7)


LESSON 4
ACTIVITY 4-2
Overloading a Method to Set Department Names and
Descriptions
Data Files:
Kiosk_4B.jar

Before You Begin:


Import the C:\085664Data\Creating Classes\Kiosk_4B.jar project into the Eclipse IDE.

Scenario:
After adding the descriptions to the output, you review your code. You decide that its more
efficient to set the department names and descriptions at the same time rather than to call each
method separately. Therefore, you decide to overload a method.

Lesson 4: Creating Classes 125


LESSON 4
What You Do How You Do It

1. Overload the setDescription a. Display the source code of the


method. DepartmentType.java file.

b. To create another method with the same


name, after the close brace of the
setDescription method, insert a new
line and type public void
setDescription(String name,
String description)

See Code Sample 1.

c. To define the methods body, insert a


space and an open brace, and then press
Enter.

d. To refer to the instance variable of the


object, type this.

e. From the displayed list, select the name :


String - DepartmentType option.

f. To set the instance variable to the local


variable passed as an argument, type
=name;

g. To instantiate the instance variable


description to the value passed to the
method, insert a new line and type
this.description=description;

h. Save the DepartmentType.java file.

Code Sample 1
public void setDescription(String description) {
this.description = description;
}
public void setDescription(String name, String description)

126 Java Fundamentals (Java SE 7)


LESSON 4
2. Remove the statement that initializes a. Display the source code of the Kiosk_
the name of the DepartmentType 4B.java file.
object.
b. In the for loop for initializing the array
elements, delete the statement that
accesses the setName method.

See Code Sample 2.

c. To modify the parameters passed using


the setDescription method, in the
arguments passed to the
setDescription method, click before
the departmentDescriptions variable
and type departmentNames[i],

See Code Sample 3.

Code Sample 2
// Initialize array elements
for (int i=0;i<departments.length;i++) {
departments[i]=new DepartmentType();
departments[i].setName(departmentNames[i]);
departments[i].setDescription(departmentDescriptions[i]);
}
Code Sample 3
departments[i]=new DepartmentType();
departments[i].setDescription(departmentNames[i],departmentDescriptions[i]);

3. Save and run the program to verify a. Save and run the program.
the code entries.
b. At the prompt, input 2

c. Notice that the department name and


description are displayed on the screen.
Then, input 0

d. Close the project.

Lesson 4: Creating Classes 127


LESSON 4
TOPIC C
Dene Constructors
In the previous topic, you overloaded a method to accept a different set of arguments and pro-
cess data accordingly. When creating objects, you can specically instantiate those objects to
allocate memory and initialize the object instance variables. In this topic, you will dene con-
structors.
In Java, you can create objects or use predened objects. When creating objects or using pre-
dened objects, you need to specify how these objects are initialized and what parameters need
to be passed to these objects. Java allows you to dene templates, in the form of constructors,
that create and initialize objects according to the applications requirements.

Constructor Methods
Constructor Methods Denition:
A constructor method is a type of method that:
Has the same name as the class in which it is located.
Does not have a return type.
Accepts arguments within parentheses, just like any other method.
Is used to initialize instance variables or perform specic tasks at object
instantiation.
Is invoked when the new keyword is used to create a new object.

Syntax: Constructor Method


A constructor method uses the following syntax:
class ClassName {
type1 instanceVar1;
type2 instanceVar2;
type3 instanceVar3;

ClassName (type1 arg1, type2 arg2, type3 arg3) {


instanceVar1 = arg1;
instanceVar2 = arg2;
instanceVar3 = arg3;
}
}

Default Constructors
In Java, every class must have at least one constructor. If a class does not have a
dened constructor, the Java compiler will automatically create a default constructor,
which will not accept any arguments. When invoked, the default constructor will ini-
tialize variables to the default value as dened by their data type. Although you can
create objects with the new keyword, you may need to dene instance variables of the
object or call other methods in your code to nish the initialization process. Finally,
the default constructor has the same accessibility as the class in which it resides and
may include a call to any superclass constructors, as super().

128 Java Fundamentals (Java SE 7)


LESSON 4
Example:

Figure 4-4: A constructor method.

The This Keyword


Denition: The This Keyword
The keyword this is a Java keyword that:
Is used to access variables and methods of the current object from within the
objects methods.
Is used in instances where the method refers to the object that has invoked it.
Is usually used to refer to the current object.

It can be used anywhere to reference the current object, such as dot notation, methods, and return
values. It can call a constructor from inside the body of another constructor. However, it cannot be
used with static class methods.

Syntax: The this Keyword Object Reference


The this keyword enables you to reduce code duplication in your programs. The
this keyword object reference uses the following syntax:
public class ClassName {

int x;
int y;

public ClassName(int x, int y) {


this.x = x;
this.y = y;
}
}

Lesson 4: Creating Classes 129


LESSON 4
Example:

Figure 4-5: Implementing the this keyword.

Overloading Constructors
Overloading Constructors
Constructor overloading is a form of polymorphism that is implemented by declaring multiple
constructors in the same class, but with different arguments. Similar to method overloading,
overloaded constructors are distinguished by the data type and number parameters they accept.
When an object is instantiated, the Java compiler compares the arguments passed with the call
to the parameters of the constructors, to select the appropriate constructor. Constructor over-
loading is often used to initialize objects in various ways based on arguments passed to it.

Figure 4-6: An overloaded constructor.

Syntax: Calling Another Constructor Method


A constructor may duplicate some of the behaviors of another constructor. In such
instances, it may be benecial to overload the constructor by adding additional state-
ments to implement the new functionality and then call the rst constructor to
implement the original functionality. The following is the syntax for calling another
constructor method:

130 Java Fundamentals (Java SE 7)


LESSON 4
class ClassName {

type1 var1;
type2 var2;
type3 var3;

ClassName(type1 arg1, type2 arg2) {


var1 = arg1;
var2 = arg2;
}
ClassName(type1 arg1, type2 arg2, type3 arg3) {
var3 = arg3;
this(arg1, arg2);
}
}
When programs are developed, you may have two arguments that are passed to a con-
structor. Over time, the program may be extended to add features that will require the
constructor to accept three arguments. In such instances, the three new argument con-
structors will contain the new logic, and the old two-argument constructor can just be
called to implement the original functionality. In this example, the second constructor
ClassName(type1 arg1, type2 arg2, type3 arg3) assigns the value to
the third variable and then calls the arguments of the rst constructor
ClassName(type1 arg1, type2 arg2).

How to Dene Constructors


Procedure Reference: Dene Constructors
To dene constructors:
1. In the source code, name the constructor with the same name as the class.
2. Insert types and parameter variables in parentheses after the constructor name.
3. Insert the body of the constructor.

Lesson 4: Creating Classes 131


LESSON 4
ACTIVITY 4-3
Dening Constructors for the Department Type Class
Data Files:
Kiosk_4C.jar

Before You Begin:


Import the C:\085664Data\Creating Classes\Kiosk_4C.jar project into the Eclipse IDE.

Scenario:
As good programming practice, you spend some time reviewing your kiosk code. You decide
to dene a constructor so that you can efficiently run the application by setting the department
name while initializing the objects that represent the department. You also decide to initialize
objects depending on the number of arguments in an overloaded constructor.

132 Java Fundamentals (Java SE 7)


LESSON 4
What You Do How You Do It

1. Define a constructor for the a. Display the source code of the


DepartmentType class. DepartmentType.java file.

b. After the declaration of the


description variable, insert a new line
and type DepartmentType()

See Code Sample 1.

c. To declare the first argument for the con-


structor, within parentheses, type
String name

d. To declare the second argument for the


constructor, type , String
description

See Code Sample 2.

e. To define the body for the constructor,


after the close parenthesis, insert an open
brace and press Enter.

Code Sample 1
private String name;
private String description;
DepartmentType()

Code Sample 2
private String description;
DepartmentType(String name, String description)

Lesson 4: Creating Classes 133


LESSON 4
2. Add code to instantiate the depart- a. To access a list of instance variables of
ment name and description. the class, type this.

b. From the displayed list, select the name :


String - DepartmentType option.

c. To set the variable to the passed param-


eter for the department name, type
=name;

d. Similarly, in the next line, instantiate the


instance variable description to the
parameter passed for the department
description.

See Code Sample 3.

e. To generate comments for the construc-


tor, choose SourceGenerate Element
Comment.

f. After the first line of the comment, insert


a new line and add the description
Constructor to set the
department name and description

Code Sample 3
DepartmentType(String name, String description){
this.name=name;
this.description=description;
}

134 Java Fundamentals (Java SE 7)


LESSON 4
3. Overload the constructor to instanti- a. After the closing brace of the constructor,
ate departments by name only. insert a new line and define another con-
structor.

See Code Sample 4.

b. To declare the argument as the depart-


ment name, within parentheses, type
String name

c. To define the body for the constructor,


after the close parenthesis, insert an open
brace and press Enter.

d. Instantiate the instance variable name to


the parameter passed for the department
name.

See Code Sample 5.

e. In the next line, instantiate the instance


variable department to the text
Description not available

See Code Sample 6.

f. Generate comments for the overloaded


constructor.

g. After the first line of the comment, insert


a new line and add the description
Overloaded constructor to set
the department name

h. In the next line, type and add


default text for department
description

See Code Sample 7.

Code Sample 4
DepartmentType(String name, String description){
this.name=name;
this.description=description;
}

DepartmentType()

Code Sample 5
DepartmentType(String name){
this.name=name;
}
Code Sample 6

Lesson 4: Creating Classes 135


LESSON 4
DepartmentType(String name){
this.name=name;
this.description="Description not available";
}
Code Sample 7
/**
* Overloaded constructor to set the department name
* and add default text for department description
* @param name
*/

4. Define a default constructor with no a. After the closing brace of the overloaded
arguments. constructor, insert two new lines and
define a constructor.

See Code Sample 8.

b. To define the body for the constructor,


after the close parenthesis, insert an open
brace and press Enter.

Because no parameters are c. Generate comments for the default con-


passed to the default structor.
constructor, it will initialize the
objects to the default values
dened by their data types. d. In the second line of the comment, type
Default constructor

e. Save the DepartmentType.java file.

Code Sample 8
DepartmentType(String name){
this.name=name;
this.description="Description not available";
}

DepartmentType()

136 Java Fundamentals (Java SE 7)


LESSON 4
5. Use the initialization statement for a. Display the source code of the Kiosk_
DepartmentType objects to set the 4C.java file.
name and description.
b. In the for loop used to set the name and
description for the departments, delete
the statement that accesses the over-
loaded setDescription method.

See Code Sample 9.

c. To initialize the department details using


the constructor, in the statement that
initializes the DepartmentType object,
within the parentheses, type
departmentNames[i],departmentDescriptions[i]

See Code Sample 10.

Code Sample 9
// Initialize array elements
for (int i=0;i<departments.length;i++) {
departments[i]=new DepartmentType();

departments[i].setDescription(departmentNames[i],departmentDescriptions[i]);
}
Code Sample 10
// Initialize array elements
for (int i=0;i<departments.length;i++) {
departments[i]=new
DepartmentType(departmentNames[i],departmentDescriptions[i]);
}

6. Save and run the program to verify a. Save the file and execute the program.
the output.
b. Verify the output of the program and at
the prompt, input 3

c. Notice that the program displays the mes-


sage with the department names and
description. Then, input 0

d. Close the project.

Lesson 4: Creating Classes 137


LESSON 4
TOPIC D
Create Static Class Members
In the previous topic, you overloaded constructor methods to initialize attributes of an object.
Each object created in a Java program uses its own instance variables, if the variables are
declared, when performing methods. In certain situations, it may be desirable to dene class
members that can be used throughout the program. In this topic, you will create static class
members.
You will usually use an object to access the variables of a class. Java allows multiple objects
to access the variable from anywhere by declaring them as static. This way, the value stored in
the variable doesnt change with any calls to the function.

Static Methods
Static Methods Denition:
A static method is a method that:
Is dened with the static keyword.
Can be accessed by using the class name, dot notation, and a method name.
Can be called from within or outside a class.
When called from outside a class, the class where a method is dened should be
specied.
Cannot access instance variables.
Is also referred to as class methods.

When using static methods from wrapper classes, you can convert objects to primitive types and
primitive types to objects. Wrapper classes are discussed in detail later in the course.

Example:

Figure 4-7: A static method.

Static Variables
Static Variables Denition:
The static variable is a variable that:
Is dened using the static keyword.
Can be accessed by all objects based on the class in which the static variables are
dened.

138 Java Fundamentals (Java SE 7)


LESSON 4
Is shared with other objects based on the class to save memory space, as only one
variable copy is maintained in a class.
Can be used outside its own class by stating the qualied name, which includes
the class name, dot notation, and variable name.
Is also referred to as a class variable.

Instances of Static Variables


You can have one copy of a static variable and not create new instances of the vari-
able, much like a template. The value of the static variable is incremented from the
previous instance of the variable or the originally assigned value from initialization,
especially when you perform certain operations on it. These instances can be referred
to by their simple name in the class in which they are dened or with their qualied
name from outside the class.

Example:

Figure 4-8: A static variable.

How to Create Static Class Members


Procedure Reference: Create Static Class Members
To create static class members:
1. In the source code, insert the static keyword.
2. State the class member type.
3. Declare the class member name.

Lesson 4: Creating Classes 139


LESSON 4
ACTIVITY 4-4
Creating Static Class Members for the Kiosk Application
Data Files:
Kiosk_4D.jar

Before You Begin:


Import the C:\085664Data\Creating Classes\Kiosk_4D.jar project into the Eclipse IDE.

Scenario:
After reviewing your source code, you determine that you can streamline your code even more
by creating a static class member. You decide to modify the code to output the welcome mes-
sage and the menu.

What You Do How You Do It

1. Define a static class variable to track a. Display the source code of the
the total number of departments. DepartmentType.java file.

b. After declaration for the description


variable, insert a new line and declare a
static variable of integer data by typing
static int totalDepartments;

See Code Sample 1.

c. Above the statement, insert a single-line


comment // Tracks the total
number of departments

See Code Sample 2.

Code Sample 1
private String name;
private String description;
static int totalDepartments;
Code Sample 2
private String name;
private String description;
// Tracks the total number of departments
static int totalDepartments;

140 Java Fundamentals (Java SE 7)


LESSON 4
2. Define getters to return the total a. To create the get method for
number of departments. totalDepartments, choose Source
Generate Getters and Setters.

b. In the Generate Getters and Setters dia-


log box, in the Select getters and setters
to create list box, expand
totalDepartments and, from the list,
select the getTotalDepartments() option.

c. In the Insertion point section, from the


drop-down list, select the After
setDescription(String, String) option.

d. Verify that the Generate method com-


ments check box is checked and then
click OK.

e. Scroll down to view the inserted static get


method for returning the value of the
static variable totalDepartments.

Lesson 4: Creating Classes 141


LESSON 4
3. Insert an expression to track the a. In the constructor method, after the
total number of departments. statement initializing the instance vari-
able department, insert a new line and
type totalDepartments++;

See Code Sample 3.

b. Similarly, in the overloaded constructor


method, after the statement initializing
the instance variable department, insert a
new line and type
totalDepartments++;

See Code Sample 4.

c. Similarly, in the default constructor


method, type totalDepartments++;

See Code Sample 5.

d. Save the DepartmentType.java file.

Code Sample 3
DepartmentType(String name, String description) {
this.name = name;
this.description = description;
totalDepartments++;
}

Code Sample 4
DepartmentType(String name) {
this.name = name;
this.description = "Description not available";
totalDepartments++;
}

Code Sample 5
DepartmentType() {
totalDepartments++;
}

142 Java Fundamentals (Java SE 7)


LESSON 4
4. Update the variable used to display a. Display the source code of the Kiosk_
the number of departments. 4D.java file.

b. To remove the code used to display the


total number of departments, delete the
code departments.length

See Code Sample 6.

c. To use the static variable for displaying


the number of departments, type
DepartmentType.

d. From the displayed list, select the


getTotalDepartments() : int -
DepartmentType option.

Code Sample 6
System.out.println(WELCOME+"\n");
System.out.println("Our store features "+departments.length+" departments\n");

5. Save and run the program to verify a. Save the file and execute the program.
the output.
b. Notice that the number of departments is
displayed correctly and then input 0

c. Close the project.

TOPIC E
Use Command-Line Arguments
In the previous topic, you worked with static methods and variables. You can also execute Java
applications from the command prompt and provide inputs for the program to process. In this
topic, you will use command-line arguments in your Java application.
Java applications, with the exception of Applets, are programs that operate independently of
other programs. Therefore, it is often useful to pass information into the program. This infor-
mation provides the program with additional data that it can process to generate output. Java
provides this functionality through command-line arguments.

Command-Line Arguments
Denition: Command-Line Arguments
Command-line arguments are parameters that:

Lesson 4: Creating Classes 143


LESSON 4
Are stored within the main method in an array of String objects.
Can be called from within the main method.
Are invoked when running a Java program.
Are listed after the le name with each argument separated by a space.
Use quotation marks when an argument contains multiple words with spaces.

The array within the main method is commonly called arguments or args. Although you can refer to
this string by any name, it is recommended that you use one of the common names.

Command-Line Arguments in the Main Method


Command-line parameters are dened as part of the main methods signature. The
array within the main method is known as arguments or args. Although you can refer
to this string by any name, it is recommended that you use one of the common names.
When developing a program, you can create functionality that uses these arguments by
writing statements that process these arguments.
The command-line argument structure is not an array; rather Java stores the arguments
as an array. Therefore, when you use command-line arguments in your program, it is a
best practice to include code to handle situations such as entry of fewer than expected
arguments. This code can either test the length of the array or use exception handling
code to handle such situations. Without this code, the chances of the application crash-
ing with an ArrayOutOfBoundsException are high. Finally, all command-line
arguments pass into the main method as String objects, so you may need to convert
these arguments to a numerical data type before performing mathematical operations.

Example:

Figure 4-9: Command-line arguments during program execution.

How to Use Command-Line Arguments


Procedure Reference: Use Command-Line Arguments
To use command-line arguments:
1. In the Text Editor area, write code to handle command-line arguments.
2. Save, compile, and run using command-line arguments.

144 Java Fundamentals (Java SE 7)


LESSON 4
ACTIVITY 4-5
Using Command-Line Arguments
Data Files:
Kiosk_4E.jar

Before You Begin:


Import the C:\085664Data\Creating Classes\Kiosk_4E.jar project into the Eclipse IDE.

Scenario:
Your manager wants the kiosk application to be more user friendly. You decide to add a greet-
ing to welcome the user to the kiosk application when the user executes the kiosk application.

What You Do How You Do It

1. Check whether the user has entered a. Display the source code of the Kiosk_
any command-line arguments. 4E.java file.

b. After the open brace of the do...while


loop, insert a new line and enter an if
statement.

See Code Sample 1.

c. Within the parentheses, enter the test


expression (args != null) &&
(args.length > 0)

d. After the closing parenthesis, enter the


open brace for the if statement code
block and press Enter.

Code Sample 1
do {

if()

/* Displays welcome message


* and department names
*/

Lesson 4: Creating Classes 145


LESSON 4
2. Specify the text to display as a a. Enter a system output statement to print
command-line argument. in a new line.

b. Within the parentheses, type "Hello!


" + args[0]

See Code Sample 2.

c. After the open brace of the do...while


loop, insert a new line and enter a com-
ment to describe the code.

See Code Sample 3.

Code Sample 2
do {

if ((args != null) && (args.length > 0)) {


System.out.println("Hello! " + args[0]);
}
/* Displays welcome message
* and department names
*/

Code Sample 3
do {

// Display message using command line argument


if ((args != null) && (args.length > 0)) {
System.out.println("Hello! " + args[0]);
}
/* Displays welcome message
* and department names
*/

146 Java Fundamentals (Java SE 7)


LESSON 4
3. Save and run the program to verify a. Save the file.
the output.
b. To run the program using command line
arguments, choose RunRun Configura-
tions.

c. In the Run Configurations dialog box, in


the left pane, verify that Kiosk_4E is
selected and in the right pane, select the
Arguments tab.

d. In the Program arguments text box, type


your name.

e. To execute the program with the specified


arguments, click Run.

f. Notice that a message is displayed using


the arguments you specified. Then, input
0

g. Close the project.

TOPIC F
Dene JavaBeans
In the previous topic, you used command-line arguments to run Java programs. A Java class
usually contains getter and setter methods for storing the attributes and properties of classes
and accessing the values passed to it. JavaBean is one such class that is used to store and
retrieve values. In this topic, you will dene JavaBeans.
Java also allows users the exibility of running Java applications from any location. It pro-
vides enhanced code functionality by getting and setting values at runtime and also allowing
the code to run in multiple locations. Java provides this functionality by using the JavaBean
class.

The JavaBean Class


Denition: The JavaBean Class
A JavaBean is a Java class that:
Allows you to code a program in a remote machine and run the code on a server,
following the Write once, run anywhere principle.
Is a reusable component only when it implements a serializable interface.
Can be visually manipulated using builder tools, such as JBuilder.

Lesson 4: Creating Classes 147


LESSON 4
Is used to represent an object at runtime.
Is used to store and retain values over a period of time.
Is written in Java and conforms to JavaBean coding standards.
Is used for encapsulating many entities into a single entity so that it enables easy
data transfer.

Write once, run anywhere is a coding principle where you can write code in a remote machine and
run the code on the server from any location. This feature cannot be implemented using an ordinary
Java class.

Serializable Interface
Serializable is an interface that is used to indicate the state of an object. The syntax for
the serializable is:
public class BeanName implements java.io.Serializable

Example:

Figure 4-10: A JavaBean class.

Getter and Setter Methods


A JavaBean class must have two types of methods, the getter and setter methods, as per con-
ventions. These methods are used to set and retrieve the properties of a class.

Method Type Used To


getter Get values from the property. The naming convention is
getVariableName(). In case of boolean variables, it may be
isVariableName()
setter Set values to the property. The naming convention is setVariableName()

148 Java Fundamentals (Java SE 7)


LESSON 4
How to Use Getter and Setter Methods in
JavaBeans
Procedure Reference: Call Methods
To use get and set properties:
1. In the source code le, create a new class.
2. Inside the class, declare variables.
3. Add getter and setter methods.

ACTIVITY 4-6
Dening a JavaBean Class
Data Files:
Kiosk_4F.jar

Before You Begin:


Import the C:\085664Data\Creating Classes\Kiosk_4F.jar project into the Eclipse IDE.

Scenario:
In addition to the kiosk application, your manager wants another application that will store and
retrieve details of kiosk users. You decide to use a JavaBean class and add getter and setter
methods to store and access users details.

What You Do How You Do It

1. Create a new JavaBean class in the a. Within the Kiosk_4F project, in the src
default package. folder, select the (default package)
folder.

b. On the toolbar, click the New drop-down


arrow, and from the displayed list, select
Class.

c. In the New Java Class dialog box, in the


Name field, type UserDetails

d. To automatically generate comments for


the code, check the Generate comments
check box and click Finish.

Lesson 4: Creating Classes 149


LESSON 4
2. Declare variables to store user a. Position the cursor after the open brace of
details. the UserDetails class and insert two
lines.

b. To store the users name, insert a state-


ment to declare a private variable name
of String data type.

See Code Sample 1.

c. To store the department name of the


selected department, in the next line,
insert a statement to declare a private
variable departmentName of String
data type.

See Code Sample 2.

d. To store the phone number of the user, in


the next line, insert a statement to
declare a private variable phoneNumber
of String data type.

See Code Sample 3.

Code Sample 1
public class UserDetails {

private String name;

Code Sample 2
public class UserDetails {

private String name;


private String departmentName;

}
Code Sample 3
public class UserDetails {

private String name;


private String departmentName;
private String phoneNumber;

150 Java Fundamentals (Java SE 7)


LESSON 4
3. Generate the getter and setter meth- a. To display the Generate Getters and Set-
ods to store and retrieve the variable ters dialog box, choose Source
data. Generate Getters and Setters.

b. To generate getters and setters for all


variables, click Select All.

c. Verify that the Generate method com-


ments check box is selected and click OK.

d. Scroll down to verify that the getters and


setters for all variables are defined.

e. Save the UserDetails.java file.

4. Declare an array of UserDetails a. Display the Kiosk_4F.java file.


class to store the user information.
b. After the statement that initializes the
array to store details of users, insert two
lines and type UserDetails[] Users =
new UserDetails[5];

See Code Sample 4.

c. Above the statement, enter a single line


comment // Declare an array of
UserDetails class to store user
info

See Code Sample 5.

Code Sample 4
// Multi-dimensional String array with details of users
String UserInfo[][] = {{"Joe", "Pat", "Chris"},
{"Paint","Electrical","Plumbing"},
{"555-623-3442","555-434-5544","555-643-7434"}};

UserDetails[] Users = new UserDetails[5];


Code Sample 5
// Multi-dimensional String array with details of users
String UserInfo[][] = {{"Joe", "Pat", "Chris"},
{"Paint","Electrical","Plumbing"},
{"555-623-3442","555-434-5544","555-643-7434"}};

// Declare an array of UserDetails class to store user info


UserDetails[] Users = new UserDetails[5];

Lesson 4: Creating Classes 151


LESSON 4
5. Access setter methods to store user a. After the statement that declares the
details. Users variable, insert two lines and type
for (int i = 0; i < 3; i++)

See Code Sample 6.

b. To define the code block for the for


loop, insert a space and an open brace,
and then press Enter.

c. To initialize the first item of the array,


type Users[i] = new UserDetails()
;

See Code Sample 7.

d. To set the name using the setter method,


type
Users[i].setName(UserInfo[0][i])
;

See Code Sample 8.

e. Similarly, use the setter method, to store


the selected department and contact
number.

See Code Sample 9.

f. Above the for loop, enter the single line


comment // Use setters to store
user details

See Code Sample 10.

Code Sample 6
// Declare an array of UserDetails class to store user info
UserDetails[] Users = new UserDetails[5];

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


Code Sample 7
// Declare an array of UserDetails class to store user info
UserDetails[] Users = new UserDetails[5];

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


Users[i] = new UserDetails();
}
Code Sample 8
// Declare an array of UserDetails class to store user info
UserDetails[] Users = new UserDetails[5];

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

152 Java Fundamentals (Java SE 7)


LESSON 4
Users[i] = new UserDetails();
Users[i].setName(UserInfo[0][i]);
}
Code Sample 9
// Declare an array of UserDetails class to store user info
UserDetails[] Users = new UserDetails[5];

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


Users[i] = new UserDetails();
Users[i].setName(UserInfo[0][i]);
Users[i].setDepartmentName(UserInfo[1][i]);
Users[i].setPhoneNumber(UserInfo[2][i]);
}
Code Sample 10
// Declare an array of UserDetails class to store user info
UserDetails[] Users = new UserDetails[5];

// Use setters to store user details


for (int i = 0; i < 3; i++) {
Users[i] = new UserDetails();
Users[i].setName(UserInfo[0][i]);
Users[i].setDepartmentName(UserInfo[1][i]);
Users[i].setPhoneNumber(UserInfo[2][1]);

Lesson 4: Creating Classes 153


LESSON 4
6. Access getter methods to retrieve a. After the system output statement that
user details. prints the text Users who wanted
more information, insert two lines and
type, for (int j = 0; j < 3; j++)

See Code Sample 11.

b. To define the code block for the for


loop, insert a space and an open brace,
and then press Enter.

c. Insert a system output statement to print


text in a new line.

See Code Sample 12.

d. To access the list of methods of


UserDetails class, within the parenthe-
ses, type the name of the object
Users[j].

e. From the displayed list, select the


getName() : String - UserDetails option.

f. To add the rest of the text that needs to


be displayed in the output, type + "
wants a quote from the " +
Users[j].getDepartmentName() +
" department"

See Code Sample 13.

g. To print the users contact number in the


next line, type
System.out.println("Phone : " +
Users[j].getPhoneNumber() +
"\n");

See Code Sample 14.

h. Above the for loop, enter the single line


comment // Use getters to print
user details

See Code Sample 15.

Code Sample 11
System.out.println("OGC Home Improvement\n");
System.out.println("Users who wanted more information\n");

for (int j = 0; j < 3; j++)


Code Sample 12
System.out.println("OGC Home Improvement\n");

154 Java Fundamentals (Java SE 7)


LESSON 4
System.out.println("Users who wanted more information\n");

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


System.out.println();
}
Code Sample 13
System.out.println(Users[j].getName() + " wants a quote from the " +
Users[j].getDepartmentName() + " department");

Code Sample 14
for (int j = 0; j < 3; j++) {
System.out.println(Users[j].getName() + " wants a quote from the " +
Users[j].getDepartmentName() + " department");
System.out.println("Phone : " + Users[j].getPhoneNumber() + "\n");
}

Code Sample 15
// Use getters to print user details
for (int j = 0; j < 3; j++) {
System.out.println(Users[j].getName() + " wants a quote from the " +
Users[j].getDepartmentName() + " department");
System.out.println("Phone : " + Users[j].getPhoneNumber() + "\n");
}

7. Save and execute the program to a. Save and run the program.
verify the code entries.
b. Notice that the program displays the for-
matted output for information about
users. Then, close the project.

Lesson 4 Follow-up
In this lesson, you dened and overloaded methods and constructors in a Java class. By using
static methods, static variables, and command line arguments in your code, you can dene
functionality for your class to efficiently meet the needs of your application.
1. Which method would you choose for populating and assigning values to an object?
Answers will vary, but may include the following: If you have a constructor, then you
would prefer to assign values directly to the object. Another way would be by using a
JavaBean class where you assign values to an object by using the getter and setter meth-
ods of a JavaBean class and then assign values to it. If the variable is static, then you
would prefer to directly assign the values by calling the class name.
2. What factors do you think will influence your decision to overload a method or a con-
structor?
Answers will vary, but may include factors such as: defining methods that perform similar
functions on different object types, passing multiple arguments or different data types to
a method, and avoiding declaring multiple methods to perform similar functions to
increase the readability of code especially when you have multiple programmers working
on an application.

Lesson 4: Creating Classes 155


NOTES

156 Java Fundamentals (Java SE 7)


LESSON 5

LESSON 5 Lesson Time


5 hour(s), 30 minutes

Implementing Inheritance
In this lesson, you will write Java programs that reuse objects and their attributes.
You will:
Import a class.
Extend a class.
Override methods.
Create interfaces.
Implement interfaces.
Work with objects.

Lesson 5: Implementing Inheritance 157


LESSON 5
Introduction
In the previous lesson, you dened and overloaded methods to perform operations based on
different data types. There are instances where you might want to use an existing class to
inherit its methods rather than creating new functionalities. In this lesson, you will implement
inheritance for classes.
Some operations are common across classes. Instead of having to dene a method each time
you want to perform a required operation, Java allows you to either import or extend an exist-
ing class, thereby enhancing the functionality of a program.

TOPIC A
Import a Class
Java enables you to write programs that not only dene functionality in your programs, but
also reuse the code across applications. Java includes several well-dened classes that you can
use in your application to provide functionality. In this topic, you will import classes from
other packages.
There are instances where you might have to reuse an existing functionality of a class. A better
programming strategy would be to import a class rather than go about dening them. This
way, you also inherit the capabilities of a required class by importing the required package.

Import Declaration
Import Declaration Denition:
An import declaration is a Java statement that:
Allows the use of one or more classes from another package.
Is located at the top of the source code.
Uses the import keyword, followed by the location of the package using dot
notation.
Can import a single class using the class name, or all classes in a single-level
package using an asterisk ( * ).
Cannot be used to import partial class names.
Imports classes from a single-level only; subclasses must be imported explicitly.

Syntax: Import Declaration


An import declaration uses the following syntax for importing a single class:
import location.packageName.ClassName;
An import declaration uses the following syntax for importing all classes in a single-
level package:
import location.packageName.*;

158 Java Fundamentals (Java SE 7)


LESSON 5
Partial Class Names
Sometimes, there are situations where a class can contain many methods which impact
the performance of the system. In such instances, programmers create a number of
subclasses and distribute these methods among them. At runtime, these subclasses are
merged together and are treated as a single class. However, Java doesnt support the
implementation of partial class names.

Example:

Figure 5-1: An import declaration.

Program Speed
Importing all classes in a package will not slow down your program. The Java com-
piler loads only those classes that are specically used within your program.

Class Conicts During Importing


In most cases, once you import a class using single or package importation, you can
refer to that class by its name throughout your source code. However, if you import
two classes that have the same name, this will lead to ambiguity on which class to
call. In order to use classes with the same name, you need to include the qualied
name of the class, using the package name, dot notation, and class name. If you do not
use qualied class names, the Java compiler issues errors when attempting to compile
your code.

Class Path Structure


In order to use the classes and packages you create, the Java compiler must be able to
locate these classes and packages. If it is unable to locate the required le, the com-
piler issues an error that the class does not exist. To avoid compilation errors, all
packages and classes should reside in a le directory structure that matches their
names. The system class path variable tells the compiler where to locate classes. You
can alter the variable settings or use the Java classpath option during compilation
and execution to specify the path to locate classes and packages.

If the class names and packages are correct and compilation errors still state that a class does not
exist, the class path variable may be congured incorrectly.

You can view a list of Java options and their usage by entering javac at the command prompt.

Lesson 5: Implementing Inheritance 159


LESSON 5
How to Import a Class
Procedure Reference: Import a Class
To import a class:
1. In the Text Editor, on the rst line of source code, or on the second line if there
is a package declaration, insert the import keyword.
2. Using the dot notation, state the location of a package name and corresponding
class name.
3. If necessary, using an asterisk, import all classes from a package.

ACTIVITY 5-1
Importing the DepartmentType Class for the Kiosk
Application
Data Files:
Kiosk_5A.jar

Before You Begin:


Import the C:\085664Data\Implementing Inheritence\Kiosk_5A.jar project into the Eclipse IDE.

Scenario:
While reviewing the source code for the Kiosk application, your colleague reorganized the les
within the directory. She placed the DepartmentType.class le in a new directory structure, but
missed updating the source code to reference the les from the new location. Therefore, your
program displays error messages when executed. You decide to retain the new directory struc-
ture and modify the code, so that it references the source les from the new location.

160 Java Fundamentals (Java SE 7)


LESSON 5
What You Do How You Do It

1. Update code to reference the source a. Display the source code of the Kiosk_
file from a different package. 5A.java file.

b. In the first line of the source code, insert


the import keyword.

c. To specify the classes from which the


source code needs to be imported, insert
a space and type
com.ogc.home.kiosk.DepartmentType;

See Code Sample 1.

Code Sample 1
import com.ogc.home.kiosk.DepartmentType;

public class Kiosk_5A {

public static void main(String[] args) {

2. Save and run the program to verify a. Save the file and execute the program.
the output.
b. Notice that the information on the depart-
ments is displayed correctly. Then, at the
prompt, input 4

c. Notice that department description is dis-


played correctly. Then, input 0

d. Close the project.

Lesson 5: Implementing Inheritance 161


LESSON 5
TOPIC B
Extend a Class
In the previous topic, you imported a class to access the functionality of your application. In
certain circumstances, you may need to extend attributes and methods of one class in conjunc-
tion with another class. In this topic, you will extend a class.
It is always easier and more efficient to reuse the functionalities of an existing class rather than
creating new ones. Java allows you to extend a class so that you can access only the attributes
of that class rather than having them dened each time.

Inheritance
Inheritance is the act of a class embodying methods and attributes dened in its parent class.
An inheritance hierarchy is set for all classes and packages provided by the Software Develop-
ment Kit (SDK). However, you can create a separate inheritance hierarchy associated with
your own classes, or by extending SDK classes. After inheritance is established, a child or sub-
class incorporates the parent or superclasses methods and attributes, apart from adding its
own. You only need to dene the additions to the subclass and superclass.

Encapsulation
Encapsulation means hiding sensitive data and displaying only the information that is
necessary for the user. It refers to the implementation of public get and set methods to
indirectly and safely manipulate private attributes of an object. Data hiding is an
object-oriented programming (OOP) concept where some data elds are hidden from
other objects.
In inheritance, to refer to a specic implementation of an object in an original class,
you must use the qualied name of an object. Without the qualied object name, spe-
cic instances are hidden within the original class. This allows you to reuse objects as
often as needed. By default, if a class doesnt extend another, it extends the
java.lang.Object class.

You can inherit only one class and multiple inheritance is prohibited in Java.

Is-A and Has-A Relationships


Often, inheritance is referred to as an Is-A relationship. The Is-A relationship refers to
how an object of an inheriting class is a member of the class it is inherited from. Con-
versely, a Has-A relationship looks at the relationship between the class and object
from a different perspective: A class has an object that is a member of another class.

Subclass and Superclass


Subclass and Superclass Denition:
A subclass is a class that:
Inherits all properties of a superclass.
Is declared with the extends keyword and the superclass name following its
name.

162 Java Fundamentals (Java SE 7)


LESSON 5
Can access superclass members using the same name as its members with the
super keyword and dot notation.

Syntax: Subclass and Superclass


A subclass and superclass declaration uses the following syntax:
class SuperClass {...}

class SubClass extends SuperClass {...}

Attributes and Methods Inherited by the Subclass


A subclass cannot inherit members from a superclass, if the members are dened with
the same name in both the subclass and superclass. The inherited members can have
multiple forms within the subclass and superclass, which is referred to as the class-
type. In Java, three types of access speciers are used: public, protected, and no
specier.

Access Specier Description


public A subclass inherits all members of a superclass that are declared
public. If a class is declared public, all its properties can be
accessed by all other subclasses.
protected A subclass inherits all members of a superclass that are declared
protected. If a class is declared protected, its members are
accessible by an immediate subclass.
No specier Members with no modiers are also inherited by a subclass, as
long as they are within the same package.

Example:

Figure 5-2: A subclass and superclass.

Lesson 5: Implementing Inheritance 163


LESSON 5
Access Modiers
Access modiers are used to dene access to methods and properties of a superclass from a
subclass. The modier is placed at the beginning of a member denition in a class declaration.
The four access modiers in Java are public, protected, private, and
package-private.

Access Modier Description


public Accessible anywhere a class.
protected Accessible in subclasses, in classes residing within the same package, and
in the class in which it is dened.
private Accessible only within a class in which it is dened.
package-private Accessible only within the package where it is declared.
package-private is the default access modier.

How to Extend a Class


Procedure Reference: Extend a Class
To extend a class:
1. In the Text Editor, state an access modier.
2. Insert the class keyword and declare a subclass name.
3. Insert the extends keyword and state a superclass name.
4. If necessary, state a superclass constructor.

ACTIVITY 5-2
Extending the StoreItem Class
Data Files:
Kiosk_5B.jar

Before You Begin:


Import the C:\085664Data\Creating Classes\Kiosk_5B.jar project into the Eclipse IDE.

Scenario:
Your colleague added three paint items to your kiosk program. These items are color, nish,
and quantity with output statements to display these items. She also created a new class for the
StoreItem. However, before going on vacation, she did not have a chance to create the
PaintItem class, which the kiosk application uses to associate the store items and the
instances of the items.

164 Java Fundamentals (Java SE 7)


LESSON 5
What You Do How You Do It

1. Create a PaintItem class that a. In the Kiosk_5B project, in the src folder,
extends the StoreItem class. select the com.ogc.home.kiosk package.

b. Click the New drop-down arrow, and from


the displayed list, select Class.

c. In the New Java Class dialog box, in the


Name field, type PaintItem

d. In the Superclass section, click Browse.

e. In the Superclass Selection dialog box, in


the Choose a type field, type
com.ogc.home.

f. In the Matching items list box, select the


StoreItem option and click OK.

g. In the New Java Class dialog box, click


Finish.

2. Declare variables to store informa- a. Position the cursor in the PaintItem sub-
tion in PaintItem objects. class, insert a new line and type the single
line comment // Define variables
to store information on paint
items

b. In the next line, declare the paintColor


variable of String data type.

c. Similarly, in the next two lines, declare


paintFinish and paintQuantity vari-
ables of String data type.

See Code Sample 1.

Code Sample 1
// Define variables to store information on paint items
String paintColor;
String paintFinish;
String paintQuantity;

Lesson 5: Implementing Inheritance 165


LESSON 5
3. Declare a constructor for the a. Insert two new lines and then type
PaintItem class. public PaintItem ()

b. To specify the first three arguments for


the constructor, within the parentheses,
type String strItemName, double
dPrice, String strDepartment,

c. To specify the next three arguments for


the constructor, insert a new line and
type String paintColor, String
paintFinish, String
paintQuantity

d. To define the code block for the construc-


tor, insert a space and an open brace, and
then press Enter.

4. Instantiate variables of the a. Add the single line comment // Call


superclass StoreItem. the superclass (StoreItem)
constructor

b. To pass data to instantiate the


superclasss variables, insert a new line
and type super(strItemName,
dPrice, strDepartment);

5. Instantiate instance variables of the a. Insert two new lines and enter the single
PaintItem class. line comment // Instantiate
instance variables

b. To instantiate paintColor to the passed


value, insert a new line and type
this.paintColor = paintColor;

c. Similarly, instantiate paintFinish and


paintQuantity to the passed values.

See Code Sample 2.

Code Sample 2
// Instantiate instance variables
this.paintColor = paintColor;
this.paintFinish = paintFinish;
this.paintQuantity = paintQuantity;

166 Java Fundamentals (Java SE 7)


LESSON 5
6. Declare a get method to return infor- a. After the close brace of the constructor
mation from the PaintItem class method, insert two new lines, and declare
and its superclass. getDescription() as a public method
to return a String value.

b. To specify the code block for the method,


insert a space, open brace, and then press
Enter.

c. Declare the paintDescription variable


as a String data type.

d. To retrieve and store information from


the superclass, insert a new line and type
paintDescription =
super.getDescription()

e. To store additional information, insert +


and press Enter.

f. To format and store information from the


instance variable in the
paintDescription variable, type
"\t" + paintColor + "\t" +
paintFinish + "\t" +
paintQuantity;

See Code Sample 3.

g. To return the value stored in the


paintDescription variable, in a new
line, type return paintDescription;

h. Save the PaintItem.java file.

Code Sample 3
String paintDescription;
paintDescription = super.getDescription() +
"\t" + paintColor + "\t" + paintFinish + "\t" + paintQuantity;

Lesson 5: Implementing Inheritance 167


LESSON 5
7. Save and run the program to verify a. Display the source code of the Kiosk_
the code entries. 5B.java file.

b. Execute the program.

c. At the prompt, input 1

d. Notice that the details of the Paint


department are displayed. Then, input 0

e. Close the project.

TOPIC C
Override Methods
In the pervious topic, you extended a class and explored the subclass and superclass hierar-
chies. Java allows you to access constructors, methods, and elds of other classes. Also, Java
allows you to redene existing members of a class while inheriting some of the characteristics
of that class. The same is true with methods of an inherited class. In this topic, you will over-
ride methods.
When writing code to create subclasses, you need to work with previously dened structures.
Through the extension of classes, you are empowered with an ability to redene those methods
that do not t your subclass needs. The same holds true for methods, through method overrid-
ing. You can program more efficiently by redening an already created object.

Method Overriding
Method Overriding Denition:
Method overriding is a technique that:
Creates a method in a subclass to replace a dened superclass method.
Uses the same name, return type, and arguments as the original method.
Can allow more access than a superclass method.
Ensures that abstract methods are overridden or the subclass itself is declared as
abstract.
Abstract methods of a superclass must be overridden or the subclass itself must be
declared as abstract. However, methods declared as nal and static in a superclass can-
not be overridden.

Syntax: Calling an Overridden Method


If the return type of a method is different than its subtype, the Java compiler would
produce a compilation error. Calling an overridden method of a superclass uses the
following syntax:

168 Java Fundamentals (Java SE 7)


LESSON 5
super.overriddenMethod( );

Example:

Figure 5-3: Overriding a method.

How to Override Methods


Procedure Reference: Override Methods
To override a method:
1. In the Text Editor, state a superclass.
2. Dene a method for a superclass.
3. Declare a subclass.
4. In the subclass, dene a method with the same signature as the method in your
superclass.

Lesson 5: Implementing Inheritance 169


LESSON 5
ACTIVITY 5-3
Override a Method in the PaintItem Class
Data Files:
Kiosk_5C.jar

Before You Begin:


Import the C:\085664Data\Implementing Inheritence\Kiosk_5C.jar project into the Eclipse IDE.

Scenario:
After reviewing the kiosk application, your manager notes that the price for the paint items
does not include the 10 percent tax. You do not want to change the structure of the
StoreItem class, because other departments also inherit from the same class. You plan to
override the superclass method that returns the price in a string format to include the tax when
computing the price.

What You Do How You Do It

1. Define a variable to store the tax a. Display the PaintItem.java file.


percentage.
b. To access methods to format the number,
click after the statement that lists the
package details, insert two new lines, and
import the NumberFormat class from the
Java library.

See Code Sample 1.

c. After the statement that declares the


paintQuantity variable, insert a line
and type static double tax=0.1;

Code Sample 1
package com.ogc.home.kiosk;

import java.text.NumberFormat;

170 Java Fundamentals (Java SE 7)


LESSON 5
2. Override the getFormattedPrice a. After the close brace of the
method to return the price after getDescription() method, insert two
including the tax. new lines and type public String
getFormattedPrice()

b. After the close parenthesis, insert a


space, open brace, and then press Enter.

c. To instantiate the variable


currencyFormat, type NumberFormat
currencyFormat =
NumberFormat.getCurrencyInstance();

d. To return the price in String format,


insert a new line and type return
(currencyFormat.format(super.getPrice()));

e. To add the tax percentage to the price,


click after the super.getPrice()
method and type +super.getPrice()
*tax

See Code Sample 2.

f. Save the PaintItem.java file.

Code Sample 2
return (currencyFormat.format(super.getPrice()+super.getPrice()*tax));

3. Execute the program to verify the a. Display the source code of the Kiosk_
code entries. 5C.java file.

b. Execute the program.

c. At the prompt, input 1

d. Verify that the price includes the 10 per-


cent tax and then input 0

e. Close the project.

Lesson 5: Implementing Inheritance 171


LESSON 5
TOPIC D
Create Interfaces
In the previous topic, you overrode methods of a superclass. However, these techniques work
strictly with methods of a single class. You may want to use capabilities of more than one
class. In this topic, you will create interfaces of abstract methods.
When working with inheritance in Java, a class may only extend one other class. There may
be situations when your programming requirements call for reusing functionality from multiple
sources. Instead of working with class extensions, Java provides for multiple inheritance
through interfaces. Without using interfaces, you will be required to write more code than nec-
essary to achieve the same functionality.

Interfaces
Interfaces Denition:
An interface is a Java code element that:
Contains a collection of method signatures with no code statements.
Can have only public members.
Is declared with the interface keyword.
Can contain constant variables, which are public, static, and nal by default.
Can extend other interfaces using the extends keyword and the super-interface
name.
Cannot contain instances of itself.

Syntax: Interface Declaration


An interface declaration uses the following syntax:
interface InterfaceName extends SuperInterfaceName { }

Example:

Figure 5-4: An interface declaration.

172 Java Fundamentals (Java SE 7)


LESSON 5
Java-Dened Interfaces
The Java SDK contains some predened interfaces. These interfaces have been
designed to cover some common actions performed when creating applications in Java.
Some of the interfaces available in Java are Iterator, Set, Map, and List.

Native Interface
A native interface is a Java interface containing methods used to invoke native meth-
ods, or methods from programming languages other than Java. The methods residing in
an interface use the native keyword included in the method denition. The interface
includes mapping between Java primitive and object types and their corresponding
native types. Using the Native interface ensures that Java can locate and execute
native methods within Java source code.

Abstract Methods
Denition: Abstract Methods
An abstract method is a method that:
Contains no method body.
Is declared with the abstract keyword.
May be dened only within interfaces or abstract classes.
Cannot be declared as nal or private.
Need not be implemented if a subclass is declared as abstract.

Example:

Figure 5-5: An abstract method.

Lesson 5: Implementing Inheritance 173


LESSON 5
Abstract Classes
An abstract class, like an abstract method, is used to represent a general concept, and
can only be used as a superclass. For example, while you do not see instances of
equipment, you do have instances of printers and monitors as items within equipment.
To that effect, while abstract classes can contain constructors and methods, they cannot
be instantiated. Attempting to instantiate an abstract class results in a compilation error.
Abstract classes are declared with the abstract keyword, and the items dened
within an abstract class are used by its subclasses.

Instead of creating an abstract class that contains only abstract methods, you can create it as an inter-
face.

How to Create Interfaces


Procedure Reference: Create Interfaces
To create interfaces:
1. In the Text Editor, insert the interface keyword.
2. Declare an interface name.
3. In the interface body, declare interface methods and/or constants.

ACTIVITY 5-4
Creating an Interface for the Kiosk Application
Data Files:
Kiosk_5D.jar

Before You Begin:


Import the C:\085664Data\Implementing Inheritence\Kiosk_5D.jar project into the Eclipse IDE.

Scenario:
Your colleague reviewed the kiosk application and suggested that the application provide simi-
lar information for each department. You decide to create an interface that lists the methods
that the classes for each department need to provide.

174 Java Fundamentals (Java SE 7)


LESSON 5
What You Do How You Do It

1. Create an interface. a. In the Kiosk_5D project, in the src folder,


select the com.ogc.home.kiosk package.

b. Click the New drop-down arrow, and from


the displayed list, select Interface.

c. In the New Java Interface dialog box, in


the Name field, type DepartmentItems
and click Finish.

2. Define abstract methods in the inter- a. Click after the open brace of the
face. DepartmentItems interface declaration
and insert two lines.

b. To declare an abstract method, type


public String getDescription();

See Code Sample 1.

c. Save the file.

d. Close the project.

Code Sample 1
public interface DepartmentItems {

public String getDescription();

Lesson 5: Implementing Inheritance 175


LESSON 5
TOPIC E
Implement Interfaces
In the previous topic, you created interfaces and dened abstract methods. The next step is to
write code to use interface methods in your application. In this topic, you will implement inter-
faces.
By creating interfaces, you add functionality to your code while creating efficiency in program-
ming. However, it is not enough to simply create an interface. With Java, you must write code
to specically implement the interfaces. Otherwise, you have just written extra code that is not
used in your program.

Interface Implementation
Interface Implementation Denition:
Classes implement interfaces by using the implements keyword followed by the
interface name after the class declaration. A class can implement more than one inter-
face, separated by commas. A class implementing an interface can refer to interface
objects using an object name, but it is required to employ all methods contained in the
interface or its super-interfaces. When used, interface methods must retain the same
signature indicated in the interface.

Example:

Figure 5-6: An interface implementation.

Inheritance Rules
An important rule in inheritance is that a class can access constants dened in an inter-
face, only if it implements the interface. Constants in an interface can be referenced
not only by inheritance, but also using the interfaceName.variableName syn-
tax. A concrete class can extend only one superclass. The concrete class implements all
abstract methods of the interface.

176 Java Fundamentals (Java SE 7)


LESSON 5
Writing Method Implementation
All methods dened in an interface are abstract. The methods are usually implemented
by a class that implements the interface. These methods are dened using the
abstract modier and do not have a body; instead statements are terminated using
a semicolon. An interface can be used to implement similar methods present in differ-
ent classes. All methods in an interface must be implemented in the class that
implements an interface, or else it results in a compilation error.

How to Implement Interfaces


Procedure Reference: Implement Interfaces
To implement interfaces:
1. Open the desired source code le.
2. If necessary, in the source code, insert access modiers.
3. State a class name that will implement the interface.
4. Insert the implements keyword.
5. State an interface name.
6. Provide method implementations for each interface method.

ACTIVITY 5-5
Implementing an Interface for the Kiosk Application
Data Files:
Kiosk_5E.jar

Before You Begin:


Import the C:\085664Data\Implementing Inheritence\Kiosk_5E.jar project into the Eclipse IDE.

Scenario:
After you have created the interface, you decide to implement it to make it mandatory for the
classes to provide at least the basic minimum functionality. Therefore, you decide to imple-
ment the interface in the class that describes the products of a department.

Lesson 5: Implementing Inheritance 177


LESSON 5
What You Do How You Do It

1. Modify the PaintItem class to a. Display the PaintItem.java file.


implement methods defined in the
interface.
b. In the PainItem class declaration state-
ment, click after the superclass
StoreItem insert a space and type
implements DepartmentInfo

See Code Sample 1.

c. Save the PaintItem.java file.

Code Sample 1
public class PaintItem extends StoreItem implements DepartmentInfo {

2. Execute the program to verify code a. Display the source code of the Kiosk_
entries. 5E.java file.

b. Execute the program.

c. At the prompt, input 1

d. Verify that the information about the


Paint department is displayed and then
input 0

e. Close the project.

178 Java Fundamentals (Java SE 7)


LESSON 5
TOPIC F
Work with Objects
In the previous topic, you implemented interfaces in Java. There are various functions that can
be performed on known objects. In this topic, you will work with objects.
How would you work with an object if you did not know what class that object belonged to?
By employing casting methods, you can nd out the class of an object. Determining the class
of an object is particularly useful when working with methods that may extend functionality if
passed to an object of a particular type.

The Equals Method


Denition: The Equals Method
The equals method is a Java method that:
Compares two objects for value equality.
Tests each character within the strings.
Returns a boolean value depending on the result of comparison.
Uses a standard method call.

Syntax: The Equals Method


The equals method is implemented in various classes, including the String class.
The syntax for using the equals method is as follows:
object1.equals(object2)

Example:

Figure 5-7: The equals method.

Equality Operator vs. Equals Method


When used with primitive types, an equality operator ( == ) performs the same func-
tion as an equals method. However, this does not hold true when pairing the equality
operator with String objects. Instead, when used with objects, the equality operator
checks to see if two objects refer to the same memory location.

Lesson 5: Implementing Inheritance 179


LESSON 5
The Instanceof Operator
The Instanceof Operator Denition:
The instanceof operator is a Java operator that:
Determines the class of an object.
Uses the instanceof keyword.
Uses an object of an unknown class.
Uses a class to compare the object with.
Evaluates to true if the object is an instance of the stated class or any subclass.

Syntax: The Instanceof Operator


The syntax of the instanceof operator:
boolean x = objectName instanceof ClassName;

Example:

Figure 5-8: The instanceof operator.

Object Casting
Object Casting
Casting objects converts an object of a class to an object of another class. You can only cast
objects that are related, such as a class and its subclass. Casting objects does not affect the
original object. Explicit object casting allows the use of superclass objects for subclass objects.
Without explicit object casting, you lose information and will be unable to employ subclass
methods and variables. Explicit object casting is performed by placing a destination class
within parentheses before the reference to a source object.

180 Java Fundamentals (Java SE 7)


LESSON 5

Figure 5-9: An explicit object casting.

How to Work with Objects


Procedure Reference: Compare Objects
To compare objects:
1. Open the desired source code le.
2. In the source code, call the equals method on the rst object to be compared.
3. As a parameter to the equals method, enter the name of a second object to be
compared.

ACTIVITY 5-6
Comparing Objects in the Kiosk Application
Data Files:
Kiosk_5F.jar

Before You Begin:


Import the C:\085664Data\Implementing Inheritence\Kiosk_5F.jar project into the Eclipse IDE.

Scenario:
After reviewing the current kiosk functionality, your manager wants a message to be displayed
when a user selects the Paint department stating that they are already in the Paint department.
To include this functionality, you decide to compare the selected entity with the Paint depart-
ments name.

Students can do this activity


individually or as a group.

Lesson 5: Implementing Inheritance 181


LESSON 5
What You Do How You Do It

1. Insert code to compare the depart- a. Display the source code of the Kiosk_
ment name to the selected 5F.java file.
departments object.
b. In the switch statement, in the case
'1' code block, after the statement that
appends the text department to the
string buffer variable sbMessage, insert
a new line and enter the single line com-
ment // Display a message when
the user selects the Paint
department

See Code Sample 1.

c. In the next line, enter an if statement.

d. To compare the Paint department with


the name of the selected object, within
parentheses, enter the test expression
selectedDepartment.equals("PAINT")

See Code Sample 2.

Code Sample 1
sbMessage.append(" department\n");
// Display a message when the user selects the Paint department
Code Sample 2
// Display message when the user selects the Paint department
if (selectedDepartment.equals("PAINT"))

2. Add a message to the sbMessage a. To define the code block for the if state-
variable if the selection is the Paint ment, after the close parenthesis, insert a
department. space, open brace, and then press Enter.

b. To add a message when the Print depart-


ment is selected, type
sbMessage.append("You are
already in the PAINT
department\n");

182 Java Fundamentals (Java SE 7)


LESSON 5
3. Save and run the program to verify a. Save the file and execute the program.
the output.
b. At the prompt, input 1

c. Notice that the message You are already


in the PAINT department is displayed and
then input 3

d. Notice that the message indicating that


you are already in the Paint department is
not displayed and then input 0

e. Close the project.

Lesson 5 Follow-up
In this lesson, you imported and extended classes, and reused objects. By importing and
extending the class, you also inherit its methods thereby enhancing the functionality of the pro-
gram by reusing already available functionality.
1. Why would you want to extend classes when creating a Java program?
Answers will vary, but may include: extending classes to define attributes and methods a
class should inherit, hide, or override; reusing code that defines methods in a class; and
reduce the development time because the objects needed are already defined.
2. Why is it useful to determine the class of an object?
Answers will vary, but may include: determining the class of an object can be particularly
useful when performing operations with methods that can perform more robustly if they
were passed an object that extended a particular type. In addition, determining a class is
essential when you come across situations where objects stored in a list are accessed by
more than one class to know the class of an object so as to access the object. In this case,
you might use the instanceof operator to determine the class of an object. Another
reason why it is useful to determine the class of an object is that you may use it to check
to see if a particular class is a subclass of another class.

Lesson 5: Implementing Inheritance 183


NOTES

184 Java Fundamentals (Java SE 7)


LESSON 6

LESSON 6 Lesson Time


1 hour(s), 30 minutes

Representing OOP
Concepts Using UML
In this lesson, you will represent OOP concepts using UML.
You will:
Introduce UML.
Apply UML.

Lesson 6: Representing OOP Concepts Using UML 185


LESSON 6
Introduction
In the previous lesson, you imported and extended classes, and reused objects. These classes
and reused objects can be represented in UML for better understanding of their roles in an
application. In this lesson, you will represent OOP concepts using UML.
As a developer, you have to understand the technical requirements of your client to build an
application. It is a tedious task to visualize functions even before creating them. Just like an
architect who uses a three-dimensional (3D) model of a building for visual representation, a
software developer uses UML for visual representation of the system design.

TOPIC A
Introduction to UML
By now, you would have written several programs in Java. An easier and interesting way to
understand the requirements before you start coding for an application is to represent the vari-
ous elements in a system diagrammatically. In this lesson, you will be introduced to UML.
There are no restrictions when using the UML tool during a system design. UML contains
various diagrams that might help developers to better understand the system design in any
stage of software development.

UML
The Unied Modeling Language (UML) is a language that:
Enables diagrammatic representation of the structure and functionality of software sys-
tems.
Is static when representing the structural aspect of a software system.
Is dynamic when representing the behavioral aspect of the software system.
Is used in all phases of software development.

Types of UML Diagrams


UML diagrams are classied into various types based on what they represent.

UML Diagram Type Used To


Use case diagrams Represent the interaction between a user (also known as an actor) and a
software system. The user in a system can interact with several use cases
which can be related to the functionality or business use of the software
system. Use cases can be dependent on or can derive from each other.
For example, when use case 1 is dependent on use case 2, it is represented
as use case 1 uses use case 2 in UML. Likewise, when use case 1 derives
from use case 2, it is represented as use case 1 extends use case 2.
Sequence diagrams Represent the sequence and ow of activities when implementing a use
case. It usually involves depicting the ow of activities between actors and
use cases with respect to time.

186 Java Fundamentals (Java SE 7)


LESSON 6
UML Diagram Type Used To
Class diagrams Represent all classes and their relationships in a software system. A class
diagram is a static representation of the object-oriented design of a software
system.
Object diagrams Represent the software systems state at a particular instance. It is a static
representation that is derived from the class diagram. While the class dia-
gram is a representation of the software system at a higher level, the object
diagram is a representation of the software system at a deeper level depict-
ing relations between instances or objects of a class.
State transition diagrams Represent the different states of transition of an object in a software system.
It is a dynamic representation that depicts the changing states of an object
and its corresponding behavior during each state. It depicts the life cycle of
an object from the time of object creation to the time it is destroyed in the
software.
Activity diagrams Represent a detailed ow of a specic activity in a software system. The
diagram includes the business logic, alternative options of performing cer-
tain tasks, and any deviations in the activity ow.
Deployment diagrams Represent how a software will be physically deployed to different client
server environments that may include multiple servers.
Communication diagrams Represent the communication between different objects in a software sys-
tem. It is similar to the sequence diagram, and shows the communication
between different objects in the software system.

Class Diagrams
Denition: Class Diagrams
A class diagram is a type of UML diagram that:
Is used to represent different classes and their relationships in a software system.
Is a static representation that provides a top-level view of the software system
with attributes and behaviors outlined for each class.
Represents a class in the form of a rectangle with three rows containing the name,
attributes, and methods of the class.

Lesson 6: Representing OOP Concepts Using UML 187


LESSON 6
Example:

Figure 6-1: A class diagram in UML.

UML Representation for Java Classes


UML Representation for Java
UML provides four mechanisms that enable you to represent software systems in an effective
Classes manner.

Mechanism Description
Specications Provides a textual description for the graphical notations of a software system.
While the graphical notation may not be able to describe attributes, methods, and
method declarations effectively, textual specications will ensure that a complete
description is provided.
Adornments Provides additional information about a software system to highlight specic
characteristics of its elements, with the help of special symbols.
For example, a class is represented with a rectangle containing several rows that
will list the name, attributes, and methods. However, information to specify that
the class is abstract, and its properties are public, private, or protected, and is
done using adornments.
Common Divisions Represents designs in UML on the basis of two conceptsclassier and instance,
and interface and implementation. The classier and instance concept is similar to
a class and its objects relationship. While the class is an abstract representation,
the object is derived from the abstract form of the class to represent its specic
instance. The interface and implementation concept represents the what and how
relationships in a software system. While the interface is a framework depicting
what a component in the system is capable of, the implementation shows how the
capability is implemented by the component.

188 Java Fundamentals (Java SE 7)


LESSON 6
Mechanism Description
Extensibility Enables the UML to be exible and extend its capabilities according to changing
Mechanism needs during software development. It is governed by three features.
Constraints: Used to add new rules to a particular element of the software
system to extend its capabilities.
Tagged values: Used to add new ad hoc properties to an existing element to
suit your needs.
Stereotype: Used to create a new element derived from an existing element in
the system to suit your needs.

OPTIONAL ACTIVITY 6-1


Introducing UML
Scenario:
As a Java programmer, you are involved in the development of a web application. Before
starting to write code, you must understand the requirements and represent the various ele-
ments in a software system diagrammatically.

1. Which extensibility mechanism allows the user to create a new element based on the
existing element?
a) Stereotype
b) Tagged value
c) Constraint
d) Adornment

2. Which UML diagram is used to represent the relation between the user and the system
environment?
a) Sequence diagram
b) Use case diagram
c) Class diagram
d) Object diagram

3. True or False? An arrow with an enclosed triangle means encapsulation and an arrow
with the closed triangle means polymorphism.
True
False

Lesson 6: Representing OOP Concepts Using UML 189


LESSON 6
TOPIC B
Apply UML
In the previous topic, you were introduced to the basic concepts in UML. The UML tool helps
in visually representing complex concepts which can include relationship classes and their
objects. In this topic, you will apply UML to represent object-oriented programming (OOP)
concepts.
Object-oriented programs contain complex relationships between classes and their correspond-
ing objects. To visualize and write code for software systems implementing OOP requires a
programmer to invest a lot of time and effort. Representing the relationships, functionality, and
other features of a software system using UML makes it easier for programmers to understand
the software system better and thereby write code efficiently to implement the required func-
tionality.

UML Notations
UML diagrams use six different notations to represent each element in a software system.

Element Represented As
Class A rectangle with three rows, where the top row lists the name, the middle row lists
the attributes, and the bottom row lists the methods of a class. It can also include an
additional row to represent additional characteristics of the class. Active classes
dene the ow of a system and are represented with a thick border.
Object A rectangle with three rows that is similar to the class notation. However, the rst
row contains the name of the object, instead of a class name. The class name
appears with an underline.
Use case An ellipse with the name of the use case mentioned within it.
Actor A stick gure that indicates internal or external entities of a system. These entities
may play the role of a client for other entities.
Node An element present during runtime. It is represented with a cuboid symbol.
Association A line with numbers or symbols next to it to represent the different forms of associa-
tion.
A straight line with numbers such as 1, 0..1, *, 0..*, 1..* represents the multiplic-
ity of a class with only one, zero or one, many, zero or many, one or many
instances, respectively.
An arrow with a diamond symbol at the end represents aggregation between
classes.

UML for OOP Concepts


Unied Modeling Language (UML) is used to represent object-oriented programming (OOP)
concepts with the help of specic symbols and notations.

190 Java Fundamentals (Java SE 7)


LESSON 6
OOP Concept Description
Inheritance Represented as a line with a pointed unlled arrow joining a child class to its parent
class. This is also referred to as a generalization arrow.
Interface Represented as a dotted line with a pointed unlled arrow joining an object to the
interface it is implementing. An interface can be represented as a rectangle or as a
circle. When represented as a circle, it does not specify any properties of the interface
and there is just a line joining the interface to the object that is implementing it.
Polymorphism Represented as a line with a pointed unlled arrow joining the subclass or object dis-
playing polymorphism to its parent class.
Abstraction Abstract classes are represented in italic font style.
Encapsulation Each access modier has its sign that is placed before the name of the attribute or
method. Common access modiers and their representations are:
public represented by a +.
protected represented by a #.
package-private represented by a ~.
private represented by a -.

ACTIVITY 6-2
Understanding UML
Scenario:
You are in the process of developing the web application using OOP concepts. While working
on the code, you need to represent certain complex concepts that include the relationship
between classes and their objects.

1. What does each of these UML representations stand for?


a A generalization arrow a. Inheritance
c A rectangle or a circle b. Abstraction
d A line with a pointed c. Interface
unlled arrow
b An italicized name d. Polymorphism

2. Which UML notation is used for representing a class?


a) A rectangle with three rows where each row stands for the class name, attributes,
and method names, respectively.
b) A rectangle with three rows where each row stands for the object name, list, and
attributes, respectively.
c) An ellipse with a use case name.
d) A cuboid symbol.

Lesson 6: Representing OOP Concepts Using UML 191


LESSON 6
Lesson 6 Follow-up
In this lesson, you represented OOP concepts using UML. Drawing UML diagrams for your
application will help you to understand requirements and implement complex functionality in
your application easily.
1. How do you think the knowledge on UML will help a user while developing an applica-
tion?
Answers will vary, but may include for a developer to create an application, it is essential
to understand the functionality and complexity of the application before writing code;
UML diagrams provide developers with a diagrammatic representation of a software sys-
tem which will help them to understand the requirements easily and create their
application in no time; also, UML has become an integral part of the development process
in most organizations and is easy to understand and is the most sought-after modeling
language when creating a complex application.
2. Which type of UML diagram would you prefer to represent your system design?
Answers will vary, but may include: you prefer to use class diagrams to represent the
interaction between a user and the environment; choose the class diagram where you
would like to show the relationship between classes and their attributes; or choose to
represent your application using an activity diagram, in case you would like to depict a
detailed flow of a specific activity in a software application.

192 Java Fundamentals (Java SE 7)


LESSON 7

LESSON 7 Lesson Time


2 hour(s), 15 minutes

Identifying Client-Side
Technologies
In this lesson, you will identify client-side technologies.
You will:
Identify client-side technologies.
Describe thin UI clients.
Describe fat UI clients.
Describe micro UI clients.

Lesson 7: Identifying Client-Side Technologies 193


LESSON 7
Introduction
In the previous lesson, you illustrated object oriented concepts using UML not only for better
understanding of user and business requirements, but also for breaking down complex func-
tionality in an application for easy understanding. There are many types of applications that
can be illustrated using UML. It is important to be aware of these applications to understand
UMLs representation in these applications. In this lesson, you will learn about client-side
technologies.
To submit data for a survey, you may have some formalities such as lling out the survey form
or questionnaire. Checking the information on the form or questionnaire after receiving it from
users may be tedious and time consuming. Client-side tools check for the validity of informa-
tion entered on a form or questionnaire before it is submitted, thereby helping you save effort
and time.

TOPIC A
Introduction to Client-Side
Technologies
Java enables you to develop programs that work in applications based on the client-server
architecture. When coding for programs that run in such environments, you need to be aware
of the specic capabilities and limitations of each technology. In this topic, you will examine
client-side technologies.
You have designed an application and shared it with your peers in your developer network.
The application has become popular and you want to release it to the public. This application
is currently running on your server, and you do not want to port it as a stand-alone application.
But, you want the application to be responsive to user inputs as well as keep the load on the
server to a minimum. A better understanding of various client technologies will help you to
choose the appropriate type of technology that provides both the secure and efficient transfer of
required data across the network.

Client-Side Technologies
A client-side application, in a clientserver architecture, is the software connected to a server
across a network. A client-side application is any software that runs on the users local
machine and accepts user requests. Processing a user request takes place at the server. Some-
times, the client-side application includes basic-level processing of data. Such processing
would reduce the amount of traffic in the network and enable the server to be more responsive.

Types of Client-Side Technologies


Client-side technologies are grouped into three major types: thin clients, fat clients, and micro
clients.

194 Java Fundamentals (Java SE 7)


LESSON 7
Client-Side Technol-
ogy Description
Thin client A thin client depends on a server for all its business logic and data. Thin clients
are sometimes referred to as slim clients or lean clients. When using thin cli-
ents, it is sufficient if only the server is secured against any external attacks
because no data is stored on the local machine. A disadvantage of this type of
technology is that an attack on the sever would affect all clients dependent on
it. A thin client offers better exibility and manageability of accessing the soft-
ware components in a network.
Fat client A fat client is designed to make specic decisions of its own to perform a bulk
of operations but needs to connect to a server periodically. The resources or the
software components are installed on the local machine. It is sometimes
referred to as a thick client, heavy client, or rich client. Examples of fat clients
would be Applets that can run without any server support. They were popular
in the past because their user interface and application settings can be custom-
ized to suit the users preferences and also offer good multimedia support
features and a high performance. An advantage they provide to programmers
includes complete control over the programs installed.
Micro client A micro client, or a hybrid client, is a combination of features of thin and fat
clients. Similar to a fat client, micro clients process data on the local machine.
However, the processed data is stored and retrieved from a server. It uses the
best features of both types of clients:
Performance and multimedia support featuresexhibited by the fat client.
Security, manageability, and exibilityexhibited by the thin client.

ACTIVITY 7-1
Introducing Client-Side Technologies
Scenario:
The project you are currently working on requires you to develop programs that work in appli-
cations based on the client-server architecture. You are required to have an understanding of
the capabilities and limitations of using this technology.

1. Which one of the following is not a client-side technology?


a) Fat client
b) Thin client
c) Micro client
d) Macro client

Lesson 7: Identifying Client-Side Technologies 195


LESSON 7
2. A fat client makes decisions on its own to perform a bulk of operations irrespective of
the periodic connection to the server.
True
False

TOPIC B
Introduction to Thin UI Clients
In the previous topic, you identied different types of technologies that can be used to develop
client-side applications based on a clientserver architecture. Before choosing a specic type of
client-side technology, you will need to understand the specic requirements to implement
each type of these technologies. In this topic, you will examine thin UI clients.
Banks store data in a centralized server which is accessible to all users across the globe. To
ensure the security and condentiality of information, the data transmission over a network
should take place securely. A thin UI client is an ideal type of client technology as it provides
a secure environment for data transactions.

The Thin UI Client


A thin user interface (UI) client is software that relies on a server for computing business logic
rather than performing these operations on its own. Usually, client-side applications are
designed to be small, in terms of size, so that most of the operations are processed by the
server. The server is secured against external intrusions, and any disruption at the server could
affect all clients connected to the environment. On the other hand, securing the server alone
cuts down the cost involved. ]

HyperText Markup Language


The HyperText Markup Language (HTML) is a commonly used language for designing web
pages. It contains tags that dene the appearance of an object or text, and also enables the user
to move across pages. Tags are of two different types:
Physical markup that denes the appearance of text and objects.
Semantic markup that describes the text structure.
Tags in HTML are not case-sensitive and are enclosed within angular brackets. Most tags in
HTML are used in pairs, with start and end tags. The end tags include a slash before the tag
name.

HTML standards and properties are dened by www.W3.org.

Web Browser
A web server hosts HTML pages and a web browser accesses web pages, renders the
information dened in the tags, and displays the web page on the local machine.

196 Java Fundamentals (Java SE 7)


LESSON 7
Advantages and Disadvantages of Using HTML
The advantages of using HTML are:
It is not case-sensitive.
Text or objects embedded are highly compressed and therefore easy to import.
All browsers support HTML.
It provides better readability.
The disadvantages of using HTML are:
It is used to build only static pages.
It is not a stand-alone application and is dynamic. Users would require to fuse
this with Java Server pages or PHP.

HTML 5.0
The most recent version of HTML is 5.0. It offers high-end multimedia support and
includes new syntax and tags that enable the user to develop high-end media-based
applications.

An HTML Program
An example of an HTML tag pair is the <HTML> used at the beginning and the
</HTML> at the end of a web page. HTML allows you to enhance your web page by
adding components such as text, tables, and images.
A sample code snippet for an HTML page is given in the following:
<HTML>
<HEAD>
<TITLE>HTML Programming</TITLE>
</HEAD>
<BODY>
<H2> Hello World </H2>
</BODY>
</HTML>

JavaScript
JavaScript, also known as ECMAScript, is a client-side scripting language executed at runtime
on a local machine. It is a prototype oriented programming language, wherein classes are
absent and class properties are inherited by cloning existing objects. JavaScript supports func-
tions to be passed as arguments to other functions without any compilation error. It is generally
used for building dynamic websites on browsers and better user interfaces. The JavaScript code
is written within an HTML web page, and starts with a <script type=
"text/javascript"> tag and ends with a </script> tag.

JavaScript shares its naming convention with Java and structure with C.

Advantages and Limitations of JavaScript


JavaScript offers the following advantages:
It can be compatible with various languages; one very common example would be
HTML.
It is a client-side technology and therefore doesnt rely on a server for computa-
tions.

Lesson 7: Identifying Client-Side Technologies 197


LESSON 7
It eliminates the need to convert data types by performing type conversions
implicitly.
JavaScript also has the following limitations:
All errors are captured at the compile time. Except for the blatant errors, the
server ignores all other errors leaving the user to manually check for the errors.
It is susceptible to intrusions.
It does not display a standard output across applications.

JavaScript Code Snippet


An example of JavaScript code snippet is given in the following:
<html>
<script type="text/javascript">
document.write("Hello world")
</script>
<body>
</body>
</html>

Thin UI Deployment Issues


Using thin UI in a client-server architecture offers both advantages and disadvantages. The
advantage of deploying thin clients lies in reducing the cost involved in securing the business
logic and data, because they are stored only on the server. The disadvantage is that all opera-
tions and computations occur only on the server-side. The availability and performance of a
server can be affected by problems such as network traffic and denial of service, which in turn
can affect the performance of the client software.

ACTIVITY 7-2
Introducing Thin UI Clients
Scenario:
You are developing a banking application using client-server technologies. While developing
the application, you are required to ensure that it makes use of a secure environment so that
data transactions are secure and free of risks.

What You Do How You Do It

1. True or False? HTML is not case-sensitive.


True
False

198 Java Fundamentals (Java SE 7)


LESSON 7
2. Which of the following are JavaScripts features? (Choose three.)
a) It is a prototype oriented programming language.
b) It is a client-side scripted language.
c) Its functions are passed as arguments.
d) It computes business logic.

TOPIC C
Introduction to Fat UI Clients
In the previous topic, you were introduced to thin clients that provide a secure environment for
data transmission. You can add specic functionality to your application using the tools of
Java, such as creating classes, calling existing methods, and storing data in a set. In this topic,
you will describe fat UI clients.
Email software, such as Microsoft Outlook, is a ne example of a fat client. Such software
runs on client systems and enables the user to send and receive emails, customize their mailing
options, and also provide advanced capabilities for search and security options. They are gen-
erally congured offline without the server support. However, for such clients to be useful,
they need to connect with a server to exchange data.

Applets
An Applet is a program written in Java and embedded within a web page. Applets require a
standard interface to display in a browser and therefore extend the java.applet.applet
class. The Java Virtual Machine (JVM) enables you to view the Applet code. Applets cannot
exist independently and depend on the host program for execution. The <Applet> tag marks
the beginning of an Applet program.

Advantages and Disadvantages of Applets


An advantage of using an Applet is its ability to execute Java program directly from
the browser. Disadvantages of Applets include considerable time required to download
an Applet if it is not present in the cache memory, the difficulty in preparing a user
interface for Applets, and the requirement of a JVM to run an Applet.

Swing
Swing is a Java extension package provided by java.swing library for creating user inter-
faces. It implements lightweight graphical components and enables the same visual
presentation in different environments. It also provides options for users to change the look
and feel of an application. Swing uses containers and components to create an interface. It
includes a J at the beginning of an item name. For example, a button is described as
JButton in Swing.

Lesson 7: Identifying Client-Side Technologies 199


LESSON 7
Instantiating Swing Components
A container is a Swing component that holds all other components of a user interface. It is the
starting point for UI creation, and each interface you create must have a Swing component.
Common Swing containers are JWindow and JFrame. A container is created by declaring a
new object of the desired type, and setting its properties using appropriate methods for the title
bar, window size, visibility, and how to close the window.
Each container inherits methods for setting its properties. The specic method used to perform
the necessary functions depends upon the type of container used. However, most containers are
located within the same hierarchy, and they dene similar methods and inherit each others
methods.

Types of Swing Containers


The two main types of containers used when creating standard Swing GUIs, JWindow and
JFrame, share certain common characteristics. The JWindow is a standard window that dis-
plays on a computer desktop. However, it does not have a title bar or provide buttons for
opening or closing a window.
Similar to a JWindow, a JFrame is a window that displays on the desktop. However, it pro-
vides built-in functionality for the title bar. It also includes standard buttons to minimize,
maximize, and close the window.

JWindow Methods
The JWindow provides a list of methods for setting a containers properties.

Method Allows You To


setGlassPane() Set the glassPane property for the window.
setContentPane() Dene the setContentPane for the window.
getContentPane() Return the content pane and its return type is Container.

Methods of JFrame
Both the JFrame and JWindow have a default state for visibility as false, and a location,
which is at the top-left corner of the screen. You can change these properties when setting the
rest of the properties for the container, or modify them at a later point during the creation of
your interface using JFrame methods.

Deployment Issues with Swing and Applets


Although swing and Applets provide a number of GUI components, they have their own limi-
tations.

200 Java Fundamentals (Java SE 7)


LESSON 7
Component Description
Swing Swing components when deployed:
Are not thread-safe.
Can lead to poor performance and nonresponsive UI, if not coded properly.
May look similar to native components, but doesnt behave like one. Components
such as web browsers and ash players are examples of native components.
Applet Applets when deployed:
Require a plug-in for execution, which many browsers by default may not support.
Require JVM which may take sometime to start running.
Display a nonstandard output where different browsers will display the contents dif-
ferently.

ACTIVITY 7-3
Introducing Fat UI Clients
Scenario:
During one of the project team meetings, your manager requests that you add certain function-
ality to the application being developed. You decide to use certain Java tools such as create
classes, call methods, and store data in a set.

1. An Applet can execute a program directly from a browser.


True
False

2. Which of the following are JWindow methods? (Choose two.)


a) GlassPane()
b) setContentPane()
c) ContentPane()
d) getContentPane()

Lesson 7: Identifying Client-Side Technologies 201


LESSON 7
TOPIC D
Introduction to Micro UI Clients
In the previous topic, you described various fat UI clients. Sometimes, you may need a client
that can process data but the data needs to be stored on and retrieved from the server. In this
topic, you will examine micro UI clients.
The airline reservation system makes use of client-server technology to store data on availabil-
ity of seats and price for various routes. This information is stored at the central server while
the applications that access this information can run at different locations. This provides users
with the exibility of booking a ticket from anywhere across the globe without worrying about
duplication of data.

Java ME
Java ME, also known as Java Platform-Micro Edition, is a Java platform that is used for
developing applications for embedded systems, such as mobile phones, television set-top
boxes, and printers. Applications developed on Java ME use a combination of lower edition
JVM and a set of application programming interfaces (APIs) installed on mobile devices.
Java ME is divided into three parts: the conguration, prole, and packages.

Java ME Part Description


Conguration It contains the lower-end version of the JVM and a few class libraries. They are
embedded in mobile devices.
Prole It is found above the base class libraries. It contains a set of APIs that are embed-
ded in mobile devices.
Packages They contain an optional set of APIs which you may use while creating your appli-
cations. Because these APIs may not be present by default in mobile devices, it is
considered a good practice to package and distribute these APIs with an application
so that the application works as intended.

MIDlets
MIDlets
A MIDlet is a type of Java application that:
Is designed using Java ME technology.
Is used in mobile devices such as mobile phones and smartphones.
Acts as an interface between an application and the operating system.
Extends the base class javax.microedition.midlet.MIDlet.

The Life Cycle of a MIDlet


The Life Cycle of a MIDlet
MIDlets may be subjected to external intrusions when run on an exploited JVM, especially
during a security breach, and for this reason, they are controlled by the application manager.
The application manager has the authority to select the MIDlets that need to be executed at a
given point in time. A MIDlet passes though three states during its life cycle.

202 Java Fundamentals (Java SE 7)


LESSON 7
MIDlet State Description
Pause An object for a MIDlet is created, but is not active.
Active The MIDlet is active.
Destroy The MIDlet is terminated and then processed by the garbage collector.

MIDlet Deployment Issues


The MIDlet deployment at times may fail. Some of the common error messages associated
with MIDlet failures are download failed, authorization error, application error, and invalid le.

Error Message Description


Download Failed The Java ARchive (JAR) le is in a different location from the one specied by the
Java Application Descriptor (JAD) attribute.
Authorization The authorization error occurs due to the following reasons:
Error A Certication Authority (CA) signs the MIDlet and there could be a problem
with the certicate signature, the JAR signature, or the root certicate in the
device.
Even if the permission is signed, it may not be supported by the device.
The date and time in the device is not set properly.
The JAD and MANIFEST.MF attributes do not match with that of the MIDlet.
Application It is a runtime error and the error message appears after installation and initiation of
Error the MIDlet.
Invalid File The invalid error occurs due to the following reasons:
The JAD and MANIFEST.MF attributes might sometimes be long and do not
match with that of the MIDlet.
Characters used in JAD and MANIFEST.MF attributes are not supported by the
device.
The API used might not be supported by the memory of the device.
The libraries used for compiling a MIDlet may not be supported by the device.

Lesson 7: Identifying Client-Side Technologies 203


LESSON 7
ACTIVITY 7-4
Introducing Micro UI Clients
Scenario:
While developing the application, you notice that data needs to be processed. In addition, you
are required to store and retrieve date from the server.

1. Which of the following is not a part of Java ME?


a) Package
b) Initialization
c) Configuration
d) Profile

2. Which of the following are phases of a MIDlet life cycle? (Choose three.)
a) Pause
b) Active
c) Destroy
d) Run

Lesson 7 Follow-up
In this lesson, you identied client-side technologies, such as thin clients, fat clients, and micro
clients. Now, you can use this knowledge to choose the appropriate client-side technology for
processing information in your applications.
1. Which type of client-side technology would you prefer to use in your application?
Answers will vary, but may include: using a thin client which depends on the host com-
puter for all its business logic to reduce the cost of securing the information, using a fat
client so that it can make decisions of its own to perform a bulk of operations to reduce
the load on the server, and using a micro client to benefit from the advantages of both
the thin and fat clients.
2. Why will you prefer to use Applets over other GUIs while developing applications?
Answers will vary, but may include: using Applets enables you to run your applications on
machines that are not connected to the server, eliminating the need to install the appli-
cation, ensuring that your applications are secure and more reliable than other programs
that work only with the support of a browser, and enabling functionality embedded in the
browser, such as a web graphical application.

204 Java Fundamentals (Java SE 7)


LESSON 8

LESSON 8 Lesson Time


2 hour(s)

Identifying Server-Side
Technologies
In this lesson, you will identify server-side technologies.
You will:
Identify server-side technologies.
Identify web components.
Identify business components.
Process XML and associating elements.

Lesson 8: Identifying Server-Side Technologies 205


LESSON 8
Introduction
In the previous lesson, you identied client-side technologies. However, data processing by
applications usually occurs not at the client side, but at the server side. In this lesson, you will
identify server-side technologies.
As a user, you must have created forms that are displayed at the client side. Data entered in
forms is processed and validated at the server side. In addition, form content can be modied
dynamically based on user input, enabling you to create an interactive form that helps you
gather essential information accurately.

TOPIC A
Introduction to Server-Side
Technologies
Java enables developers to build applications that run on servers to process the data clients
send in. When programming for such applications, the developer needs to understand the tech-
nology better to use its features effectively. In this topic, you will examine server-side
technologies.
As a developer, you would choose to create web pages that are dynamic and provide a visual
appeal to users. This would require a constant change in templates that you use and the content
you feed in. Deploying the server-side technology allows you to automatically update the tem-
plates on your website by importing a single le rather than manually updating each page in
the website.

Server-Side Technologies
A server-side technology is a technology that:
Runs on a server for performing server operations.
Processes data quickly because it runs on the server.
Processes applications that contain dynamic content on websites.
Provides interactive websites wherein a user can retrieve or modify the data residing on
the server.
Is commonly used in e-commerce applications.

The Java EE Architecture


The Java Enterprise Edition (Java EE) is used for developing applications that validate busi-
ness logic at the server side. Java EE is freeware that can be downloaded from the web. The
Java EE platform consists of a set of application programming interfaces (APIs) and follows
dened protocols to provide the functionality for developing applications. Java EE allows you
to add annotations in source code. Congured at runtime, annotations contain information
about a program, and do not affect the programs operations. Java EE 6 has increased the
popularity of lightweight web proles for web-based applications. The rules and nomenclature
for Java EE are dened by the Java Community Process (JCP).

206 Java Fundamentals (Java SE 7)


LESSON 8
N-Tier Architecture
Java EE typically follows an N-Tier architecture. In an N-Tier architecture, the func-
tionality of an application is distributed across three or more tiers. The components
present in each of the tiers, along with the server infrastructure, are responsible for
carrying out the required tasks. For example, the integration tier and the server-side
runtime infrastructure can be used for procuring data from the back-end. To develop
and maintain such applications, different teams are allocated for specic application
components in each tier.

Advantages and Disadvantages of Java EE


Advantages of using Java EE.
It supports development by a team with diverse levels of application development
skill and experience.
The key feature of the Java EE architecture includes scalability and extensibility.
It is based on Java and all the advantages of Java can be leveraged using Java
EE.
It typically includes standards followed for platform development that is guaran-
teed to run on multiple platforms.
It can be programmed using IDEs, such as Eclipse and NetBeans, which are open
source freeware to reduce the overall development cost.
Disadvantages of using Java EE.
It does not allow users to program certain tasks involving API Server controls.
API controls include administration security, such as role names and role refer-
ence.
Several Java EE vendor versions are available and using a specic version could
prevent your application from being interoperable across different application
servers.

Server-Side Components
A server-side component constitutes a set of classes and interfaces that are created to provide
specic functionality. Various types of server-side components include: Enterprise JavaBeans
(EJB), servlets, and web components that use the Java Server Pages (JSP) technology.
The principle feature of Java EE is its component-based development model wherein each
developed component can be reused or transported across applications. Programmers can code
each component without having to understand the environment in which the components are
deployed. Therefore, it is easy for programmers to test, reuse, and maintain components.
Another important feature of these components is that they help you by providing a suitable
API for building the user interface. Server-side components perform two tasks:
They serialize state variables to be compatible with client-side components.
They deserialize any response from the client side.

Loose Coupling
Loose coupling is a development environment where programmers can develop compo-
nents that interact with each other without having to understand the behavior of the
other components. This enables programmers to test, reuse, and maintain components
easily.

Lesson 8: Identifying Server-Side Technologies 207


LESSON 8
State Variables
State variables are object entities that are passed from the server side to the client side.

ACTIVITY 8-1
Introducing Server-Side Technologies
Scenario:
You have been assigned to work on an e-commerce application that will run from a server.
You are required to understand the technology e-commerce websites work on and how effec-
tively these features can be utilized in your project.

1. Which of these statements best describes Java EE?


a) Validates business logic at the client side
b) Contains heavily downloadable objects and is very difficult to download
c) Contains annotations that can change the course of the program
d) Validates business logic at the server side

2. Which of the following sentences are functionality or characteristics of server-side


technology? (Choose two.)
a) It processes applications that contain static content on websites.
b) It is commonly used in e-commerce applications and databases.
c) It deserializes the object entities passed from the server to the client.
d) It is a component-based model.

208 Java Fundamentals (Java SE 7)


LESSON 8
TOPIC B
Identify Web Components
In the previous topic, you were introduced to various server-side technologies. Server-side
applications need to process data to yield the desired results. In order to process data, these
applications need specic software to perform computations. In this topic, you will identify
web components.
In an air ticketing system, a user might ll in the details to book a ight to a country. The
back-end application needs to be designed to yield the desired results. Application frameworks,
such as servlets and JSP, can be used to design the back-end application to perform the neces-
sary operation.

Servlets
A servlet is a Java class that runs on the server-side and is used for extending the capabilities
of a server. Servlets can respond to various types of requests, such as HTTP requests, and then
send a response back to the web browser. So, servlets can also be described as an applet that
runs on the server instead of the web browser. A servlet is a framework used for designing the
server so that it caters to the application for which it is being created. A servlet resides in a
container component called the web container. The web container is a Java Virtual Machine
(JVM) that stores and manages servlet instances to respond to HTTP requests. Each request is
handled by a single instance of the servlet inside the web container. Java EE does not support
the creation of additional servlets in case of additional requests. The requests are handled con-
currently by procuring one thread per request. Also used with web applications, servlets are
compatible with both Java EE and Java SE editions.

The Life Cycle of a Servlet


Java EE allows the web container to handle the servlet life cycle. Servlets on web servers go The Life Cycle of a Servlet
though various phases during their existence.

Servlet Phase Description


Servlet initiation Servlet initiation happens when a client sends a request. The rst phase of the servlet
life cycle after creating a servlet would be to load a servlet. A class le containing
servlet code is loaded into the JVM. Class les are loaded into the web applications
physical hierarchy to be executed during the servlet life cycle.
Create servlet The web container lays a restriction on the number of instances created. At a given
instance time, only one servlet instance is created and the request to the servlet is handled
concurrently.
Call to the The web container also creates an object which encompasses all initialization param-
Init() method eters. A call to the Init() method of the servlet would initialize the servlet. The
Init() method can be overridden to perform any initialization the servlet might
want. This method is invoked by the web container.
Call to the Services can be provided using the service() method. The components receive
service() the HTTP request from web components using the service() method. The
method service() method is invoked by the web container.

Lesson 8: Identifying Server-Side Technologies 209


LESSON 8
Servlet Phase Description
Call to the The web component can destroy the servlet once it nishes its execution. A call to
destroy() the destroy() method terminates a servlet execution. Just like the Init()
method method, the destroy() method can be called only once at any given instance. The
destroy() method can be overridden to allocate space in memory. This method is
invoked by the web container.

The JSP Technology


JSP is a technology that:
Is used in conjunction with HTML for implementing dynamically generated web pages
along with template pages.
Is implemented to provide sufficient support on the web that includes extracting the scope
of an object and displaying the response, which Java does not provide.
Contains code written and embedded into the HTML le and executed for displaying
dynamic content.
Is converted into a servlet instance by the web component.
Processes a servlet based on the HTTP request. The code is then executed for dynamic
content.

The most common technologies that are used with JSP include PHP from Apache and ASP by Microsoft.

The JSP Life Cycle


The JSP Life Cycle
A JSP page is saved with a le extension .jsp. To process a JSP page, you must rst convert
that page to a servlet that can process HTTP requests. The life cycle of a JSP page involves
six stages.

Stage Description
Converting JSP to a The web component converts JSP code into a source le containing a servlet
servlet class. The servlet class implements the interface
javax.servlet.jsp.HttpPage and is different from the usual servlet
class. The HttpJspPage interface extends the JspPage interface which
extends the servlet interface. So, the newly converted servlet also implements
the javax.servlet.Servlet interface.
Compiling JSP After converting the JSP code into a servlet, the web component compiles
source code into a Java class le.
Loading JSP The servlet class is loaded into memoryin this case, the web containers
JVMbefore it is used. By default, the classloader of the web container will
load the class into the JVM. The web container then creates an instance of this
class.
Initializing JSP The jspInit() method is invoked by the web container to initialize the
newly created instance.
Providing services A call to the jspService() JSP method can service requests.

210 Java Fundamentals (Java SE 7)


LESSON 8
Stage Description
Destroying JSP A call to the jspDestroy() method by the web container cleans up the
memory of all instances of the servlet class, classloader, and other instances
created by JSP during the initializing and services phases. The instances are
then ready for garbage collection.

ACTIVITY 8-2
Identifying Web Components
Scenario:
While developing an e-commerce application, you observe that data has to be processed so
that the requested result is obtained. You must be aware of specic software so that computa-
tions can be performed to process the data.

1. Which phase of the servlet life cycle is crucial for creating a servlets instances?
a) Servlet initiation
b) Create servlet instance
c) Call to the init() method
d) Call to the destroy() method

2. True or False? A call to the destroy() method cleans up the memory space that is oth-
erwise occupied by the servlet class.
True
False

Lesson 8: Identifying Server-Side Technologies 211


LESSON 8
TOPIC C
Identify Business Components
In the previous topic, you were introduced to web components. Sometimes, the code for a
servlet and JSP can become very lengthy. Java provides other frameworks to reduce the length
of programs. In this topic, you will identify business components.
In an airline reservation system, a user will ll in the journey details to book a ight. The data
entered on the form is then sent to the server for processing. The back-end application of the
server needs to be designed so that it extracts the essential details and performs necessary
computations. Using the EJB framework, you can design the back-end application to store and
perform computations on the data client-side applications submit.

The EJB Technology


An EJB is an API that:
Is a set of rules and functions which can be used to work with applications and compo-
nents.
Denes a basic architecture used to develop and deploy transactional and distributed
object based software components on the server-side, which are used in enterprise applica-
tions.
Is software that organizations use to solve complex problems, such as payment processing
and customer relationship management.
Enables applications to be customized without the need to understand the source code.
Provides back-end support, such as database connection pooling and transaction process-
ing.
Provides a way of exposing business logic without compromising the security of the
application.
Allows the user to choose the EJBs methods required in a transaction.
Allows end-users to choose the security role to run a program.

Types of EJB
There are three types of EJBs: Session Beans, Entity Beans, and Message-driven Beans.

212 Java Fundamentals (Java SE 7)


LESSON 8
EJB Type Description
Session Beans Session Beans allow for implementing application code in middleware and
also provide easy access to application code. Accessed through a local JVM
interface or a Remote Interface, they create maps to illustrate business pro-
cess ow. Session Beans are of two types:
Stateful Session Bean: This bean has a state. It keeps track of the client
with whom it is interacting through the whole session. It provides access
to only one client at a time. An ideal example would be a store on the
web where Session Beans can be used to track the location of a product in
the checkout area. So, it can hold and lock the items which the customer
is purchasing.
Stateless Session Bean: This bean does not have a state and is usually
termed light weight components. The client has to maintain the state in
this case. Since it doesnt maintain any state, any number of clients can
access this bean depending on the availability of the instance. If one client
invokes a bean just after another client ran a method call, the instance will
be the same. An ideal example of this would be sending client support
emails.
Entity Beans A server-side component which represents the data managed in the database.
They bind data with business object denitions to read and update data con-
sequently. Entity Beans have an identity and each one of those denotes
exclusive sets of data. An example would be the customer entity bean. The
bean is structured in a way that it can be accessed by many applications
simultaneously. The bean developer also decides which parameters from the
database identify the customer individually. The bean developer can also
decide what the methods are that can be public and also which data can
either be only read or modied.
Message-driven Beans Message-driven Beans are based on the Java messaging service. They provide
an API which allows parts of an application to send and receive messages.
They send, receive, and listen to messages anytime without any interventions,
supporting asynchronous messaging. An example of a message driven bean is
a scheduler application that triggers time-based events.

The Home Interface


A Home Interface, also known as a Local Interface, is a method that:
Is composed of other methods which are not attached to any instance of the EJB. This
would include the class-level methods which are used to create, remove, and nd
instances of EJB.
Is not specic to any particular bean instance.
Requires sample code for creating the interface.
Is used when other EJBs or clients address the bean within the same or single JVM.
Is used when arguments are to be passed by reference between the client and the EJB.

The bean and client will use only one copy of data. The changes made in the data can be accessed by both the
client and the bean only when the beans are composed of the same package (EJB.jar). When two beans are
deeply connected with each other, they can be both deployed in a single JVM.

Lesson 8: Identifying Server-Side Technologies 213


LESSON 8
The Remote Interface
A Remote Interface is a type of interface that:
Is composed of methods which are attached to an instance of the EJB. This includes
methods that provide the actual business logic.
Is a method that is not specic to any particular bean instance.
Is deployed in a distributed environment.
Is used when arguments are to be passed by value between the client and the bean. In
this case, the bean and client will have their own copies of data.

ACTIVITY 8-3
Identifying Business Components
Scenario:
While working on the client-side application, you notice that the code has become lengthy.
You decide to design the back-end to store and perform computations on the data submitted by
the client-side application.

1. Which of these is not a type of EJB?


a) Session Beans
b) Entity Beans
c) JavaBeans
d) Message-driven Beans

2. Which of these statements about a Home Interface are true? (Choose three.)
a) A Home Interface consists of methods which are not attached to any instance of the
EJB.
b) A Home Interface consists of methods which are attached to an instance of the EJB.
c) A Home Interface must not be specific to a bean instance.
d) A Home Interface is used when arguments are passed by reference.

3. True or False? A Remote Interface is used when arguments are passed between the
EJB and client by value.
True
False

214 Java Fundamentals (Java SE 7)


LESSON 8
TOPIC D
Process XML and Associating
Elements
In the previous topic, you were introduced to business components. When designing web-based
applications, you will need to process and structure data that may not be organized. In this
topic, you will process XML and associating elements.
Assume the user uses his remote system to check for the availability of tickets to book his
ight. The form is sent from the user system to the server the moment he hits the submit but-
ton. The server connects to the database to check for the availability of the time slot depending
on the user input. The associating elements of the XML extract the data from the database.
The data is extracted depending on the elds declared in the form. The server retrieves and
organizes the data into elds and is then sent to the client. This way, the user gets to see and
work with well-organized and structured data.

The XML Parser


An XML parser is software that:
Is used for reading Extensible Markup Language (XML) documents.
Runs on a platform where JVM is installed.
Determines data structures and their properties.
Extends an interface to extract the information from XML tags.

Types of XML Parsers


XML parsers are classied into various types depending on their utility and purpose.

XML Parser Type Description


XML pull parser This parser is recommended for those applications that require a fast XML
parser for speeding up the process.
SAX A Simple API for XML (SAX) is a parser that follows an event-based
approach; therefore, it is an event-driven interface. Events could include XML
tagging and error detection.
Expat XML parser This parser is scripted in the C language and is run on platforms compatible
with UNIX or Windows 32. The parser can be used for writing the XML
parser and not for validating it.
XP and XT These parsers are written in Java. The XP parser is used for validation and is
known for its high performance. The XT parser is an XSL processor for differ-
entiating formed and not well-organized documents and is used for writing
programs for transformation systems.

Lesson 8: Identifying Server-Side Technologies 215


LESSON 8
XML Binding
XML binding allows XML schemas and Java classes to be bound to XML representations.
The signicant feature of XML binding is that it can use the object to access data from an
XML-based le. Used for serializing or de-serializing objects or data, it enables you to write
code in a programming language and port it to another programming language easily.

The Java Architecture for XML Binding


A JAXB or Java Architecture for XML Binding is an API for accessing XML docu-
ments. JAXB delivers the XML document to the Java program. The schema for the
XML document binds (converted) into a group of Java classes that the schema repre-
sents. A schema is nothing but an XML specication which identies all elements in
the document, the manner in which they should appear, and the parameters they can
have. The schema is typically written in a schema language such as W3C XML which
denes relationships and data types. Schema binding is a way to generate a group of
Java classes that have been representing the schema. The JAXB also provides a bind-
ing compiler which binds the schema.
This binding provides two features:
Marshaling: Accounts for storing data in memory in XML format without imple-
menting any XML loading and saving conventions.
Unmarshaling: Accounts for retrieving data in memory in XML format without
implementing any XML loading and saving conventions. An example of this
would be to access an XML document and display the output using JAXB.

ACTIVITY 8-4
Processing XML and Associating Elements
Scenario:
While working on the application, you observe that data is cluttered and the output is not user-
friendly. You will need to process the data and structure it accordingly so that the data is
organized.

1. Which of the following is not a type of XML parser?


a) SAX
b) XS
c) XP
d) XT

2. True or False? Marshaling is a feature of XML binding.


True
False

216 Java Fundamentals (Java SE 7)


LESSON 8
Lesson 8 Follow-up
In this lesson, you identied server-side technologies. Now you will be able to determine the
right type of server-side technology to use based on the given requirements for an application.
1. Which type of server-side technology would you prefer while writing your code for
designing applications?
Answers will vary, but may include: Enterprise JavaBeans to develop complex applications
because it can be used for customizing applications easily, and servlets to develop web
applications, because they respond to any type of user requests, handle multiple threads
simultaneously, and are platform independent.
2. What type of applications do you think will benefit from implementing server-side
technologies? Why?
Answers will vary, but may include applications such as airline reservation systems which
use a server to store and retrieve data that will be displayed to users from varied geogra-
phies, banking systems that enable customers to access their accounts from any location,
and online collaboration systems such as emails and file sharing that enable organizations
to leverage technology and work with teams spread over multiple geographies.

Lesson 8: Identifying Server-Side Technologies 217


NOTES

218 Java Fundamentals (Java SE 7)


LESSON 9

LESSON 9 Lesson Time


2 hour(s)

Identifying Integration
Technologies
In this lesson, you will identify integration technologies.
You will:
Identify synchronous communication.
Identify web services.
Identify database connectivity.
Identify asynchronous communication.

Lesson 9: Identifying Integration Technologies 219


LESSON 9
Introduction
In the previous lesson, you identied the server-side technologies used for creating applications
that process data at the server. To use the processed information, you must know how to
retrieve it from the server. In this lesson, you will identify integration technologies.
Online shopping is a ne example of an integrated technology in use. The shopping cart allows
a customer to select items for purchase. The customer then enters essential details such as the
name, address, mode of payment, card number, location, and packaging costs in a form and
submits it. On submitting the form, information is sent for evaluation and stored in a database.
While the user interface where customers enter the payment details is a proprietary program of
an e-commerce service provider, the shopping cart is a proprietary program of another com-
pany. Integrating different technologies enables you to develop seamless applications that use
proprietary software from different vendors.

TOPIC A
Describe Synchronous
Communication
In this lesson, you will identify the various technologies used for connecting a client to a
server to send and retrieve information. Data can be sent and retrieved from a client either
synchronously or asynchronously. In this topic, you will describe synchronous communication.
In time-critical applications, such as airline or hotel reservation, client requests need to be pro-
cessed by the server and the information must be sent back to the client quickly to ensure
customer satisfaction. In such situations, the synchronous communication model enables pro-
grammers to develop applications that ensure faster processing of client requests.

JNDI
The Java Naming and Directory Interface (JNDI) is an event interface that:
Helps software clients to search for data and objects by name.
Is independent of software platforms.
Connects an object to a JNDI method.
Is a look-up interface where a user can generate queries.
Allows a client to see whether entries have been modied.
Is a Service Provider Interface (SPI) that uses a server, database, or le to make a con-
nection.

Function of a JNDI
JNDI arranges all names into a specic order or hierarchy. A name can be either a
string or an object. A name is attached to an object in a directory by storing this object
or calling a reference to that object. The name also states the context or procedure on
how to look up an object.

220 Java Fundamentals (Java SE 7)


LESSON 9
RMI
Denition: RMI
The Remote Method Invocation (RMI) is an interface that:
Performs operations equivalent to remote procedure calls.
Processes an object running in a Java Virtual Machine (JVM), and can invoke an
object running in another JVM.
Is located in the java.rmi package.
Consists of three phases:
The server creates remote objects and prepares references to these objects,
which are made available to a client. The server waits for the client to invoke
the methods on these objects.
The client gets the remote references created by the server and invokes a
method on the objects.
The object registry, a name server, holds all object names. After an object
has been registered, remote access to the object can be made using the
objects name.

Example:

Figure 9-1: An RMI system.

RMI Architecture
The RMI architecture consists of ve components.

Component Signicance
Server The RMI server connects its name to a registry.
Client The RMI client looks for the server name in a registry for remote connectivity.
When a client invokes a remote method, the remote method call is delivered to the
stub.
Stub The RMI stub delivers a remote call to the skeleton on the server side. The stub
opens up a socket to the remote server, arranges parameters of an object, and sends
the data or data stream to the skeleton.
Skeleton The RMI skeleton contains a method that receives remote calls, rearranges param-
eters, and invokes an original remote object.
Registry This RMI registry is similar to the naming directory, JNDI, and is used mainly to
bind objects. Any reference to a client is returned to the client.

Lesson 9: Identifying Integration Technologies 221


LESSON 9

RMI Interface and Classes


The RMI interface and classes are dened in the java.rmi package. A Remote Interface can
declare methods that a client can access from any remote machine. A Remote Interface must
fulll the following two conditions: it should extend the interface Remote and every remote
method declaration dened in the interface should include the exception
RemoteException.
The server functions of RMI are provided by the Remote Object class, which has four sub-
classes: remote server, unicast remote object, activatable, and remote
method. A remote object invokes methods in the class java.lang.object.

Class Description
Remote Server This class executes business logic or functionality.
Unicast remote object This class is used for creating remote objects and making them
available to remote clients.
Activatable This class is used for creating remote objects and making them
available to remote clients.
Remote method Every remote method declared in an interface must dene a remote
exception. During every RMI failure, a remote exception is thrown.
It is a checked exception (handled by the caller of a remote
method).

ACTIVITY 9-1
Describing Synchronous Communication
Scenario:
You are assigned the task of creating a website for one of your customers. Per the customers
requirements, the website must follow the standards and specic set of protocols laid out in
designing websites so that data is easily retrievable from the server.

1. Which of the following are components of a typical RMI setup?


a) Registry
b) Skeleton
c) Stub
d) HTTP

222 Java Fundamentals (Java SE 7)


LESSON 9
2. What information do you need to use the JNDI lookup service?
a) Implementation type
b) Interface type
c) Name
d) SPI

TOPIC B
Introduction to Web Services
In the previous topic, you were introduced to synchronous communication that retrieves data
by calls to the remote server or by using an interface. However, the server needs to be
designed in a particular format using a specic set of protocols for easy retrieval of data. In
this topic, you will be introduced to web services.
Java enables programmers to develop dynamic applications, including interactive websites, as
an important mode of doing business. Creating and designing websites involve implementation
of standards that ensure proper communication between the discrete technologies that together
provide a service.

JAX-RPC
Java API for XML-based RPC (JAX-RPC) is a technology for modeling web services that
work on Remote Procedure Calls (RPC). RPC is a mechanism that programs from a client
computer to request access to a remote service without knowing the network details. JAX-RPC
allows its client to access any web service, irrespective of the platform used. A lower version
of JAX-RPC, which is compatible with Java ME, includes a package subset that comes with
J2ME web services. This package enables portable web services to enhance proper communi-
cation between clients and servers.

SOAP
Simple Object Access Protocol (SOAP) is a protocol in an XML format that is used for trans-
mitting most of the web service messages. SOAP depends upon HTTP for sending messages
and consists of an envelope tag, a header, and a body. The envelop tag is typically an indica-
tion to the receiver that a message is on its way. The header contains information about the
sender and receiver, and the body contains data or information.
SOAP enables the standardization of communication across varied networks, facilitates easier
connectivity and data transfers, and ensures a secure connection where the chances of getting
lost in a network are very remote.
Parts of SOAP include:
The processing model that contains the rules for sending and receiving messages.
The extensibility model, which denes the features of SOAP and its modules.
The message construct which denes a message construction.

Lesson 9: Identifying Integration Technologies 223


LESSON 9
UDDI
Universal Description, Discovery and Integration (UDDI) is an XML-based registry that busi-
nesses use for providing information on the Internet and registering for web services. It is
accessed by SOAP messages and is used for providing access to WSDL documents based on
protocols and messaging formats. UDDI consists of three parts.

UDDI Part Description


White Provides information about suppliers including the name, address, and contact information
pages in several languages.
Yellow Classies businesses according to the standard taxonomies in the respective countries.
pages Examples of taxonomies include: North American Industry Classication System (NAICS)
and United Nations Standard Products and Services Code (UNSPSC). A single business
may provide multiple services, and therefore multiple yellow pages can be linked to a
single white page.
Green Provides technical information about the various services of a particular business. For
pages example, instructions on how to access a web-related service based on parameters such as
interface and interfaces.

WSDL
The Web Services Description Language (WSDL) is a document that characterizes the function
and implementation of a web service. A web service can access the WSDL and initiate the pro-
cess that invokes a web service. It describes and provides services irrespective of the formats
and protocols used for communication.
It consists of seven parts.

WSDL Part Description


Types A container for denitions of data types.
Message An explanation of the data being transferred.
Operation A description of an action.
Port type A group of operations supported by end points.
Binding An accurate protocol and specication of data formats of a port type.
Port A single end point which combines the binding and address of a network.
Service A group of associated ports.

224 Java Fundamentals (Java SE 7)


LESSON 9
ACTIVITY 9-2
Introducing Web Services
Scenario:
You have designed the website by following proper communication between various applica-
tions. You are now required to establish a proper connection to the server so that you can
access the website.

1. Which technologies will be suitable if you want to allowing non-Java clients to call your
services? (Choose two.)
a) JAX-RPC
b) SOAP
c) RMI
d) WSDL

2. Which important information you need to specify when using a UDDI registry to provid-
ing services? (Choose three.)
a) White pages
b) Yellow pages
c) WSDL
d) Green pages

3. Which part of the SOAP message stores information related to either the sender or the
receiver?
a) Envelope
b) Header
c) Body
d) Message

Lesson 9: Identifying Integration Technologies 225


LESSON 9
TOPIC C
Introduction to Database
Connectivity
In the previous topic, you identied the technologies that enable you to design interactive
websites by following proper communication between various applications. You must establish
a proper connection to the server to retrieve data that you would add to the website. In this
topic, you will be introduced to database connectivity.
You are a market analyst in an organization and need to connect to the services of a market
research organization to get the latest updates from the market. The market research organiza-
tion hosts a website that contains information of all the stocks and indices in a database in a
remote server. To obtain the necessary data from the server, the market research organization
should provide the means for a user to connect with a database stored on the server. Database
connectivity lls in this gap to retrieve or update information in a database stored on the
server.

RDBMS
A Relational Database Management System (RDBMS) is a database management system used
for storing large amounts of data in tables. It enables you to create a relationship between
tables and allows you to access data without modifying the table structure. An RDBMS is built
based on the atomicity, consistency, isolation, durability (ACID) properties, which ensure that
data can be processed reliably, and provide for the normalization of databases.

SQL
Structured Query Language (SQL) is a language used for accessing and updating data stored in
an RDBMS. Various database vendors use different versions of SQL, such as PL-SQL for
Oracle and T-SQL for SQL Server. SQL includes various elements, such as clauses that are an
integral part of SQL statements and queries that allow you to lter a result based on specic
criteria.

JDBC
JDBC Denition:
Java DataBase Connectivity (JDBC) is an API that:
Species how a Java program can access data from a database using standard
Java classes.
Allows SQL statements to be executed.
Is registered with the JDBC driver manager, which is used for creating connec-
tions to execute statements such as insert, update, and delete.
Sends SQL queries to a database.
Processes query results returned by a database.

226 Java Fundamentals (Java SE 7)


LESSON 9
Example:

Figure 9-2: A JDBC.

ACTIVITY 9-3
Introducing Database Connectivity
Scenario:
You team is involved in maintaining your organizations website. You need to ensure proper
communication between various applications that run on the website. Before you start, you
want make sure that you understand the database concepts correctly.

1. Which of the factors are critical for choosing the correct RDBMS for an application?
(Choose two.)
a) The ability to store large amounts of data in tables and define relationships between
them.
b) The capability to support an extensive set of additional SQL functions.
c) Implementation of the ACID property.
d) The ability to filter results based on specific criteria.

2. Which programming language is used to interact with an RDBMS?


a) PHP
b) SQL
c) Java
d) C

Lesson 9: Identifying Integration Technologies 227


LESSON 9
TOPIC D
Describe Asynchronous
Communication
In the previous topic, you were introduced to database connectivity for sending and retrieving
the data from a database. The data from a database may not necessarily have to be communi-
cated immediately. In some instances, you want to process this data further before sending it to
a client. In this topic, you will describe asynchronous communication for mail service.
Email server software comes with highly scalable messaging services that allow users to access
emails, tasks, and notes from anywhere across the globe. The mail servers interface also pro-
vides the functionality to access its features from any location that has network access. Using
asynchronous communication would enable you to identify the conguration features of mail
servers that make them more responsive.

JavaMail
JavaMail is an API that provides a platform-independent framework for email applications. It
allows developers to add the mailing functionality to applications. It is protocol independent
and works with multiple protocols, such as Simple Mail Transfer Protocol (SMTP) and Post
Offce Protocol 3 (POP3). The advantage of using JavaMail is that it stores POP3 and other
protocol messages. JavaMail allows you to send email through any Java application and man-
age attachments to an email.
JavaMail includes packages such as:
javax.mail that denes common classes, which are common to all mail systems.
javax.mail.event that provides events for JavaMail.
javax.mail.internet that denes classes, which are applicable to specic Internet
mail standards, such as SMTP and POP3.
javax.mail.search that searches for terms.

JMS
The Java Messaging Service (JMS) is an API used for exchanging messages between two cli-
ents. It enables communication between those application components that use Java EE, and
supports asynchronous messaging, wherein multiple clients send messages at the same time.
Not all components are necessary for its proper functioning or for storing sent messages; how-
ever, JMS delivers a message only once. Despite multiple clients accessing a network at the
same time, JMS ensures the security of its network resources. It supports point-to-point and
publish-and-subscribe models.

JMS Elements
JMS contains seven elements.

228 Java Fundamentals (Java SE 7)


LESSON 9
Part Description
JMS provider Provides a JMS interface implementation for sending and receiving mes-
sages.
JMS client A function which is used for sending and receiving messages.
JMS producer A JMS client which composes and sends messages.
JMS subscriber A JMS client which receives messages.
JMS queue An area which contains messages sent or is waiting to be sent in any
order.
JMS message Contains data that is being transferred between JMS clients.
JMS topic A mechanism for sending messages to multiple subscribers.

ACTIVITY 9-4
Describing Asynchronous Communication
Scenario:
You are successful in retrieving data from the database. You observe that you will need to pro-
cess this data even more before it can be sent to the client.

1. Which of these statements about the JMS is true?


a) JMS is an API that supports synchronous messaging.
b) JMS is an API that enables communication between clients.
c) Every component of a JMS is essential for proper functioning.
d) JMS is not reliable.

2. Which of the following packages are included in JavaMail? (Choose three.)


a) javax.mail
b) javax.mail.event
c) javax.mail.search
d) javax.mail.webmail

Lesson 9: Identifying Integration Technologies 229


LESSON 9
Lesson 9 Follow-up
In this lesson, you identied integration technologies. You can now choose an appropriate inte-
gration technology to connect to back-end applications such as databases, and send the data
retrieved to a client by using enhanced mail communication.
1. Which type of communication method would you prefer to send and receive data
across a network?
Answers will vary, but may include: the synchronous communication method where a user
retains the connection until the transaction is complete, after which the control passes to
another user, or where feedback needs to be instantaneous; or the asynchronous commu-
nication method where multiple users can access a network simultaneously and can
connect to the network much faster than the synchronous communication method.
2. What technology will you use most often while implementing web services?
Answers will vary, but may include: JAX-RPC is one of the emerging technologies that
provides users with the advantage of accessing web services irrespective of the platform
of these web services and can be used in mobile phones as it is compatible with the Java
ME platform and applications; and SOAP provides capability when multiple users need to
access a network, and is used in sending messages in XML format.

230 Java Fundamentals (Java SE 7)


Follow-up FOLLOW-UP
In this course, you explored the essential elements of Java SE 7 and created programs in Java
that incorporate control ow based on user input. You also created functionality for your appli-
cation using classes and Java libraries, and extended the capability of existing programs using
inheritance.
1. What are some of the best programing practices that you will follow when you are
developing applications using Java?
Answers will vary, but may include using camel casing to ensure that the purpose of iden-
tifiers can be easily determined; using comments to describe code to enable easy
troubleshooting; using JavaBeans to ensue that the attributes of a class are accessible
indirectly; and using interfaces to specify methods that classes need to implement.
2. How do you think Java will enable you to develop or extend applications efficiently
that meet requirements?
Answers will vary, but may include using classes defined in Java libraries to add addi-
tional functionality to your programs; using inheritance to extend the capability of
existing applications; or using packages to define a set of components that can be used
across multiple applications.
3. What features of the Java programming language do you think will enable you to cre-
ate dynamic programs?
Answers will vary, but may include using method overloading to enable the methods
defined in an application to accept different types and number of arguments for process-
ing; and using method overriding to ensure that the application can process data
differently than the superclass.

Whats Next?
This course does not follow any specic series. Interested students can take any of Logical
Operations courses related to Java technologies to enhance their knowledge.

231
NOTES

232 Java Fundamentals (Java SE 7)


LESSON
LABS

LESSON LABS
Due to classroom setup constraints, some labs cannot be keyed in sequence immediately fol-
lowing their associated lesson. Your instructor will tell you whether your labs can be practiced
immediately following the lesson or whether they require separate setup from the main lesson
content. Lesson-level lab setup information is listed in the front of this manual in the course
setup section.

LESSON 1 LAB 1
Creating, Compiling, and Running a Cash Register
Application
Activity Time:
25 minutes

Data Files:
CashRegister.jar

Scenario:
Your company, Our Global Company (OGC) Technologies, is creating a new cash register sys-
tem. Your colleague had started developing the application in the CashRegister.java le, but
could not nish it due to commitments to other projects. Your manager provides you with a list
of requirements for this application:
A receipt must contain four columns: item number, quantity, price per each, and
cost (quantity * cost).
Each item should display on its own line.
A double line ( == ) should separate line items and the subtotal.
The subtotal, tax, and total should display with separate row labels on separate
lines.
A message for the total number of items purchased should appear after the total.
A message thanking the customer for shopping at the store should appear last.
To test the application, you decide to use the following data:
Item ID: 101, quantity 8, and price $1.15.

Lesson Labs 233


LESSON

LABS
Item ID: 102, quantity 8, and price $0.65.
Item ID: 103, quantity 6, and price $0.85.
Item ID: 104, quantity 2, and price $1.25

1. Import the CashRegister project into Eclipse from the C:\085664Data\


Programming in Java\ folder.

2. In the CashRegister project, create a public class named CashRegister in the


default package.

3. Write the main method.

4. Declare a PurchaseType array named purchases with four slots.

5. Define an instance of the PurchaseType class for each element of the


purchases array and set the purchase quantity and cost given in the table using
the setAmounts() method.

6. Declare a variable named totalItems to store the total items and a variable
named subTotal to store the subtotal and initialize each of them to 0.

7. Print the quantity, price, and cost of each item in the purchases array using the
array index and the getQuantity(), getPrice(), and getCost() methods
respectively on separate lines.

8. For each index of the purchases array, write an expression to increment the
value of totalItems using the getQuantity() method.

9. For each index of the purchases array, write an expression to increment the
subTotal using the getCost() method.

10. Print a double line to separate the items from the subtotal.

11. Print the subtotal value with a corresponding label.

12. Write an expression to calculate sales tax on the subtotal amount at the rate of 10
percent.

13. Print the sales tax amount, total amount, and total number of items purchased
with corresponding labels for each.

14. Print a message Thank you for shopping at our store! at the end of the program.

15. Save, compile, and execute the program to test your code.

16. Close the CashRegister project.

234 Java Fundamentals (Java SE 7)


LESSON
LESSON 2 LAB 1 LABS
Controlling Program Flow in the Cash Register Program
Activity Time:
20 minutes

Data Files:
CashRegisterV2.jar

Scenario:
You had developed a cash register program for a client. Given that the cash register may
require to perform calculations for various products, you are required to update the program to
facilitate its usage as required. Moreover, the customer also wants you to provide a feature that
would calculate a discount of 10% for purchases over $50. You decide to implement these
changes in the program.

1. Import the CashRegisterV2 project into Eclipse from the C:\085664Data\


Controlling Program Flow folder.

2. Open the CashRegister2.java file.

3. Before the code statement that outputs a double-line, create a for loop to
traverse the length of the array and display the product details using the
getQuantity(), getPrice(), and getCost() methods.

4. In the for loop, calculate the total number of items purchased and the subtotal
amount by incrementing them using getQuantity() and getCost() methods,
respectively.

5. After the code statement that outputs a double line, create an if statement to
see if the total purchases are worth over $50.

6. Calculate a discount of 10% for purchases over $50 and print the discount amount
along with a label.

7. Print the subtotal after the discount amount with a label.

8. Save, compile, and execute the program to test your code.

9. Close the CashRegisterV2 project.

Lesson Labs 235


LESSON
LABS LESSON 3 LAB 1
Working with the Java Class Library in the Cash Register
Program
Activity Time:
15 minutes

Data Files:
CashRegisterV3.jar

Scenario:
You are developing a cash register application for a client. You have developed the application
and incorporated features to generate reports. The customer requires you to build a security
feature for the cash register program by implementing password protection. You are required to
implement a password protection to the application. Also, the application must prompt users to
provide a password when the application is launched. It must also validate the password pro-
vided and display a message when the password is invalid. For testing purposes, you decide to
use the word secret as password for the application.

1. Import the CashRegisterV3 project into Eclipse from the C:\085664Data\Working


with Java Class Libraries folder.

2. Open the CashRegister3.java file.

3. At the start of the main method, write a system output statement that prompts
users to enter a password by displaying a message.

4. Declare a StringBuffer instance to store the password.

5. Declare a character variable.

6. Create a while loop to check for continued character input until the Enter key is
pressed using the ASCII value for Enter, which is 13.

7. In the while loop, call a StringBuffer method to continue adding letters to the
password.

8. Create an if statement that encloses the rest of the code in the main method
and checks whether the password entered is correct.

9. In the main method, after the closing brace of the if statement, create an else
statement to display a system output statement that prompts the user when an
invalid password is entered.

236 Java Fundamentals (Java SE 7)


LESSON
10. Save, compile, and run to test your code.
LABS
11. Close the CashRegisterV3 project.

LESSON 4 LAB 1
Creating an Employee Class in the Cash Register
Program
Activity Time:
20 minutes

Data Files:
CashRegisterV4.jar

Scenario:
You are developing a cash register application for a client. The client requirements state that
each employee be assigned a case-sensitive user name and password to use the cash register
program. You are required to create a feature that will:
Save employee names and passwords.
Retrieve names and passwords.
Validate the user name and password.
Also, the password used must have at least 6 characters. You decide to incorporate these fea-
tures and test the application with the user name and password for four employees.

1. Import the CashRegisterV4 project into Eclipse from the C:\085664Data\Creating


Classes folder.

2. Create a class named Employee in the default package.

3. Add two variables named empName and empPasswd to store the employee name
and password respectively.

4. Create a constructor that accepts the employee name and password as param-
eters and throws an exception when the password is fewer than six characters in
length.

5. Define methods named getName and getPassword that return the employee
name and password respectively.

Lesson Labs 237


LESSON
In the CashRegister4 class, after the boolean variable named
LABS 6.
isValidPassword, create a for loop with a nested if statement to check the
input user name and password with the user name and password stored in the
application.

7. Within the if loop, set the isValidPassword to true when the password is
valid and break the loop.

8. Save, compile, and run the application to test the working of the application.

9. Close the CashRegisterV4 project.

LESSON 5 LAB 1
Creating a Manager Class in the Cash Register Program
Activity Time:
10 minutes

Data Files:
CashRegisterV5.jar

Scenario:
You created a cash register application that stores user names and passwords of employees
who use the cash register. The customer asked you to incorporate features that will enable
users to retrieve passwords if they forget their password. You are required to incorporate a fea-
ture that will enable managers to access user names and passwords and retrieve them if
employees forget their passwords. You decide to implement this functionality in the applica-
tion.

1. Import the CashRegisterV5 project into Eclipse from the C:\085664Data\


Implementing Inheritence folder.

2. In the com.mystore.cashregister package, create a public class named


Manager that extends the Employee class.

3. Define a boolean variable, mLookup, that determines whether a manager has


access to passwords of employees.

4. Create a constructor with parameters for the name, password, and lookup that
calls a superclass constructor and sets the lookup variable equal to the corre-
sponding parameter.

238 Java Fundamentals (Java SE 7)


LESSON
Define a method, canLookupPasswords, to return if a manager is allowed to
5.
look up passwords. LABS
6. Save the Manager.java file.

7. Close the CashRegisterV5 project.

LESSON 5 LAB 2
Importing a Class for the Cash Register Program
Activity Time:
20 minutes

Data Files:
CashRegisterV6.jar

Scenario:
You are working on a cash register application where you are enabling managers to access the
user name and password of other employees. The application must provide managers with an
option to choose whether they want to access employees passwords . Depending on the
response, the application must determine if the manager has the required privileges to access
passwords of other employees. When the manager has the required privileges, the application
must display the list of user names and passwords. Managers must also be able to access the
reports generated by the application when they respond in the negative when prompted for
access to passwords of other employees. For testing purposes, you decide to use the manager
name Karl and the password Karl123 to test the application.

1. Import the CashRegisterV6 project into Eclipse from the C:\085664Data\


Implementing Inheritence folder.

2. Import the Manager class into the CashRegister5 class.

3. Add a manager, Karl, who has access to passwords of other employees to the list
of employees.

4. After the code to set the isValidPassword variable to true, create an if state-
ment that checks whether the employee is a member of the Manager class.

5. Create a nested if statement to check to see if the manager has the privileges to
access passwords of other employees.

Lesson Labs 239


LESSON
In the nested if statement, create a system output to provide managers with a
LABS 6.
choice to access user passwords using a yes/no input.

7. In the nested if statement, display passwords of employees if the application


receives the input y.

8. Save, compile, and run the application to test your code.

9. Close the CashRegisterV6 project.

240 Java Fundamentals (Java SE 7)


GLOSSARY

GLOSSARY
abstract class attributes
A Java class used to represent abstract con- Characteristics displayed by a class and its
cepts. objects.
abstract method boolean literal
A method that contains no implementations The specic declaration of any boolean value.
and can only be a superclass.
break
access modiers A Java code statement that halts execution of
Java keywords that extend objects. a loop.
ACID bytecode
(atomicity, consistency, isolation, durability) A An intermediate representation of Java pro-
set of properties that enables the data transac- grams that is created when Java programs are
tions reliably across a network. compiled using the Javac compiler.
annotations case
Contain information about a program, and do A statement that denes a group of actions to
not affect the programs operations. execute based on a specic test expressions
value within a switch statement.
API
(application programming interface) An inter- character literal
face that enables developers to facilitate the The specic declaration of any character
development of programs using a specic value.
application.
class diagram
Applet A type of UML diagram that is used to repre-
A program written in Java and embedded sent different classes and their relationships in
within a web page. a software system.
application manager class
An application manager is a software program A Java code element that is the template for
responsible for MIDlet initiation and destruc- objects with similar features and behaviors.
tion.
clientserver architecture
arithmetic operators An architecture that includes the client and
Symbols used to perform basic arithmetic the server to carry out operations.
operations in Java.
comments
array Statements in source code that are ignored by
A Java code element that stores lists of items the Java compiler.
of the same data type.

Glossary 241
GLOSSARY
component do...while loop
A Swing object that contributes to an inter- A Java ow control statement that executes a
face, such as a button, panel, or text eld. block of code and then checks for a specic
condition, and executes the code until the
concatenation condition is true.
The joining of two text items.
dot notation
concrete class Is normally used with attributes and methods
A class that can extend only one superclass. to access attributes or methods of an object.
constant Driver manager
A variable type that denes a variable but A library that acts as an interface between
does not change its value. applications and drivers.
constructor method EJB
A Java method that initializes a new instance (Enterprise JavaBean) A server-side compo-
of a class. nent used for enterprise applications.
constructor overloading encapsulation
Declaring a constructor with the same name The wrapping together of attributes and
as another constructor in the same class, but behaviors.
with different arguments.
enumerated data type
constructor A language construct in Java that helps repre-
A Java method that initializes a new instance sent data sets with constant values.
of a class.
equals method
container A Java method that compares two objects for
A Swing component that holds all other com- value equality.
ponents that form the user interface.
exception handling code
continue Used to handle exceptions that arise when
A Java code statement that causes a loop to incidents happen for which code was pro-
skip remaining loop statements and restart at gramed to handle.
the next loop iteration.
ow control statement
data hiding A Java statement that allows programs to
Versions of objects that do not know about execute a statement or a block of code based
each other. on the value of a variable or test expression.
decrement operator for loop
An operator that allows you to reduce the A Java ow control statement that repeats a
value of a numeric variable or array element single or a block of statements until a condi-
by 1. tion changes.
default constructor for...each loop
A constructor automatically created by the A loop that is used to access individual values
Java compiler containing no arguments. successively in an array.
default Has-A relationship
A statement that denes a group of actions to The relationship between a class and an
execute when no case statement is executed. object in which a class has an object that is a
member of another class.

242 Java Fundamentals (Java SE 7)


GLOSSARY
Home Interface instantiation
A Home Interface is composed of methods The process of creating an instance (object)
which are not attached to any instance of the for a class in Java.
EJB. This would include class level methods
which are used to create, remove, and nd interface
instances of EJB. A Java component that contains zero or more
methods with no implementations and zero or
HTML more constant variables.
(HyperText Markup Language) A commonly
used language for designing web pages and interpreted
contains tags that dene the appearance of A bytecode output generated by the Javac
objects or text. compiler that is executable on any computer.

IDE Is-A relationship


(Integrated Development Environment) A soft- The relationship between an object and a
ware application that provides various options class in which the object of an inheriting
to enable programmers to develop applica- class is a member of the class it is inherited
tions quickly. from.

identier Java class library


A name assigned to an entity, such as an A group of predened classes, categorized
object or method. and arranged into packages.

if statement Java Community Process


A Java ow control statement that is declared A process which interested parties use for
with the if keyword and contains a boolean dening Java technical specications.
test expression within parentheses.
Java EE
if...else statement (Java Enterprise Edition) A platform for
A Java ow control statement that uses a developing applications that validate business
double selection to choose between two logic at the server side.
courses of action.
Java ME
immutable (Java Platform-Micro Edition) A Java plat-
Unable to be altered after creation. form that is designed to be used in
developing applications for embedded systems
import declaration such as embedded devices which include
A Java statement that allows classes from mobile phones, television set-top boxes, and
other packages to be used in programming. printers.
increment operator Java platform process
An operator that allows you to increase the A process for developing applications with
value of a numeric variable or array element the Java programming language. It consists of
by 1. ve phases: edit, compile, load, verify, and
interpret.
inheritance
The act of one class (subclass) embodying Java
methods and attributes of a superclass. A programming language that is used to cre-
ate high-end applications that can be used
instanceof operator across a variety of domains.
A Java operator that determines the class of
an object. JavaBean
A Java class that is a reusable software com-
ponent and which can be visually manipulated
using builder tools.

Glossary 243
GLOSSARY
javadoc local variable
A JDK tool that uses declarations and docu- A variable that resides in a method argument
mentation comments in source code to create or in the body of a method.
a document that describes objects.
logical operators
JavaMail Operators that evaluate expressions carrying
An API that provides a platform-independent boolean values.
framework for mailing applications.
loose coupling
JAX-RPC A method of connecting components in a par-
(Java API for XML-based RPC) A technology ticular environment so that they interact
for modeling web services. effectively without having any information
about each other.
JAXB
An API for accessing XML documents. main method
A method that is the entry point of a Java
JDBC application.
(Java DataBase Connectivity)An API that
species how a programmer can access a Math class
database in the format of tables from Java A Java class containing methods and con-
code using the standard classes in Java pro- stants used for common mathematical
gramming. calculations.
JDK method arguments
(Java Development Kit) A tool that provides Java code elements that are passed by a
options to develop Java applications. method and contained within parentheses fol-
lowing the method name.
JMS
(Java Messaging Service) An API used for method declaration
sending and receiving messages between two A Java code element that consists of ve
clients. modiers: access modier, return type,
method name, arguments, and method body.
JNDI
(Java Naming and Directory Interface) An method overloading
interface that helps software clients to search Declaring methods using the same name in
for data and objects through a name. the same class, but with different arguments.
JSP method overriding
(Java Server Pages) A technology that is used Used to create a method in a subclass to
for implementing dynamically generated web replace a dened superclass method imple-
pages along with template pages. mentation.
JVM method
(Java Virtual Machine) Software that provides An action or a behavior that objects based on
an environment to execute Java bytecode. a class can perform or exhibit.
keywords multi-dimensional array
Java-reserved words that may not be used to A Java programming element that is an array
name Java applications or objects, such as of arrays.
classes or methods.
NAICS
literal (North American Industry Classication Sys-
Any item that directly represents a value. tem) It is a standard used for dening
statistical data.

244 Java Fundamentals (Java SE 7)


GLOSSARY
native interface RDMS
A Java interface containing methods used to (Relational Database Management Systems)
invoke native methods. Database management software used for stor-
ing large amounts of data in an organized
native methods format in tables.
The methods implemented in programming
languages other than Java. relational operators
Symbols used to determine relational com-
nested if statement parisons between operands in Java.
An if statement placed within the if block of
another if statement. Remote Interface
A Remote Interface is an interface composed
numeric literal of methods which are attached to an instance
The specic declaration of any numeric value. of the EJB. This would include methods
which provide the actual business logic.
object
A Java code element that is created from a return type
class to hold specic and unique data values. A class or primitive data type of the value
returned by a method.
operands
Variables or values used to perform arithmetic RMI
operations. (Remote Method Invocation) An interface that
performs operations equivalent to remote pro-
operator precedence
cedure calls.
The order in which operators are evaluated
within expressions by Java. RPC
(Remote Procedure Calls) A mechanism that
package
programs from the client computer to request
A collection of classes organized in a folder
access to the program service in a remote
hierarchy by category.
location.
platform-independent
servlet
A software system model that is independent
A Java class that runs on the server-side and
of the specic hardware or software platform
is used for extending the capabilities of a
used to run the software system.
server.
POP3
SMTP
A protocol that manages emails.
(Simple Mail Transfer Protocol) A protocol
postx that manages emails.
Operators used after an operand. SOAP
prex (Simple Object Access Protocol) A protocol
Operators used before an operand. used for transmitting most of the web service
messages.
primitive data types
The eight basic data types built into Java for source code
storing different types of values such as inte- Java statements written by the programmer.
gers, oating-point numbers, characters, and SPI
boolean values.
(Service Provider Interface) An interface that
uses a server, database, or le to make a con-
nection.

Glossary 245
GLOSSARY
SQL syntax
(Structured Query Language) A query lan- A set of rules that dene how a program is
guage used for managing data in RDBMS and written.
its objects structure.
test expression
state variables An expression that includes a logical operator
Object entities that are passed from the server and two operands and returns a boolean value
side to the client side. based on whether the relationship dened by
the logical operator is true.
statement
A Java language construct that contains this keyword
instructions to perform a desired action. The this keyword is a Java keyword that is
used to access the variables and methods of
static method the current object from within the objects
A method dened with the static keyword methods.
that applies to the class, not to individual
objects. thread-safe
A thread has exclusive access to a resource
static variable which no other thread can utilize.
A variable dened with the static keyword
that applies to the class, not to individual UDDI
objects. (Universal Description, Discovery and Inte-
gration) An XML-based registry that
String class businesses use for providing information on
A Java class within java.lang that denes the Internet and register to web service appli-
string variables and constants. cations.
string literal UI
The specic declaration of any series of char- (user interface) A part of the application or
acters. software that is presented to the user to inter-
act and perform operations on software.
StringBuffer class
A Java class within java.lang that denes UML
mutable string objects. (Unied Modeling Language) A language
used to diagrammatically represent the struc-
subclass
ture and functionality of software systems.
A class that inherits all the properties from a
superclass or a baseclass; also called a child units in last place
class. The difference between the two float val-
ues nearest to the result.
superclass
The class from which a subclass inherits; also UNSPSC
called a parent class. (United Nations Standard Products and Ser-
vices Code) It is a standard used for
Swing
classifying products and services.
A Java package used to create a user inter-
face. variable scope
The block of code in which a variable may be
switch statement
used.
A Java ow control statement that provides a
multiple selection structure to determine a variables
course of action. Memory locations that are used to store data
items of a particular primitive type or class.

246 Java Fundamentals (Java SE 7)


GLOSSARY
while loop
A Java ow control statement that executes a
block of code until it meets a specic condi-
tion.
write once, run anywhere
A coding principle where code is written in a
remote machine and executed from any loca-
tion on the server.

WSDL
(Web Services Description Language) A docu-
ment which characterizes the function and
implementation of a web service.

XML parser
Software used for reading XML documents.

Glossary 247
NOTES

248 Java Fundamentals (Java SE 7)


INDEX

INDEX
A executing, 66
abstract classes, 174 bytecode, 3
abstract methods, 173
access modiers, 164 C
ACID, 226 call methods, 109
activity diagrams, 186 calling multiple methods, 106
adornments of UML, 188 case statement, 65
annotations, 206 Also See: statements
API, 3 character literal, 25
Applets, 199 class diagrams, 186
advantages and disadvantages, 199 of UML, 187
deployment issues, 200 classes, 11
application programming interface abstract, 174
See: API and implementing interfaces, 176
arguments concrete, 176
command-line, 144 conicts, 159
arithmetic operators, 31, 32 creating, 16
ArrayOutOfBoundsException, 43 Math, 98
arrays, 41 Math, methods, 106
accessing, 43 path structure, 159
accessing with for...each loops, 77 string, 98, 107
creating, 43 Also See: immutable
data access, 43 StringBuffer, 99, 108
declaration, 41 client-side technology, 194
length, 42 types, 194
multi-dimensional, 42 clientserver architecture, 194
reference, 42 command-line arguments, 144
attributes, 13 and main method, 144
and dot notation, 104 comments, 15
and subclasses, 163 common divisions of UML, 188
automatic type conversion, 32 communication diagrams, 186
components
B Swing, 199
block statements, 21 concatenation, 32
boolean literal, 25 constants, 24
break statement constructor methods, 128
in nested loops, 75 syntax, 128, 131
break statements, 66 constructors, 96
after case statements, 66 dening, 131

Index 249
INDEX
overloading, 130 vs equality operator, 179
syntax, 97 escape character literals, 26
continue statements, 76 exception handling code, 144
syntax, 76 expressions
control ow test, 54
and do...while loops, 85 writing, 36
and for loops, 73 extensibility mechanism of UML, 188
and if statements, 55
and if...else statements, 56 F
and nested for loops, 75 fat client, 194
and nested if statements, 58 ow control statements, 54
and switch statements, 66 for loops, 72
and while loops, 84 and control ow, 73
and while loops, 83
D counters, 73
data hiding, 162 nested, 74
data types optional parts, 73
enumerated, 25 syntax, 73
primitive, 24 for..each loops, 76
decrement operator, 34 accessing array data, 77
default constructors, 128 accessing other data types, 77
default statement, 65 syntax, 76
Also See: statements
deployment diagrams, 186 G
do...while loops, 84 getter method, 148
and control ow, 85 green pages, 224
syntax, 85
H
dot notation, 14, 104
Home Interface, 213
syntax, 105
HTML, 196
driver manager, 226
5.0, 197
E advantages and disadvantages, 197
Eclipse, 3 program, 197
IDE Workbench, 4 HyperText Markup Language
EJB, 207 See: HTML
Home Interface, 213
I
Remote Interface, 214
IDE, 3
technology, 212
identiers, 23
types, 212
if statements, 54
elements
and control ow, 55
and case sensitivity, 11
syntax, 55
encapsulation, 162
if...else statements, 55
Enterprise JavaBeans
and control ow, 56
See: EJB
syntax, 56
enumerated data types, 25
immutability
equality operator
and String class, 98
vs. equals method, 179
immutable, 98
equals method, 179
Also See: classes
syntax, 179
implementing methods, 177

250 Java Fundamentals (Java SE 7)


INDEX
import declaration, 158 Java DataBase Connectivity
syntax, 159 See: JDBC
increment operator, 34 Java Development Kit
innite loop, 73 See: JDK
inheritance, 162 Java EE, 206, 207
rules, 176 advantages and disadvantages, 207
instanceof N-Tier architecture, 207
operator, 180 Java Enterprise Edition
syntax, 180 See: Java EE
instantiating Java ME
Swing components, 200 APIs, 202
instantiation, 13 Java Messaging Service
integer literals, 26 See: JMS
Integrated Development Environment Java Naming and Directory Interface
See: IDE See: JNDI
interface declaration Java platform process, 3
syntax, 172 Java Platform-Micro Edition
interfaces, 172 See: Java ME
creating, 174 Java Server Pages
implementation, 176 See: JSP
native, 173 Java Virtual Machine
interpreted, 2 See: JVM
JavaBean, 148
J javadoc, 15
Java, 2 Also See: JDK
and polymorphism, 123 JavaMail, 228
and relational operators, 32 JavaScript, 197
arithmetic operators, 31 advantages and limitations, 198
class library, 97 code snippet, 198
classes and UML, 188 JAX-RPC, 223
dened interfaces, 173 JAXB, 216
EE, 206 JCP, 206
keywords, 22 JDBC, 226
ME, 202 JDK, 15
method, 5 JFrame methods, 200
MIDlets, 202 JNDI, 220
naming conventions, 12 functions, 220
Java API for XML-based RPC JSP, 207, 210
See: JAX-RPC life cycle, 210
Java application technology, 210
creating, 5 JVM, 3
running, 6 and MIDlets, 202
Java Architecture for XML Binding and polymorphism, 124
See: JAXB and RMI, 221
Java class libraries, 97 JWindow methods, 200
and packages, 97
creating a new object, 99 K
Java Community Process keywords, 22
See: JCP implements, 176

Index 251
INDEX
this, 129 overloading issues, 124
overriding, 168
L parameters, 106
literals, 25 setter, 148
escape characters, 26 static, 138
integer, 26 String class, 107
types, 25 StringBuffer class, 108
logical operators, 33 micro client, 194
loops MIDlets, 202
break statements, 75 application manager, 202
do...while, 84 deployment issues, 203
for, 72 life cycle, 202
for...each, 76 multi-dimensional arrays, 42
nested for, 75 syntax, 43
nested while, 83
while, 83 N
loose coupling, 207 N-Tier architecture, 207
NAICS, 224
M native interfaces, 173
main method, 5 native methods, 173
marshaling, 216 nested for loops, 74
Math class, 98 and control ow, 75
accuracy of methods, 107 break statements, 75
methods, 106 syntax, 75
methods, 5, 14 nested if statements, 57
abstract, 173 and control ow, 58
and dot notation, 104 multiple, 57
and subclasses, 163 syntax, 57, 58
arguments, 105 nested while loops, 83
call, 149 syntax, 84
calling multiple, 106 North American Industry Classication System
constructor, 128 See: NAICS
declaration, 118 numeric literal, 25
declaration header, 119
declaration syntax, 119 O
dening, 120 object casting, 180
equals, 179 object diagrams, 186
execution, 106 object-oriented programming
getter, 148 See: OOP
implementation, 177 objects, 12
JFrame, 200 reusing, 13
JWindow, 200 Swing, 199
main method, 5 OOP, 2
main, with command-line arguments, 144 concepts, 190
Math class, 106 operands, 31
naming them, 14 Also See: arithmetic operators
native, 173 postx, 34
of a Math class, 106 prex, 34
overloading, 123 operator precedence, 35

252 Java Fundamentals (Java SE 7)


INDEX
order, 35 RMI, 221
operators architecture, 221
arithmetic, 31 interface, 222
Also See: operands RPC, 223
decrement, 34
equality, 179 S
increment, 34 sequence diagrams, 186
instanceof, 180 serializable interface, 148
logical, 33 server-side
precedence, 35 components, 207
relational, 32 technologies, 206
overloading constructors, 130 Service Provider Interface
overridden method, 168 See: SPI
syntax, 169 servlets, 209
life cycle, 209
P setter method, 148
packages, 97 Simple Mail Transfer Protocol
and the Java class library, 97 See: SMTP
partial class names, 159 Simple Object Access Protocol
pass by reference, 106 See: SOAP
pass by value, 106 SMTP, 228
perspective, 4 SOAP, 223
platform-independent, 2 and UDDI, 224
polymorphism, 123 source code, 3
dynamic or runtime, 124 specications of UML, 188
POP3, 228 SPI, 220
Post Office Protocol 3 SQL, 226
See: POP3 state transition diagrams, 186
postx, 34 state variables, 208
function, 34 statements, 21
prex, 34 block, 21
function, 34 break, 66
primitive data types, 24 continue, 76
program speed, 159 continue, with while loops, 83
if, 54
R if...else, 55
RDBMS, 226 import declaration, 158
Relational Database Management System nested if, 57
See: RDBMS switch, 65, 67
relational operators, 32 Also See: case
relationships Also See: default
Has-A, 162 switch, with enum, 67
Is-A, 162 system output, 22
Remote Interface, 214 static class members, 139
remote method invocation static methods, 138
See: RMI static variables, 14, 139
Remote Procedure Calls instances, 139
See: RPC String class, 98
return type, 118 immutability, 98

Index 253
INDEX
methods, 107 Unied Modeling Language
syntax, 98 See: UML
string concatenation, 32 United Nations Standard Products and Services
string literal, 25 Code
StringBuffer class, 99 See: UNSPSC
methods, 108 units in last place, 107
syntax, 99 Universal Description, Discovery and Integration
Structured Query Language See: UDDI
See: SQL unmarshaling, 216
subclasses, 159, 163 UNSPSC, 224
access modiers, 164 use case diagrams, 186
and attributes, 163 user interface
and methods, 163 See: UI
syntax, 163
V
superclasses, 163
variables, 23
access modiers, 164
and literals, 25
method overriding, 168
creating, 27
syntax, 163
declaration, 24
Swing
local, 119
components, 199
multiple, 24
components, instantiating, 200
scope, 119
container types, 200
state, 208
containers, 199
static, 139
deployment issues, 200
switch statements, 65
W
and control ow, 66
web browser, 196
data types, 65
Web Services Description Language
with enum, 67
See: WSDL
syntax, 2
while loops, 83
system output statements, 22
and control ow, 84
T and for loops, 83
test expression, 54 continue statement, 83
thin client, 194 syntax, 83
thin UI clients, 196 white pages, 224
deployment issues, 198 write once, run anywhere, 148
this keyword, 129 WSDL, 224
syntax, 130
X
thread-safe, 200
XML binding, 216
U XML parser, 215
UDDI, 224 types, 215
UI, 196
Y
UML, 186
yellow pages, 224
class diagrams, 187
diagrams, 186
Java classes, 188
notations, 190
OOP concepts, 190

254 Java Fundamentals (Java SE 7)