576
Oracle Instructor D17249GC11 Edition 1.1 August 2004 D39815 e10g: Java Programming r Guide - Volume 1

Java Programming

Embed Size (px)

Citation preview

Page 1: Java Programming

Oracle

Instructor

D17249GC11Edition 1.1August 2004D39815

e10g: Java Programming

r Guide - Volume 1

Page 2: Java Programming

Copyright © 2004, Orac

This documentation conprovided under a licenseis also protected by copy

Authors

Jeff GallusGlenn Stokol is also protected by copy

If this documentation is dDefense, then it is deliveapplicable:

Restricted Rights Lege

Use, duplication or disclocommercial computer sounder Federal law, as seRights in Technical Data

Technical Contributorsand ReviewersKenneth CooperPeter DriverChristian DugasCraig HollisterChika Izumi

This material or any portwithout the express priois a violation of copyrigh

If this documentation is dDepartment of Defense, FAR 52.227-14, Rights i

The information in this dproblems in the docume

Chika IzumiPete LaseauGlenn MaslenMonica MotleyGayathri Rajagopal

PublisherPoornima G

problems in the documeOracle Corporation, 500Oracle Corporation does

All references to Oracle of Oracle Corporation.

All other products or commay be trademarks of th

cle. All rights reserved.

tains proprietary information of Oracle Corporation. It is e agreement containing restrictions on use and disclosure and yright law. Reverse engineering of the software is prohibited.yright law. Reverse engineering of the software is prohibited. delivered to a U.S. Government Agency of the Department of ered with Restricted Rights and the following legend is

end

osure by the Government is subject to restrictions for oftware and shall be deemed to be Restricted Rights software et forth in subparagraph (c)(1)(ii) of DFARS 252.227-7013, a and Computer Software (October 1988).

tion of it may not be copied in any form or by any means r written permission of Oracle Corporation. Any other copying t law and may result in civil and/or criminal penalties.

delivered to a U.S. Government Agency not within the then it is delivered with “Restricted Rights,” as defined in n Data-General, including Alternate III (June 1987).

ocument is subject to change without notice. If you find any ntation please report them in writing to Education Productsntation, please report them in writing to Education Products, Oracle Parkway, Box SB-6, Redwood Shores, CA 94065.

s not warrant that this document is error-free.

and Oracle products are trademarks or registered trademarks

mpany names are used for identification purposes only, and heir respective owners.

Page 3: Java Programming

Contents

Preface

I IntroductionObjectives I-2Course Overview I-3

1 Introducing the Java and Oracle Platformst oduc g t e Ja a a d O ac e at o sObjectives 1-2What Is Java? 1-3Key Benefits of Java 1-4An Object-Oriented Approach 1-6Platform Independence 1-7Using Java with Enterprise Internet Computing 1-8Using the Java Virtual Machine 1-10Using the Java Virtual Machine 1-10How Does JVM Work? 1-12Benefits of Just-In-Time (JIT) Compilers 1-14Implementing Security in the Java Environment 1-16Deployment of Java Applications 1-18Using Java with Oracle 10g 1-19Java Software Development Kit 1-20Using the Appropriate Development Kit 1 21Using the Appropriate Development Kit 1-21Integrated Development Environment 1-22Exploring the JDeveloper Environment 1-23Oracle10g Products 1-24Summary 1-25

2 Defining Object-Oriented PrinciplesObjectives 2-2Objectives 2 2What Is Modeling? 2-4What Are Classes and Objects? 2-5An Object’s Attributes Maintain Its State 2-6Objects Have Behavior 2-8Objects Are Modeled as Abstractions 2-9Defining Object Composition 2-11The Donut Diagram 2 13The Donut Diagram 2-13Guided Practice: Spot the Operations and Attributes 2-14Collaborating Objects 2-15Objects Interact Through Messages 2-16What Is a Class? 2-17How Do You Identify a Class? 2-18Comparing Classes and Objects 2-19Wh t I E l ti ? 2 21What Is Encapsulation? 2-21What Is Inheritance? 2-22

iii

Page 4: Java Programming

Using the “Is-a-Kind-of” Relationship 2-23What Is Polymorphism? 2-24Architecture Rules for Reuse 2-26Engineering for a Black Box Environment 2-27Order Entry UML Diagram 2-28Summary 2-29Practice 2: Overview 2-30Order Entry System Partial UML Class Model 2-33

3 Basic Java Syntax and Coding ConventionsObjectives 3-2Examining Toolkit Components 3-4Exploring Packages in J2SE/J2EE 3-5Documenting Using the J2SE 3-6Contents of a Java Source 3-7Establishing Naming Conventions 3-8More About Naming Conventions 3-10gDefining a Class 3-12Rental Class: Example 3-13Creating Code Blocks 3-15Defining Java Methods 3-16Examples of a Method 3-17Declaring Variables 3-18Examples of Variables in the Context of a Method 3-19Examples of Variables in the Context of a Method 3 19Rules for Creating Statements 3-20What Are JavaBeans? 3-21Managing Bean Properties 3-22Exposing Properties and Methods 3-23JavaBean Standards at Design Time 3-24Compiling and Running a Java Application 3-25The CLASSPATH Variable 3-26The CLASSPATH Variable 3-26CLASSPATH: Example 3-27Summary 3-28Practice 3: Overview 3-29

4 Exploring Primitive Data Types and OperatorsObjectives 4-2Reserved Keywords 4-4Reserved Keywords 4 4Variable Types 4-5Primitive Data Types 4-7What Are Variables? 4-9Declaring Variables 4-10Local Variables 4-11Defining Variable Names 4-12What Are Numeric Literals? 4-13What Are Numeric Literals? 4-13What Are Nonnumeric Literals? 4-15

iv

Page 5: Java Programming

Guided Practice: Declaring Variables 4-17What Are Operators? 4-19Categorizing Operators 4-20g g pUsing the Assignment Operator 4-21Working with Arithmetic Operators 4-22More on Arithmetic Operators 4-23Examining Conversions and Casts 4-24Incrementing and Decrementing Values 4-26Relational and Equality Operators 4-27Using the Conditional Operator (?:) 4-28Using the Conditional Operator (?:) 4 28Using Logical Operators 4-29Compound Assignment Operators 4-30Operator Precedence 4-31More on Operator Precedence 4-32Concatenating Strings 4-33Summary 4-34Practice 4: Overview 4 35Practice 4: Overview 4-35

5 Controlling Program FlowObjectives 5-2Categorizing Basic Flow Control Types 5-4Using Flow Control in Java 5-6Using the if Statement 5-7Nesting if Statements 5-8Nesting if Statements 5 8Guided Practice: Spot the Mistakes 5-9Defining the switch Statement 5-10More About the switch Statement 5-12Looping in Java 5-13Using the while Loop 5-14Using the do…while Loop 5-15Using the for Loop 5-16Using the for Loop 5-16More About the for Loop 5-17Guided Practice: Spot the Mistakes 5-18The break Statement 5-19Summary 5-20Practice 5: Overview 5-21

6 Building Applications with Oracle JDeveloper 10g6 Building Applications with Oracle JDeveloper 10gObjectives 6-2What Is Oracle JDeveloper 10g? 6-3Exploring the JDeveloper Environment 6-4Examining Workspaces 6-5What Are Projects? 6-7Creating JDeveloper Items 6-8Creating an Application Workspace 6-9Creating an Application Workspace 6-9Specifying Project Details 6-10Selecting Additional Libraries 6-11

v

Page 6: Java Programming

Adding a New J2SE 6-12Looking at the Directory Structure 6-13Exploring the Skeleton Java Application 6-14p g ppFinding Methods and Fields 6-15Supporting Code Development with Profiler and Code Coach 6-16Customizing JDeveloper 6-17Using the Help System 6-18Obtaining Help on a Topic 6-19Oracle JDeveloper 10g Debugger 6-20Setting Breakpoints 6-22Setting Breakpoints 6 22Using the Debugger Windows 6-24Stepping Through a Program 6-25Watching Data and Variables 6-26Summary 6-27Practice 6: Overview 6-28

7 Creating Classes and Objectsg jObjectives 7-2Using Java Classes 7-4Comparing Classes and Objects 7-5Creating Objects 7-6Using the new Operator 7-7Comparing Primitives and Objects 7-8Using the null Reference 7-9Using the null Reference 7 9Assigning References 7-10Declaring Instance Variables 7-11Accessing public Instance Variables 7-12Defining Methods 7-13Calling a Method 7-14Specifying Method Arguments: Examples 7-15Returning a Value from a Method 7 16Returning a Value from a Method 7-16Calling Instance Methods 7-17Applying Encapsulation in Java 7-18Passing Primitives into Methods 7-19Passing Object References into Methods 7-20What Are Class Variables? 7-21Initializing Class Variables 7-22Wh t A Cl M th d ? 7 23What Are Class Methods? 7-23Guided Practice: Class Methods or Instance Methods 7-24Examples in Java 7-25Creating Classes Using the Class Editor 7-26What Are Java Packages? 7-27Grouping Classes in a Package 7-28

vi

Page 7: Java Programming

Setting the CLASSPATH with Packages 7-29Access Modifiers 7-30Summary 7-32yPractice 7: Overview 7-33

8 Object Life Cycle and Inner ClassesObjectives 8-2Overloading Methods 8-4Using the this Reference 8-5Initializing Instance Variables 8-6What Are Constructors? 8-7Defining and Overloading Constructors 8-8Sharing Code Between Constructors 8-9final Variables, Methods, and Classes 8-10Reclaiming Memory 8-11Using the finalize() Method 8-12What Are Inner Classes? 8-13Using Member Inner Class 8-14Using Local Inner Class 8-15Defining Anonymous Inner Classes 8-16Using the Calendar Class 8-17Summary 8-18Practice 8: Overview 8-19

9 Using Strings, String Buffer, Wrapper, and Text-Formatting ClassesObjectives 9-2What Is a String? 9-3Creating a String 9-4Concatenating Strings 9-5Performing Operations on Strings 9-6Performing More Operations on Strings 9-7g p gComparing String Objects 9-8Producing Strings from Other Objects 9-9Producing Strings from Primitives 9-10Producing Primitives from Strings 9-11Wrapper Class Conversion Methods 9-12Changing the Contents of a String 9-13Formatting Classes 9-14Formatting Classes 9 14Using the SimpleDateFormat Class 9-15Using the MessageFormat Class 9-16Using DecimalFormat 9-17Guided Practice 9-18Using Regular Expressions 9-20

vii

Page 8: Java Programming

About System.out.println 9-23About OutputStream and PrintStream 9-24What Is Object Serialization? 9-25jSerialization Streams, Interfaces, and Modifiers 9-28Summary 9-29Practice 9: Overview 9-30

10 Reusing Code with Inheritance and PolymorphismObjectives 10-2Key Object-Oriented Components 10-3Example of Inheritance 10-4Specifying Inheritance in Java 10-5Defining Inheritance by Using Oracle JDeveloper 10g 10-6What Does a Subclass Object Look Like? 10-7Default Initialization 10-8The super Reference 10-9The super Reference Example 10-10pUsing Superclass Constructors 10-11Specifying Additional Methods 10-13Overriding Superclass Methods 10-15Invoking Superclass Methods 10-17Example of Polymorphism in Java 10-19Treating a Subclass as Its Superclass 10-20Browsing Superclass References by Using Oracle JDeveloper 10g 10-21Browsing Superclass References by Using Oracle JDeveloper 10g 10 21Acme Video and Polymorphism 10-22Using Polymorphism for Acme Video 10-23Using the instanceof Operator 10-25Limiting Methods and Classes with final 10-26Ensuring Genuine Inheritance 10-27Summary 10-28

11 Using Arrays and CollectionsObjectives 11-2What Is an Array? 11-3Creating an Array of Primitives 11-4Declaring an Array of Primitives 11-5Creating an Array Object for an Array of Primitives 11-6Initializing Array Elements 11-8Initializing Array Elements 11 8Creating an Array of Object References 11-9Initializing the Objects in the Array 11-10Using an Array of Object References 11-11Arrays and Exceptions 11-12Multidimensional Arrays 11-13main() Revisited 11-14

viii

Page 9: Java Programming

Working with Variable-Length Structures 11-15Modifying a Vector 11-16Accessing a Vector 11-17gJava Collections Framework 11-18Collections Framework Components 11-20Using ArrayList and Hashtable 11-21Using Iterators 11-22Summary 11-23Practice 11: Overview 11-24

12 Structuring Code by Using Abstract Classes and InterfacesObjectives 12-2Defining Abstract Classes 12-3Creating Abstract Classes 12-4What Are Abstract Methods? 12-5Defining Abstract Methods 12-7Defining and Using Interfaces 12-8g gExamples of Interfaces 12-9Creating Interfaces 12-10Implementing Interfaces 12-12Sort: A Real-World Example 12-13Overview of the Classes 12-14How the Sort Works 12-15The Sortable Interface 12-16The Sortable Interface 12 16The Sort Class 12-17The Movie Class 12-18Using the Sort 12-19Using instanceof with Interfaces 12-20Summary 12-21Practice 12: Overview 12-22

13 Throwing and Catching ExceptionsObjectives 13-2What Is an Exception? 13-3How Does Java Handle Exceptions? 13-4Advantages of Java Exceptions: Separating Error Handling Code 13-5Advantages of Java Exceptions: Passing Errors Up the Call Stack 13-7Advantages of Java Exceptions: Exceptions Cannot Be Ignored 13-8Advantages of Java Exceptions: Exceptions Cannot Be Ignored 13 8Checked Exceptions, Unchecked Exceptions, and Errors 13-9What to Do with an Exception 13-11Catching and Handling Exceptions 13-12Catching a Single Exception 13-13Catching Multiple Exceptions 13-14

ix

Page 10: Java Programming

Cleaning Up with a finally Block 13-15Catching and Handling Exceptions: Guided Practice 13-16Allowing an Exception to Pass to the Calling Method 13-18g p gThrowing Exceptions 13-19Creating Exceptions 13-20Catching an Exception and Throwing a Different Exception 13-21Summary 13-22Practice 13: Overview 13-23

14 User Interface Design: Swing Basics Planning the Application LayoutObjectives 14-2Running Java UI Applications 14-3AWT, Swing, and JFC 14-4Swing Features 14-6Lightweight or Heavyweight Components? 14-8Planning the UI Layout 14-9The Containment Hierarchy 14-10yTop-Level Containers 14-12Intermediate Containers 14-14Atomic Components 14-15Layout Management Overview 14-16Border Layout 14-18GridBag Layout 14-19GridBag Constraints 14-20GridBag Constraints 14 20Using Layout Managers 14-22Combining Layout Managers 14-24Using Frames or Dialogs 14-25Using JPanel Containers 14-27Adding Borders to Components 14-29Using Internal Frames 14-30Swing Text Controls 14 32Swing Text Controls 14-32Adding Components with Oracle JDeveloper 10g 14-33Creating a Frame 14-34Adding Components 14-35Setting Pluggable Look and Feel 14-37Summary 14-39Practice 14: Overview 14-40

15 Adding User Interface Components and Event HandlingObjectives 15-2Swing Components 15-3Swing Components in JDeveloper 15-5Invoking the UI Editor 15-7How to Add a Component to a Form 15-8Edit the Properties of a Component 15-9Edit the Properties of a Component 15-9Code Generated by JDeveloper 15-10

x

Page 11: Java Programming

Creating a Menu 15-12Using JDeveloper Menu Editor 15-13Practice 15-1: Overview 15-14UI for Java Application 15-15Java Event Handling Model 15-20Event Handling Code Basics 15-21Event Handling Process: Registration 15-22Event Handling Process: The Event Occurs 15-24Event Handling Process: Running the Event Handler 15-25Using Adapter Classes for Listeners 15-26Using Adapter Classes for Listeners 15 26Swing Model View Controller Architecture 15-27Basic Text Component Methods 15-30Basic JList Component Methods 15-31What Events Can a Component Generate? 15-32How to Define an Event Handler in JDeveloper 15-33Default Event Handling Code Style Generated by JDeveloper 15-34Completing the Event Handler Method 15 35Completing the Event Handler Method 15-35Summary 15-36Practice 15-2: Overview 15-37

16 Using JDBC to Access the DatabaseObjectives 16-2Java, J2EE, and Oracle 10g 16-3Connecting to a Database with Java 16-4Connecting to a Database with Java 16 4What Is JDBC? 16-5Preparing the Environment 16-6Steps for Using JDBC to Execute SQL Statements 16-8Step 1: Registering the Driver 16-9Connecting to the Database 16-10Oracle JDBC Drivers: Thin Client Driver 16-11Oracle JDBC Drivers: OCI Client Drivers 16 12Oracle JDBC Drivers: OCI Client Drivers 16-12Choosing the Right Driver 16-13Step 2: Getting a Database Connection 16-14About JDBC URLs 16-15JDBC URLs with Oracle Drivers 16-16Step 3: Creating a Statement 16-17Using the Statement Interface 16-18St 4 E ti Q 16 19Step 4a: Executing a Query 16-19The ResultSet Object 16-20Step 4b: Submitting DML Statements 16-21Step 5: Processing the Query Results 16-23Step 6: Closing Connections 16-24A Basic Query Example 16-25

xi

Page 12: Java Programming

Mapping Database Types to Java Types 16-26Handling an Unknown SQL Statement 16-28Handling Exceptions 16-29g pManaging Transactions 16-30The PreparedStatement Object 16-31How to Create a PreparedStatement 16-32How to Execute a PreparedStatement 16-33Maximize Database Access 16-34Connection Pooling 16-35Summary 16-38Summary 16 38Practice 16: Overview 16-39

17 Deploying Applications by Using Java Web StartObjectives 17-2What Is Java Web Start? 17-3Running a Web Start Application 17-4Advantages of Web Start 17-5Examining the JNLP File 17-6Deploying Applications with JDeveloper 17-7Creating the Deployment Profile File 17-8Saving the Deployment Profile 17-9Selecting Files to Deploy 17-10Making an Executable .jar File 17-11Creating and Deploying the Archive File 17-12g p y gUsing JDeveloper to Deploy an Application to Java Web Start 17-13Step 1: Generate Deployment Profiles and Archive Application 17-14Step 2a: Start OC4J 17-15Step 2b: Creating a Connection 17-16Step 3: Use Web Start Wizard to Create a JNLP File 17-17Step 4: Archive and Deploy the Application to the OC4J Server 17-18Summary 17-19Summary 17 19Practice 17: Overview 17-20

Appendix A: Practice Solutions

Appendix B: Java Language Quick-Reference Guide

Appendix C: Order Entry Solution

xii

Page 13: Java Programming

Preface

Page 14: Java Programming
Page 15: Java Programming

Profile

Prerequisites• Required: Previous experience with another 3GL programming language, preferably a structured

l h P l Clanguage such as Pascal or C• Suggested: Familiarity with basic HTML

How This Course Is OrganizedOracle 10g: Java Programming is an instructor-led course featuring lectures and hands-on exercises. Online demonstrations and written practice sessions reinforce the concepts and skills introduced.

Preface - 3

Page 16: Java Programming

Related Publications

Oracle PublicationsTitle Part NumberOracle 10g: Build J2EE Applications (inClass course) D17247GC10Oracle JDeveloper 10g: Build Applications with Oracle ADF (inClass course) D16975GC10Oracle JDeveloper Handbook (Oracle Press)

Additional Publications• System release bulletins• System release bulletins• Installation and user’s guides• Read-me files• International Oracle User’s Group (IOUG) articles• Oracle Magazine

Preface - 4

Page 17: Java Programming

Typographic Conventions

Typographic Conventions In Text

Convention Element ExampleConvention Element Example

Bold Emphasized words and phrases in Web content only

To navigate within this application , do notclick the Back and Forward buttons.

Bold italic Glossary terms (if there is a glossary)

The algorithm inserts the new key.

Brackets Key names Press [Enter].

Caps and lowercase

Buttons,check boxes,triggers,

i d

Click the Executable button.

Select the Registration Required check box.

windowsAssign a When -Validate-Item trigger.

Open the Master Schedule window.

Carets Menu paths Select File > Save.

Commas Key sequences Press and release these keys one at a time:[Alt], [F], [D]

Preface - 5

Page 18: Java Programming

Typographic Conventions (continued)

Typographic Conventions In Text (continued)

Convention Object or Term ExampleConvention Object or Term Example

Courier New, case sensitive

Code output, SQL and PL/SQL code elements, Java code elements, directory names, file names, passwords,

h

Code output: debug.seti (‘I’,300);

SQL code elements: Use the SELECT command to view information stored in the last_name column of the emp table. Java code elements: Java programming involves the St i and St i B ff classespath names,

user input, usernames

String and StringBuffer classes.

Directory names: bin (DOS), $FMHOME (UNIX)

File names: Locate the init.ora file.

Passwords: Use tiger as your password.

Path names: Open c:\my_docs\projects.

U i t E t 300User input: Enter 300.

Usernames: Log on as scott.

Initial cap Graphics labels (unless the term is a proper noun)

Customer address (but Oracle Payables)

Italic Emphasized words Do not save changes to the databaseItalic Emphasized words and phrases in print publications, titles of books and courses, variables

Do not save changes to the database. For further information, see Oracle7 Server SQL Language Reference Manual. Enter [email protected], where user_id is the name of the user.

Plus signs Key combinations Press and hold these keys simultaneously: [Control] + [Alt] + [Delete][Control] + [Alt] + [Delete]

Quotation marks

Lesson and chapter titles in cross references, interface elements with long names that have only initial caps

This subject is covered in Unit II, Lesson 3, “Working with Objects.” Select the “Include a reusable module component” and click Finish.

only initial caps Use the “WHERE clause of query” property.

Preface - 6

Page 19: Java Programming

Typographic Conventions (continued)

Typographic Conventions in Navigation PathsThis course uses simplified navigation paths, such as the following example, to direct you through Oracle A li iApplications. Example:Invoice Batch Summary(N) Invoice > Entry > Invoice Batches Summary (M) Query > Find (B) Approve

This simplified path translates to the following:p p g1. (N) From the Navigator window, select Invoice > Entry > Invoice Batches Summary.2. (M) From the menu, select Query > Find.3. (B) Click the Approve button.Notation:

(N) = Navigator (I) = Icon(M) M (H) H li k(M) = Menu (H) = Hyperlink(T) = Tab (B) = Button

Preface - 7

Page 20: Java Programming
Page 21: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Introduction

Schedule: Timing Topic10 minutes Lecture10 minutes Total

Page 22: Java Programming

Oracle10g: Java Programming I-2

I-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this course, you should be able to do the following:• Write stand-alone applications with the Java

programming language• Develop and deploy an application• Build, generate, and test application components

by using Oracle JDeveloper 10g

Page 23: Java Programming

Oracle10g: Java Programming I-3

I-3 Copyright © 2004, Oracle. All rights reserved.

Course Overview

• This course teaches you how to write Java applications.

• You also learn how to build, debug, and deploy applications by using Oracle JDeveloper 10g.

• The development environment is Oracle JDeveloper 10g and the Oracle Database.

Instructor NoteThe database used for this course is 9.2. It is the latest edition supported by the Development Tools.

Page 24: Java Programming
Page 25: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Introducing the Javaand Oracle Platforms

Schedule: Timing Topic60 minutes Lecture00 minutes Practice60 minutes Total

Page 26: Java Programming

Oracle10g: Java Programming 1-2

1-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Identify the key elements of Java• Describe the Java Virtual Machine (JVM)• Examine how Java is used to build applications• Identify the key components of the J2SE Java

Development Kit (known as JDK or SDK)• Describe Java deployment options

Lesson AimThis lesson introduces the background and usefulness of the Java language. It discusses Java’s position with the Oracle10g. Java is the programming language of choice for Internet applications. It has gained this status because of its robust nature, the object-orientation of the language, the depth of its predefined classes, and its “write once, run anywhere” deployment model. You learn how Java supports object-oriented programming and architectural neutral deployment.

Page 27: Java Programming

Oracle10g: Java Programming 1-3

1-3 Copyright © 2004, Oracle. All rights reserved.

What Is Java?

Java:• Is a platform and an object-oriented language• Was originally designed by Sun Microsystems for

consumer electronics• Contains a class library• Uses a virtual machine for program execution

What Is Java?Designed by Sun MicrosystemsJava is a platform and an object-oriented programming language, which was originally developed by Sun Microsystems, Inc. It was created by James Gosling for use in consumer electronics. Because of the robustness and platform-independent nature of the language, Java soon moved beyond the consumer electronics industry and found a home on the World Wide Web. Java is a platform, which means that it is a complete development and deployment environment.Class LibrariesJava contains a broad set of predefined classes, which contain attributes and methods that handle most of the fundamental requirements of programs. Window management, input/output, and network communication classes are included in the Java Developer’s Kit (JDK). The class library makes Java programming significantly easier and faster to develop when compared with other languages. JDK also contains several utilities to facilitate development processes. These utilities handle operations, such as debugging, deployment, and documentation.Java Uses a Virtual MachineOne of the key elements of the Java language is platform independence. A Java program that is written on one platform can be deployed on any other platform. This is usually referred to as “write once, run anywhere” (WORA). This task is accomplished through the use of the Java Virtual Machine (JVM). JVM runs on a local machine and interprets the Java bytecode and converts it into platform-specific machine code.

Page 28: Java Programming

Oracle10g: Java Programming 1-4

1-4 Copyright © 2004, Oracle. All rights reserved.

Key Benefits of Java

• Object-oriented• Interpreted and platform-independent• Dynamic and distributed• Multithreaded• Robust and secure

Key Benefits of JavaObject-OrientedAn object is an entity that has data attributes, plus a set of functions that are used to manipulate the object. Java is a strongly typed language, which means that almost everything in Java is an object. The main exceptions are the primitive data types, such as integers and characters.Interpreted and Platform IndependentJava programs are interpreted to the native machine’s instruction set at run time. Because Java executes under the control of a JVM, Java programs can run on any operating system that provides a JVM.Dynamic and DistributedJava classes can be downloaded dynamically over the network when required. In addition, Java provides extensive support for client-server and distributed programming.

Page 29: Java Programming

Oracle10g: Java Programming 1-5

Key Benefits of Java (continued)MultithreadedJava programs can contain multiple threads to carry out many tasks in parallel. Multithreading capability is built into Java and is under the control of the platform-dependent JVM.Robust and SecureJava has built-in capabilities to prevent memory corruption. Java automatically manages the processes of memory allocation and array bounds checking. It prohibits pointer arithmetic, and restricts objects to named spaces in memory.

Instructor NoteHistorically speaking, Gosling’s team started using C++ initially, but soon found that C++ programs were too liable to crash, partly due to language complexity, and also because of the destructive capabilities of C++ constructs, such as pointers. To overcome these problems, Gosling’s team invented their own object-oriented language, called Oak. To make it robust, they eliminated problematic language constructs, and made it architecturally neutral, by fully specifying the semantics of the language and creating a virtual machine to execute the programs. Oak was designed from the ground up to look like C++ but also to reduce the learning curve for those who knew C++. Oak was renamed Java, when it gained popularity in the World Wide Web and the revolution began. The robustness, compactness, platform independence, and flexibility that had been designed for the electronics consumer market make Java the ideal language for creating Web-based programs. Because Java is an interpreted language, it is slower than C++ in terms of execution speed, but this is often unimportant when dealing with user interactions.

Page 30: Java Programming

Oracle10g: Java Programming 1-6

1-6 Copyright © 2004, Oracle. All rights reserved.

An Object-Oriented Approach

• Objects and classes– An object is a run-time representation of a “thing.”– A class is a “static definition of things.”

• Class models elaborate:– Existing classes and objects– Behaviour, purpose, and structure– Relationships between classes– Relationships between run-time objects

• Same models exist throughout the project.

Analysis Implementation Integrationand testingDesign

CLASS MODELS

An Object-Oriented ApproachObject-oriented programming is a powerful and natural paradigm that is used to write application programs. The approach ensures that programs survive the changes accompanying the growth of a business and its systems. After you understand the function of each object and develop clean, reliable interfaces between the functions, you can decommission older parts of an application system without concern.Classes provide a means to capture the structure and behavior of a real-world person, place, or thing, and represent a one-to-one mapping between the real-world object and its implementation. This one-to-one mapping tends to eliminate the typical transformations that are found in nonobject-oriented design approaches.

Page 31: Java Programming

Oracle10g: Java Programming 1-7

1-7 Copyright © 2004, Oracle. All rights reserved.

Platform Independence

• Java source code is stored as text in a .java file.• The .java file is compiled into .class files.• A .class file contains Java bytecodes

(instructions).• The bytecodes are interpreted at run time.

– The Java .class file is the executable code.

Compile

Movie.java

JVM

Running programMovie.class

(javac) (java)

Platform IndependenceJava Is an Interpreted LanguageJava program source code is stored in .java files. For example, a Java program dealing with movies in a video rental company may have files called Movie.java, Customer.java, and Rental.java.Each .java file is compiled into a corresponding .class file with the same name. For example, a Movie.java compiles to at least one class file. (Inner classes is quite common.) But, the public Movie.java compiles to one Movie.class. These .class files contain Java bytecodes, which are platform-independent machine instructions.Java Virtual Machine (JVM)JVM provides the environment for running Java programs. The JVM interprets Java bytecodes into the native instruction set for the machine on which the program is currently running. The same .class files can be executed unaltered on any platform for which a JVM is provided. For this reason, JVM is sometimes referred to as a virtual processor.Traditional Compiled LanguagesWhen compiling a traditional language such as C, the code written by the programmer is converted into machine instructions for the platform on which the compilation takes place. This compiled program can then run only on machines that have the same processor as that on which it was compiled, such as Intel, SPARC, or Alpha.

Page 32: Java Programming

Oracle10g: Java Programming 1-8

1-8 Copyright © 2004, Oracle. All rights reserved.

Using Java with EnterpriseInternet Computing

Web server

Application server

Presentation Businesslogic

• Servlets• JavaServer

Pages (JSPs)

• EnterpriseJavaBeans (EJB)

• CORBA

Client Data

Java and Enterprise Internet ComputingYou can design Java programs as server-based components that form scalable Internet applications.The currently accepted model for Java Internet computing divides the end-to-end application process into several logical tiers. To utilize this model, JavaSoft defined the Java2, Enterprise Edition (J2EE). There are four logical tiers:Client TierWhen Java is needed to execute on client machines, it is typically implemented as a browser-based application. But a thin client can be just Web pages that are delivered from a server as HTML.Presentation TierThis is executed on a Web server. Code in this tier handles the application’s presentation to the client. Common Java features for this function are servlets and JavaServer Pages (JSPs). Servlets and JSPs can each generate dynamic HTML for display as Web pages to clients.

Page 33: Java Programming

Oracle10g: Java Programming 1-9

Java and Enterprise Internet Computing (continued)Application (Business Logic) TierYou can use Java on an application server to implement shareable, reusable business logic as application components. A common way to implement this is to use component models, such as Enterprise JavaBeans (EJB) and Common Object Request Broker Architecture (CORBA) objects. These two components are also to be considered during design time, when a distributed environment is required.Data TierThe data server not only stores data, but can also store and execute Java code, particularly where this code is data intensive or enforces validation rules pertaining to the data. You can also use Business Components, from Oracle’s Application Development Framework (ADF), to support the data access of your application.

Page 34: Java Programming

Oracle10g: Java Programming 1-10

1-10 Copyright © 2004, Oracle. All rights reserved.

Using the Java Virtual Machine

Operating system

JVM

Application

Running Java ApplicationsAll Java applications run within a Java Virtual Machine (JVM). JVM is invoked differently depending on whether the Java program is an application or an applet.ApplicationsYou can run stand-alone applications by invoking a local JVM directly from the operating system command line and supplying the name of the main class for the application. After loading the applications main class file, JVM runs the program by calling a known entry point in the class; that is, a public static method called main(...). JVM runs the code by interpreting the bytecodes in the Java program and converting bytecode into platform-specific machine instructions.

Page 35: Java Programming

Oracle10g: Java Programming 1-11

Running Java Applications (continued)Running Java AppletsA Java applet is a special type of Java program that is used in Web pages. When a Web browser reads an HTML page with an applet tag, it downloads the applet over the network to the local system and runs the applet in a JVM that is built into the browser. The browser invokes a specific call sequence of known methods in the Java applet class to execute the Java code in the context of the browser’s JVM. The applet entry points differ from the entry point that is used by JVM to run stand-alone applications.In the case of an applet, the presentation server is not necessarily used. A Java application is quite capable, and typically is configured, to connect directly to the business logic. Applets are not covered in this course, and are only presented here for completeness. In this course, during deployment of your application, you use the Java Web Start product.

Page 36: Java Programming

Oracle10g: Java Programming 1-12

1-12 Copyright © 2004, Oracle. All rights reserved.

How Does JVM Work?

• The class loader loads all required classes.– JVM uses a CLASSPATH setting to locate class files.

• JVM Verifier checks for illegal bytecodes.• JVM Verifier executes bytecodes.

– JVM may invoke a Just-In-Time (JIT) compiler.• Memory Manager releases memory used by the

dereferenced object back to the OS.– JVM handles Garbage collection.

How Does JVM Work?JVM Class LoaderWhen a .class file is run, it may require other classes to help perform its task. These classes are loaded automatically by the class loader in JVM. The required classes may reside on the local disk or on another system across the network. JVM uses the CLASSPATH environment variable to determine the location of local .class files. The classpath can be added in run time by using the java -cp or -classpath option. Classes that are loaded from the network are kept in a separate namespace from those on the local system. This prevents name clashes and the replacement or overriding of standard classes, malicious or otherwise.JVM VerifierIt is the job of the verifier to make sure that the Java code that is being interpreted does not violate any of the basic rules of the Java language and that the code is from a trusted source. A trusted source is an option; and if used, the check is not performed.This validation ensures that there are no memory access violations or other illegal actions performed.

Page 37: Java Programming

Oracle10g: Java Programming 1-13

How Does JVM Work? (continued)Bytecode InterpreterJVM is the bytecode interpreter that executes the bytecodes for the loaded class. If enabled, JVM can use just-in-time (JIT) technology to translate Java bytecodes into native machine instructions.Memory ManagementJVM keeps track of all instances in use. After an instance is no longer in use, JVM is allowed to release the memory that is used by that object. It performs the release of memory after the object is no longer needed, but not necessarily immediately. The process (thread) that JVM uses to manage dereferenced objects is called garbage collection.

Page 38: Java Programming

Oracle10g: Java Programming 1-14

1-14 Copyright © 2004, Oracle. All rights reserved.

Benefits of Just-In-Time (JIT) Compilers

JIT compilers:• Improve performance• Are useful if the same bytecodes are executed

repeatedly• Translate bytecodes to native instruction• Optimize repetitive code, such as loops• Use Java HotSpot VM for better performance and

reliability

Just-In-Time (JIT) CompilersJVMs translate Java bytecodes into native machine instructions. What happens if the same code is executed again, later in the program? In an environment without JIT compilers, the code is interpreted every time it is encountered, even if it has already been interpreted earlier in the program.The compilers are designed to easily translate bytecode into machine code, which is optimized to run on the target platform.Benefits of Just-In-Time CompilersMost JVMs now support JIT compilation. JIT compilers translate bytecodes only the first time that they are encountered; if the same code is executed later, then it is automatically mapped to the corresponding native machine instruction.JIT compilers enable Java programs to run more quickly because they obviate the need for repeated translation of bytecodes to native machine instructions. This is especially effective in repetitive code, such as loops or recursive functions. Some JIT compilers are intelligent enough to optimize groups of related bytecodes into more efficient native machine instructions.

Page 39: Java Programming

Oracle10g: Java Programming 1-15

Just-In-Time (JIT) Compilers (continued)Java HotSpotThe Java HotSpot virtual machine (VM) is a key component in maximizing the deployment of enterprise applications. It is a core component of Java 2, Standard Edition (J2SE) software, which is supported by leading application vendors and technologies. Java HotSpot VM supports virtually all aspects of development, deployment, and management of corporate applications.

Page 40: Java Programming

Oracle10g: Java Programming 1-16

1-16 Copyright © 2004, Oracle. All rights reserved.

Implementing Securityin the Java Environment

Interface-specific access

Class loader

Bytecode verifier

Language and compiler

Java Security LayersLanguage and CompilerThe Java language was designed to be a safe language. The constructs that allow direct manipulation of memory pointers have been eliminated, thereby reducing or even eliminating run-time program crashes and, as a consequence, memory leaks.Class LoaderThe class loader ensures that each class coming from a local source (built-ins) and the classes from each network source are stored separately. During execution, the run-time system first looks up the built-ins for referenced classes; if they are not found, then it consults the referencing class. This ensures that built-in classes are not overridden by network-loaded classes. This prevents “spoofing,” or overriding the expected and trusted behavior of a built-in class. Inside a JVM, there can be several classloaders controlling each applications namespace.

Page 41: Java Programming

Oracle10g: Java Programming 1-17

Java Security Layers (continued)Bytecode VerifierDuring the execution of a Java program, JVM can import code from anywhere. Java must make sure that the imported code is from a trustworthy source. To accomplish this task, the run-time system performs a series of checks called bytecode verification.Interface-Specific AccessBuilt-in classes and methods control access to the local file system and network resources. These classes are restrictive by default. If imported code tries to access the local file system, then the security mechanism prompts the user.

Page 42: Java Programming

Oracle10g: Java Programming 1-18

1-18 Copyright © 2004, Oracle. All rights reserved.

Deployment of Java Applications

• Client-side deployment:– JVM runs stand-alone applications from the

command line.– Classes load from a local disk, eliminating the need

to load classes over a network.• Server-side deployment:

– Serves multiple clients from a single source– Is compatible with a multitier model for Internet

computing.

Java ApplicationsJava originally gained popular acceptance because of the success of its applets. Today, however, it is also possible to write stand-alone applications in Java. A Java application is invoked by using a JVM and is not run from within a browser.Client-Side DeploymentJava applications can be deployed to run stand-alone applications within a local operating system, from the command line. For example, Java applications can access the local file system or establish connections with other machines on the network.Server-Side DeploymentJava applications can also execute on the server machine, as long as a JVM is available on that platform. The use of server-side Java applications is compatible with the multitier model for Internet computing.

Page 43: Java Programming

Oracle10g: Java Programming 1-19

1-19 Copyright © 2004, Oracle. All rights reserved.

Using Java with Oracle 10g

Oracledatabase

Web serverClient

Application server

Presentation Businesslogic

Data

OracleApplication Server

Java and Oracle 10gOracle 10g is a complete and integrated platform, which supports all the server-side requirements for Java applications. Oracle 10g comprises the following:Oracle Database 10gIn addition to its database management features, the Oracle Database (currently, version 10g) provides support for a variety of Java-based structures including Java components and Java stored procedures. These Java structures are executed in the database by its built-in Java Virtual Machine, called the Enterprise Java Engine (EJE).Oracle Application Server 10gThe Oracle Application Server 10g maintains and executes all your application logic, including Enterprise JavaBeans, through its own built-in JVM. Oracle Application Server 10g uses the OC4J J2EE server to execute servlets and JSPs. Oracle Application Server 10g Enterprise Manager is the tool that is used to manage and distribute applications, for ease of use.

Instructor NoteFor more architectural information about Oracle Application Server 10g, direct students to the various eClasses that are available on the Oracle Learning Network.

Page 44: Java Programming

Oracle10g: Java Programming 1-20

1-20 Copyright © 2004, Oracle. All rights reserved.

Java Software Development Kit

Sun Java J2SE (known as JDK and Java SDK) provides:• Compiler (javac)• Core class library

– classes.zip– rt.jar

• Debugger (jdb)• Bytecode interpreter: The JVM (java)• Documentation generator (javadoc)• Java Archive utility (jar)• Others

J2SE

Java Software Development KitSun provides the Java 2, Standard Edition (J2SE), which is also known as Java Software Development Kit (Java SDK) or the Java Development Kit (JDK). The components that are provided by the J2SE include the following:

• The Java compiler is javac. It compiles Java source code into Java bytecodes.• The Java bytecode interpreter, java, is the engine that runs Java applications.• The program that generates documentation in HTML from Java source code comments is

javadoc.Core Class LibraryThe J2SE provides core Java class in the following class library files:• classes.zip located in the jdk_home\lib for JDK 1.1.x or earlier• rt.jar located in the jdk_home\jre\lib for Java SDK 1.2.x or later

Other Java J2SE Tools• jdb is the Java class debugger. It is similar to the dbx or gdb debuggers on UNIX.• jar is used to create Java Archive (JAR) files, which are zipped Java programs. • javah is used to generate C files for native methods.• javakey supports the generation of certification keys for trusted Java code.• javap is used to disassemble Java bytecodes into human-readable format.• native2ascii converts Java source code to Latin 1 characters.• serialver is used to generate version numbers for classes.

Page 45: Java Programming

Oracle10g: Java Programming 1-21

1-21 Copyright © 2004, Oracle. All rights reserved.

Using the Appropriate Development Kit

Java2 comes in three sizes:• J2ME (Micro Edition): Version specifically targeted

at the consumer space• J2SE (Standard Edition): Complete ground-up

development environment for the Internet• J2EE (Enterprise Edition): Everything in the J2SE

plus an application server and prototyping tools

A Size for Every NeedJava 2, Micro EditionThe technology that Java 2, Micro Edition (J2ME) uses covers the range of extremely tiny commodities, such as smart cards or a pager, all the way up to the set-top box, which is an appliance that is almost as powerful as a computer. Like the other editions, the J2ME platform maintains the qualities for which Java technology has become famous.Java 2, Standard EditionThe J2SE technology has revolutionized computing with the introduction of a stable, secure, and feature-complete development and deployment environment that is designed from the ground up for the Web. It provides cross-platform compatibility, safe network delivery, and smart card tosupercomputer scalability. It provides software developers with a platform for rapid application development.Java 2, Enterprise EditionThe J2EE platform is intended as a proof of concept, and a guide for implementations in the application server marketplace. The J2EE SDK includes a J2EE application server and various tools to help developers prototype J2EE applications.

Page 46: Java Programming

Oracle10g: Java Programming 1-22

1-22 Copyright © 2004, Oracle. All rights reserved.

Integrated Development Environment

Development

UML

ADF

XML

SCM

Debug

Exchange

Database

HTML

Deployment

Synchronized changes

Integrated Development EnvironmentThe add-in API architecture of Integrated Development Environment (IDE) means that all the tool components (for example, navigator, editor, and modeller) share memory models and event systems. In this way, an update in one tool is notified to another tool so that it can refresh its image or take other appropriate actions.In Oracle 10g, the JDeveloper IDE was developed in pure Java. Synchronization between model and code can be set so that you can decide to work by using one or the other user interface.Customizable EnvironmentYou can customize the JDeveloper Integrated Development Environment and arrange its look to better suit your project needs and programming style. To suit the IDE to your individual taste, you can:

• Change the look and feel of the IDE• Create and manipulate custom navigators• Customize the Component Palette• Customize the IDE environment• Select JDeveloper’s embedded J2EE server• Arrange the windows in the IDE

Page 47: Java Programming

Oracle10g: Java Programming 1-23

1-23 Copyright © 2004, Oracle. All rights reserved.

Exploring the JDeveloper Environment

System Navigator Code Editor Property Inspector

Component Palette

The Oracle JDeveloper 10g EnvironmentJDeveloper contains four major user interface components. These components are what you use to edit code, design and manage the user interface, and navigate around your program.Component PaletteProperties are attributes that define how a component appears and responds at run time. In JDeveloper, you set a component’s initial properties during design time, and your code can change those properties at run time. System NavigatorSystem Navigator is made up of two components. The Navigator pane shows a list of files or classes in a project. The files may be Java source files, .class files, graphics files, HTML, XML documents, and so on. The Structure pane lists all the methods, fields, and graphical user interface (GUI) components in a selected class.Code EditorEditors are where most of the work takes place; this is where you write code and design user interfaces. Open an editor by double-clicking the item you want to edit or view. Property InspectorProperty Inspector is the window that shows the properties and events associated with a selected component in the design region of a viewer.

Page 48: Java Programming

Oracle10g: Java Programming 1-24

1-24 Copyright © 2004, Oracle. All rights reserved.

Oracle10g Products

Oracle 10g ProductsOracle Database 10gThe Oracle Database manages all your information: Word documents, Excel spreadsheets, XML, images, and so on. Oracle Development Suite 10g tools can automatically reuse the database structure and its integrity constraints, which reduces the amount of manual coding.Oracle Application Server 10gThe Oracle Application Server 10g runs all your applications: J2EE applications, Forms, wireless, portals, and business intelligence. Using Oracle Application Server 10g, all applications that are developed with Oracle Development Suite 10g can be deployed and managed in a single application server.Oracle Developer Suite 10gOracle Developer Suite 10g leverages the infrastructure that is offered by Oracle Application Server 10g and Oracle Database 10g enabling developers to build scalable, secure, and reliable e-business applications quickly and easily. The suite provides a complete and highly productive development environment for building applications. Oracle JDeveloper 10g is now available as a separate product and not just as part of the developer suite product.

Page 49: Java Programming

Oracle10g: Java Programming 1-25

1-25 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:• Java code is compiled into platform-independent

bytecodes.• Bytecodes are interpreted by JVM.• Java applications can be stand-alone or

implemented across an Internet-computing model.

Page 50: Java Programming
Page 51: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Defining Object-Oriented Principles

Page 52: Java Programming

2-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Define objects and explain how they are used• Associate objects so that they can communicate

and interact via messages• Define classes and explain how they are used• Describe object-oriented (OO) principles: classes,

objects, and methods• Describe the value of Reusable Software

Components • Examine the OO model that is used in this course

Page 53: Java Programming

2-3 Copyright © 2004, Oracle. All rights reserved.

Full Notes Page

Page 54: Java Programming

2-4 Copyright © 2004, Oracle. All rights reserved.

What Is Modeling?

• Models perform the following functions:– Describe exactly what the business needs– Facilitate discussion– Prevent mistakes

• Modeling and implementation are treated separately.

• Before coding can begin, the model must be correct.

Page 55: Java Programming

2-5 Copyright © 2004, Oracle. All rights reserved.

What Are Classes and Objects?

• A class:– Models an abstraction of objects– Defines the attributes and behaviors of

objects– Is the blueprint that defines an object

• An object:– Is stamped out of the class mold– Is a single instance of a class– Retains the structure and behavior

of a class

Page 56: Java Programming

2-6 Copyright © 2004, Oracle. All rights reserved.

An Object’s Attributes Maintain Its State

• Objects have knowledge about their current state.• Each piece of knowledge is called an attribute.

– The values of attributes dictate the objects’ state.

Attribute: Ink amount

Attribute: Cash available

Object: My blue pen

Object: Acme Bank ATM

Page 57: Java Programming

2-7 Copyright © 2004, Oracle. All rights reserved.

Page 58: Java Programming

2-8 Copyright © 2004, Oracle. All rights reserved.

Objects Have Behavior

• An object exists to provide behavior (functionality) to the system.

• Each distinct behavior is called an operation.

Operation: Write

Operation: Withdraw

Object: My blue pen

Object: Acme Bank ATM

Page 59: Java Programming

2-9 Copyright © 2004, Oracle. All rights reserved.

Objects Are Modeled as Abstractions

• A Java object is modeled as an abstract representation of a real-world object.

• Model only those attributes and operations that are relevant to the context of the problem.

Real-world attributes/operations that you may not want to model:• Attributes: Ink color• Operations: Refill, change color, point, write

Context: Product catalogReal-world attributes/operations that you may want to model:

• Attributes: Model, manufacturer, price• Operations: Change price

Page 60: Java Programming

2-10 Copyright © 2004, Oracle. All rights reserved.

Page 61: Java Programming

2-11 Copyright © 2004, Oracle. All rights reserved.

A PC may be an object.

A PC may have a CD drive, which

may be an object.

A PC may have a keyboard, mouse, and

network card, all of which may be objects.

Defining Object Composition

• Objects can be composed of other objects.• Objects can be part of other objects.• This relationship between objects is known as

aggregation.

Page 62: Java Programming

2-12 Copyright © 2004, Oracle. All rights reserved.

Page 63: Java Programming

2-13 Copyright © 2004, Oracle. All rights reserved.

The Donut Diagram

getAge()

Client orsender

Person

Messagenameaddressbirthdate

getName

setBirthdate getAge

getAddress setAddress

Page 64: Java Programming

2-14 Copyright © 2004, Oracle. All rights reserved.

Guided Practice:Spot the Operations and Attributes

Page 65: Java Programming

2-15 Copyright © 2004, Oracle. All rights reserved.

Collaborating Objects

Collaborating objects work together to complete a task and form the basis of an application system.• All methods are defined within a class and are not

defined globally as in traditional languages.• All objects are created from classes and contain

all the attributes and methods of that class.• Objects must associate with each other to

collaborate on common tasks.• Associated objects communicate by sending

messages.

Page 66: Java Programming

2-16 Copyright © 2004, Oracle. All rights reserved.

Objects Interact Through Messages

• Objects communicate by sending messages.• A sending object must be associated with or

linked to the receiving object.• The message sender requests the receiver to

perform the operation that is named in the message.

• This communication is similar to calling a procedure:– The sender calls a method of the receiver.– The receiver executes the called method.

• Calling a method is always in the context of a particular object:– myPen.write( ): Object-oriented programming– write (myPen): Traditional structured

programming

Page 67: Java Programming

2-17 Copyright © 2004, Oracle. All rights reserved.

When you create my blue pen, you do not have to specify its operations or attributes. You simply say what class it belongs to.

What Is a Class?

• A class is a template for objects.• A class definition specifies the operations and

attributes for all instances of that class.• A class is used to manage complexity.

Page 68: Java Programming

2-18 Copyright © 2004, Oracle. All rights reserved.

How Do You Identify a Class?

• Identify the common behavior and structure for a group of objects.

• Recognize a single coherent concept.• Caution: A common misconception is the use of

the words classes and objects interchangeably. Classes define objects.

My blue pen ops: write, refillattribs: ink amount, color of ink

Your blue pen ops: write, refillattribs: ink amount

Page 69: Java Programming

2-19 Copyright © 2004, Oracle. All rights reserved.

Comparing Classes and Objects

• Classes are static definitions that you can use to understand all the objects of that class.

• Objects are the dynamic entities that exist in the real world and your simulation of it.

• Caution: OO people almost always use the words classes and objects interchangeably; you must understand the context to differentiate between the two meanings.

Page 70: Java Programming

2-20 Copyright © 2004, Oracle. All rights reserved.

Page 71: Java Programming

2-21 Copyright © 2004, Oracle. All rights reserved.

What Is Encapsulation?

Encapsulation hides the internal structure and operations of an object behind an interface.• A bank ATM is an object that gives its users cash.

– The ATM hides (encapsulates) the actual operation of withdrawal from the user.

– The interface (way to operate the ATM) is provided by the keyboard functions, screen, cash dispenser, and so on.

– Bypassing the encapsulation is bank robbery.• Bypassing encapsulation in object-oriented

programming is impossible.

Page 72: Java Programming

2-22 Copyright © 2004, Oracle. All rights reserved.

What Is Inheritance?

• There may be a commonality between different classes.

• Define the common properties in a superclass.

• The subclasses use inheritance to include those properties.

Savings account Checking accountAccount

Page 73: Java Programming

2-23 Copyright © 2004, Oracle. All rights reserved.

Using the “Is-a-Kind-of” Relationship

• A subclass object “is-a-kind-of”superclass object.

• A subclass must have all the attributes and behaviors of the superclass.

Savings account

Account Pen

Pencil

Page 74: Java Programming

2-24 Copyright © 2004, Oracle. All rights reserved.

What Is Polymorphism?

Polymorphism refers to:• Many forms of the same operation• The ability to request an operation with the same

meaning to different objects. However, each object implements the operation in a unique way.

• The principles of inheritance and object substitution.

Load passengers

Page 75: Java Programming

2-25 Copyright © 2004, Oracle. All rights reserved.

Page 76: Java Programming

2-26 Copyright © 2004, Oracle. All rights reserved.

Architecture Rules for Reuse

Write code that contains:• Events that can interact with your Java application• Properties that can be exposed• Methods that can be invoked

Write code that supports:• Introspection or reflection• Customization• Persistence

Page 77: Java Programming

2-27 Copyright © 2004, Oracle. All rights reserved.

Engineering for a Black Box Environment

JavaBeans follow the black box approach which enables you to:• Simplify something of arbitrary complexity down

to a single object that everyone can understand• Think of large systems as a collection of

interconnected entities (black boxes) communicating via their interfaces

Page 78: Java Programming

2-28 Copyright © 2004, Oracle. All rights reserved.

Order Entry UML Diagram

Page 79: Java Programming

2-29 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:• An object is an abstraction of a real-world object.• A class is a template or blueprint for objects.• Classes form inheritance trees: Operations that

are defined in one class are inherited by all subclasses.

• Polymorphism frees the caller from knowing the class of the receiving object.

Page 80: Java Programming

2-30 Copyright © 2004, Oracle. All rights reserved.

Practice 2: Overview

This practice covers:• Identifying business objects for the Order Entry

system• Identifying methods for the classes• Identifying attributes for the classes• Searching for inheritance in the classes• Examining UML class model for course

application

Page 81: Java Programming

2-31 Copyright © 2004, Oracle. All rights reserved.

Practice 2: Notes

Page 82: Java Programming

2-32 Copyright © 2004, Oracle. All rights reserved.

Practice 2: Notes

Page 83: Java Programming

2-33 Copyright © 2004, Oracle. All rights reserved.

Order Entry SystemPartial UML Class Model

Order

id: intorderDate: DateshipDate: DateshipMode: StringorderTotal: double

addItem()removeItem()setOrderDate()getOrderDate()setShipDate():

OrderItemlineNo: intquantity: intprice: double

getQuantity()setQuantity()setPrice()getPrice()getItemTotal():

Customername: Stringaddress: Stringphone: doublegetName()setName()setAddress()getAddress():

Companycontact: Stringdiscount: int

getContact()setContact():

Individual

licNumber: String

setLicNumber()getLicNumber():

Productid: intname: Stringdescription: StringretailPrice: double

getPrice():

Page 84: Java Programming

2-34 Copyright © 2004, Oracle. All rights reserved.

Page 85: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Basic Java Syntax and Coding Conventions

Schedule: Timing Topic60 minutes Lecture45 minutes Practice

105 minutes Total

Page 86: Java Programming

Oracle10g: Java Programming 3-2

3-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Identify the key components of the Java language• Identify the three top-level constructs in a Java

program• Identify and describe Java packages• Describe basic language syntax and identify Java

keywords• Identify the basic constructs of a Java program• Compile and run a Java application• Examine the JavaBean architecture as an example

of standard coding practices • Use the CLASSPATH variable and understand its

importance during compile and run time.

Lesson AimThis lesson introduces the basic constructs of the Java language. You learn conventions, standards (that is, capitalization, spacing, and so on), compiling, and running applications. You become familiar with the basic language constructs so that you can recognize and manipulate them with or without using Oracle JDeveloper. The lesson explores JavaBeans as an example of good coding practices.

Page 87: Java Programming

Oracle10g: Java Programming 3-3

Lesson Aim (continued)OverviewJava ComponentsThe Java environment is made up of a run-time engine, documentation tools, debugging utilities, and predefined classes and methods that are designed to decrease development time.ConventionsWhen programming in Java, you must use established naming, capitalization, indenting, and commenting conventions.Classes, Objects, and MethodsIn Java, almost everything is an object. Objects are created from blueprints called classes. The objects contain attributes (data) that can be accessed by functions that are contained within the object. Functions that act on the data are called methods.Using JavadocJavadoc is a facility that is provided within J2SE and produces HTML documentation from your program. It reads the source code and parses specially formatted and positioned comments into documentation.Compiling and Running JavaJava is an interpretive language, which means that the code is interpreted to machine code only at run time. This is what makes the “write once, run anywhere” (WORA) concept work. There are several steps in the process of interpreting program source code into a running program. Java code is first compiled into bytecodes by the Java compiler. Bytecodes are interpretable, intermediate representation of the Java program. The resulting bytecodes are interpreted and converted into machine-specific instructions by the Java Virtual Machine (JVM) at run time.Security ConcernsUsing the jad.exe, you can make the code so confused or opaque as to be difficult to perceive or understand. Obfuscation of your code can make field debugging more difficult. For example, stack traces are often very useful in isolating bugs. After compression or obfuscation by one of these tools, however, the stack trace may no longer contain the original method names. In general, refrain from using obfuscation, unless you really want to make it difficult to modify your code.

Page 88: Java Programming

Oracle10g: Java Programming 3-4

3-4 Copyright © 2004, Oracle. All rights reserved.

Examining Toolkit Components

The J2SE/J2EE from Sun provides:• Compiler• Bytecode interpreter• Documentation generator

J2SE

Examining Toolkit ComponentsSun J2SE Components

• The Java compiler is javac; it compiles Java source code into Java bytecodes.• The Java bytecode interpreter is the engine that runs Java applications.• The program that generates documentation in HTML from Java source code comments

is javadoc.Other J2SE Tools• jdb : Used as a Java class debugger and it is similar to the dbx or gdb debuggers on

UNIX• jar : Used to create Java Archive (JAR) files, which are zipped Java programs • javah : Used to generate C files for native methods• javakey : Provides support for generating certification keys for trusted Java code• javap : Used to disassemble Java bytecodes into human-readable format• native2ascii : Used to convert Java source code to Latin 1 characters

Page 89: Java Programming

Oracle10g: Java Programming 3-5

3-5 Copyright © 2004, Oracle. All rights reserved.

Exploring Packages in J2SE/J2EE

The J2SE/J2EE from Sun provides standard packages for:• Language• Windowing• Input/output• Network communication

J2SE

Java PackagesThe Java language includes a series of classes that are organized into packages, depending on functional groups. For example, there is a set of classes that helps create and use network connections; these classes are contained in the java.net package. The basic package for the Java language is named classes.zip in 1.1.x and is renamed rt.jar since 1.2.x.Standard Java PackagesThese packages contain the classes that form the foundation for all Java applications.Built-in Classes That Are Distributed with Java Language• java.lang: Basic language functions• javax.swing: Parent package to all Swing-related packages• java.util: Facility supporting interfacing, implementing, sorting, and searching on

collections• java.awt: Utility to managing layout, handling events, and rendering graphics for

AWT• java.io: General interface for all I/O operations

Page 90: Java Programming

Oracle10g: Java Programming 3-6

3-6 Copyright © 2004, Oracle. All rights reserved.

Documenting Using the J2SE

The J2SE/J2EE from Sun provides documentation support for:• Comments

– Implementation– Documentation

• Documentation generator

J2SE

DocumentationThere are two types of documentation methods in Java that you can specify in your source code. One is for the internal documentation, and the other is for external documentation.Comments

• Implementation comments are included in the source code. They are useful for programmers who are examining the code. When writing implementation comments, you must explain the code and any special processes that may need detailed explanations. Use:

- // to start comments up to the end of the line- /* to start comments across multiple lines, and end with */

• Documentation comments are created using javadoc. Javadoc is a utility that is provided with J2SE and that creates an HTML document from the documentation comments in Java source code. You can use the javadoc utility to document classes and methods, so that they can be better understood when used by other programmers. Use:

- /** to start documentation comments across multiple lines, and end with */Documentation GeneratorJavadoc is a documentation generator that is part of J2SE.

Page 91: Java Programming

Oracle10g: Java Programming 3-7

3-7 Copyright © 2004, Oracle. All rights reserved.

Contents of a Java Source

• A Java source file can contain three top-level constructs:– Only one package keyword followed by the package

name, per file– Zero or more import statements followed by fully

qualified class names or “*” qualified by a package name

– One or more class or interface definitions followed by a name and block

• File name must have the same name as the public class or public interface.

RentalItem.javapackage practice16; // collection of classes of similar functionality

import java.util.*; // import for Date class

public class RentalItem {

private InventoryItem inventoryItem;

private String dueDate;

private Date dateReturned;

public RentalItem(int aInventoryItemId) {

try {

inventoryItem = DataMan.fetchInventoryItemById(aInventoryItemId);

}

catch (ItemNotFound e2) {

System.out.println("Invalid Item ID");

}

dueDate = calcDueDate();

} // end constructor

Page 92: Java Programming

Oracle10g: Java Programming 3-8

3-8 Copyright © 2004, Oracle. All rights reserved.

Establishing Naming Conventions

Naming conventions include:• Class names

– Customer, RentalItem, InventoryItem• File names

– Customer.java, RentalItem.java• Method names

– getCustomerName(), setRentalItemPrice()• Package names

– oracle.xml.xsql, java.awt, java.io

Naming ConventionsFile NamesJava source code is stored in files with the .java extension. Use the name of the class held within the file as the file name. Remember that Java is case sensitive, and the names must match exactly, including case. Compiled Java code, or bytecodes, is stored in files with the .class extension.The name of the Java source file must be the name of the public class in the file; otherwise, the code will not compile. You may have source code for more than one class in the file, but only one can be public, and the file name must be the same name as the public class.Class NamesUse descriptive nouns or noun phrases for class names. Capitalize the first letter of each word in the class name, including the first word (for example, MyFirstClassName).

Page 93: Java Programming

Oracle10g: Java Programming 3-9

Naming Conventions (continued)Method NamesUse verbs or verb clauses for method names. Make the first letter of the method name lowercase with the first letter of each internal word capitalized (for example, getSomeInformation() ).PackagesThe Java documentation states that package names must nearly always be in lowercase, and resemble a reverse notation of a “Domain name.” For example, when Oracle Corporation develops class libraries, package names begin with “oracle.” followed by a descriptive name. The naming convention ensures that a package name is unique to avoid clashing when using APIs from multiple vendors in the same application.

Page 94: Java Programming

Oracle10g: Java Programming 3-10

3-10 Copyright © 2004, Oracle. All rights reserved.

More About Naming Conventions

• Variables:– customerName, customerCreditLimit

• Constants:– MIN_WIDTH, MAX_NUMBER_OF_ITEMS

• Uppercase and lowercase characters• Numerics and special characters

Naming Conventions (continued)VariablesUse short, meaningful names for variables. Use mixed-case letters with the first letter lowercase and begin all internal words with uppercase letters (for example, intsquareFootage). Choose names that indicate the intended use of the variable. Avoid using single-character variable names except for temporary variables. Common names for temporary variables are c, d, and e for character fields and i, j, k, m, and n for integers.String customerName; // string variableint customerCreditLimit; // integer variable

ConstantsDeclare constants with descriptive names in all uppercase. Separate internal words with underscores (for example, int MIN_WIDTH).

Page 95: Java Programming

Oracle10g: Java Programming 3-11

Naming Conventions (continued)Uppercase and LowercaseJava is case sensitive. You must adopt and follow a strict capitalization scheme. The scheme that is presented above is a generally accepted practice.Numerics and Special CharactersNumbers, underscores, and dollar signs may be used for names in addition to uppercase and lowercase letters. The only syntactic restriction is that identifiers must not begin with a number. This rule prevents them from being confused with numeric literals. Underscores are not generally used except for private and local variables.

Page 96: Java Programming

Oracle10g: Java Programming 3-12

3-12 Copyright © 2004, Oracle. All rights reserved.

Defining a Class

Class definitions typically include:• Access modifier• Class keyword• Instance fields• Constructors• Instance methods• Class fields• Class methods

Class DefinitionA class is an encapsulated collection of data and methods to operate on the data. A class definition, data and methods, serves as a blueprint that is used in the creation of new objects of that class.A class definition typically consists of:

• Access modifier: Specifies the availability of the class from other classes• Class keyword: Indicates to Java that the following code block defines a class• Instance fields: Contain variables and constants that are used by objects of the class• Constructors: Are methods having the same name as the class, which are used to

control the initial state of any class object that is created• Instance methods: Define the functions that can act upon data in this class• Class fields: Contain variables and constants that belong to the class and are shared by

all objects of that class• Class methods: Are methods that are used to control the values of class fields

The order of the fields, constructors, and methods does not matter in Java. Ordering the parts of a Java program consistently will, however, make your code easier to use, debug, and share. The order listed in the slide is generally accepted.

Page 97: Java Programming

Oracle10g: Java Programming 3-13

3-13 Copyright © 2004, Oracle. All rights reserved.

Rental Class: Example

public class Rental {//Class variablestatic int lateFee;

// Instance variablesint rentalId;String rentalDate;float rentalAmountDue;…// Instance methodsfloat getAmountDue (int rentId) {…}…}

Declaration

Instance variable

Instance method

Access modifier

Rental Class: ExampleThis slide shows the syntax of a class definition. Every Java program needs at least one class definition, even if the class contains only a static main() method.The First LineThe class definition usually starts with the public access modifier. If you omit the publicmodifier, then the class is visible only to other classes within the same package. The access modifier is followed by the class keyword, followed by the class body enclosed in braces.Instance VariablesThe class body contains declarations of instance variables and instance methods. Instance variables constitute the state of an object. Instance variables are usually declared private; if no access level is specified, then they can be accessed by any class in the same package.

Page 98: Java Programming

Oracle10g: Java Programming 3-14

Rental Class: Example (continued)Instance MethodsInstance methods define the operations that can be performed on objects of this class type. Each instance method has a name, an optional list of arguments, and a return type. If no access level is specified, then instance methods can be accessed by any class in the same package.Class Variables and Class MethodsClass fields and class methods are defined by using the static keyword.

Page 99: Java Programming

Oracle10g: Java Programming 3-15

3-15 Copyright © 2004, Oracle. All rights reserved.

Creating Code Blocks

• Enclose all class declarations.• Enclose all method declarations.• Group other related code segments.

public class SayHello {

public static void main(String[] args) {

System.out.println("Hello world");

}

}

Code BlocksEnclose class declarations within braces { }. The class declaration contains variables, constants, and methods. The class body must begin on a new line following the class declaration and the opening brace. Indicate the end of the class declaration by a single closing brace on a new line. There is another coding convention, which puts the opening brace on the next line even with the closing brace from the previous statement.Method declarations follow the same form with the opening brace on the same line as the method definition and the closing brace on a new line. All statements and declarations within the braces are part of the method.You can also group code segments within a method declaration by using braces. Grouping enhances the readability of your code. The easier it is to read and follow your code, the easier it will be to debug and reuse.Variables that are defined within a code block are available during the execution of that code block and are discarded at the completion of execution.main() MethodThe interpreter looks for a specific method to start the program, and that method is called main(). It is simply the starting place for the interpreter to begin. Only one class will need to have a main method to get things started. You only need a main method for an application. If you are writing an applet, then the main method is not needed, because the browser has its own way to start or bootstrap the program.

Page 100: Java Programming

Oracle10g: Java Programming 3-16

3-16 Copyright © 2004, Oracle. All rights reserved.

Defining Java Methods

• Always define within a class.• Specify:

– Access modifier– Static keyword– Arguments– Return type

[access-modifiers] [static] "return-type"

"method-name" ([arguments]) {

"java code block“ … }

return

Method DefinitionWhen you define a class for an object-oriented program, you implement all the behavior of that class in one or more methods. A Java method is equivalent to a function, procedure, or subroutine in other languages, except that it must be defined within a class definition. Methods consist of the following:

• Access modifier: You can specify a method as either public, private, or protected. Public methods can be known and used by external users, whereas private methods can be seen or used only by methods within the class. Protected methods are accessible from any class that extends or inherits from the class.

• Static keyword: Variables and methods are usually accessed for a particular object. If the method or variable is defined with the static keyword, then it becomes a class method or variable, which means that it applies to the class of objects as a whole and not as individual objects. Static variables are shared by all objects of that class.

• Arguments: The arguments that are listed for a method are those parameters that are required for the method to perform its function.

• Return type: A return type is required for all method definitions. There is no default return type in Java. The return type specifies the object type that will be returned when the method has completed its task. It can be an integer, a string, any defined object type, or void.

Page 101: Java Programming

Oracle10g: Java Programming 3-17

3-17 Copyright © 2004, Oracle. All rights reserved.

Examples of a Method

public float getAmountDue (String cust){

// method variables

int numberOfDays;

float due;

float lateFee = 1.50F;

String customerName;

// method body

numberOfDays = getOverDueDays();

due = numberOfDays * lateFee;

customerName = getCustomerName(cust);

return due;

}

Declaration

Methodvariables

Methodstatements

Return

Method ExampleDeclarationIn this example, the defined method returns a float primitive type. The method name is declared as getAmountDue. The method name begins with a lowercase letter with the beginning letter of each subsequent word in uppercase letters. The next item is the declaration of the expected parameter list. The parameter list consists of the argument data type and argument name.Method VariablesThe next set of statements defines any method-specific variables. These variables are used only during the execution of the method and are discarded when control is passed back to the object that called this method. The float data type is used for real numbers (numbers with decimal points).Method StatementsThe executable body of the method comes next. This section contains the Java statements that are used to act upon data. It can include conditional statements, data manipulation operations, or any other valid Java statements.ReturnThe return statement accomplishes two things. The return causes the execution to branch back to the caller of the method, and then it passes back the specified value, if there is one.

Page 102: Java Programming

Oracle10g: Java Programming 3-18

3-18 Copyright © 2004, Oracle. All rights reserved.

Declaring Variables

• You can declare variables anywhere in a class block, and outside any method.

• You must declare variables before they are used inside a method.

• It is typical to declare variables at the beginning of a class block.

• The scope or visibility of variables is determined in the code block.

• You must initialize method variables before using them.

• Class and instance variables are automatically initialized.

Declaring VariablesDeclarationJava requires that variables be declared before they can be accessed. Declare variables and constants by placing each statement on a separate line, so that the code is clear and easy to understand. You can declare multiple variables of the same type within one statement.ScopeIf variables or constants are required only within a code block, then declare them at the top of the code block. Variables that are defined within a code block will be discarded when the execution of the code block is complete. This is useful for temporary variables or those needed to hold specific information during a calculation or process. After the process is complete, they are no longer needed.InitializationWhenever possible, initialize variables at declaration. This provides some insight into the use or purpose of the variable. The only reason for not initializing at declaration is if the value is dependent on a calculation that is not yet performed.When you declare primitive instances or class variables, they are automatically initialized to a default value depending on their type.

Page 103: Java Programming

Oracle10g: Java Programming 3-19

3-19 Copyright © 2004, Oracle. All rights reserved.

Examples of Variablesin the Context of a Method

public float getAmountDue (String cust) {

float due = 0;

int numberOfDays = 0;

float lateFee = 1.50F;

{int tempCount = 1; // new code block

due = numberOfDays * lateFee;

tempCount++;

} // end code block

return due;

}

Method variables

Temporary variables

Examples of Variables in the Context of a MethodMethod VariablesIn this example, the numberOfDays and lateFee variables are defined at the beginning of the method. Both of these variables are method variables; that is, they are used while the method is being executed and are discarded at the return of execution control to the caller.Temporary VariablesThe tempCount variable is defined within a subblock of the getAmountDue method. The tempCount variable is available only during the execution of this block of code. When the block of code is complete, the variable is discarded, whether or not the method maintains execution control.

Page 104: Java Programming

Oracle10g: Java Programming 3-20

3-20 Copyright © 2004, Oracle. All rights reserved.

Rules for Creating Statements

• Use a semicolon to terminate statements.• Define multiple statements within braces.• Use braces for control statements.

StatementsJava statements cause some action to occur, such as setting a value, sending output, reading a database, and so on. They always end with a semicolon. Compound statements are a list of related statements that are contained within a set of braces. Indent the statements one level below the enclosing statement for clarity. Place the opening brace on the line that begins the compound statement. Place the closing brace on a separate line, indented to the correct level. Use braces around all statements when they are part of a control (if-else) structure.

public float getAmountDue (String cust) {float due = 0;int numberOfDays = 0;float lateFee = 1.50F;

If (…) { {int tempCount = 1; // new code block due = numberOfDays * lateFee; tempCount++; //nested compound statement

… } // end code block} //end if return due;

}

Page 105: Java Programming

Oracle10g: Java Programming 3-21

3-21 Copyright © 2004, Oracle. All rights reserved.

What Are JavaBeans?

A JavaBean is a platform-neutral reusable software component that:• Can be manipulated visually in a builder tool• Communicates with other JavaBeans via events• Comprises visible components that must inherit

from other visible components• Provides an architecture for constructing the

building blocks of an application

About JavaBeansA JavaBean is a reusable platform-independent software component that can be manipulated visually in a builder tool such as JDeveloper. The JavaBean’s standard is a low-level component model, tailored to the Java language. It does not specify the kind of component document or application framework such as CORBA, OpenDOC, or Taligent). JavaBeans focuses purely on the interface that a Java building block must represent.A JavaBean consists of a single class or a group of classes. At a minimum, a bean must have a public class declaration and a no-parameter constructor. Any classes can be part of a bean. There is no specific superclass that a bean must extend—unlike, for example, an applet, which must extend the Applet class. However, a JavaBean must conform to certain basic architecture rules.Beans are not a special type of component. A bit of Java code does not have a special “bean”type or label that makes it a bean. A JavaBean has a set of criteria that makes it flexible and reusable to others. It is not about, for example, different types of coffee, such as French Roast or Columbian. Rather, it is about the packaging of the coffee meat so that it can be used as a bean in a variety of environments (for example, used in a grinder for a beverage or covered in chocolate as an after-dinner treat).

Instructor NoteStudents will probably find that even if JavaBeans are new to them, many of the concepts and rules that are associated with JavaBeans are familiar.

Page 106: Java Programming

Oracle10g: Java Programming 3-22

3-22 Copyright © 2004, Oracle. All rights reserved.

Managing Bean Properties

• Properties are the bean class member variables. (Variables can be primitive types or objects.)

• A property can be:– Unbound, which is a simple property– Bound, which triggers an event when the field is

altered– Constrained, in which changes are accepted or

vetoed by interested listener objects

PropertiesProperties are the bean variables. They can be of any Java data type; that is, primitives or objects. In the context of a bean, variables or properties can have a binding that is stated as any of the following:

• Unbound: Unbound properties are simple properties that are accessed or modified by using the associated get and set methods.

• Bound: Bound properties are like simple properties, but when modified by using the set method they trigger the PropertyChangeEvent event. The PropertyChangeEvent object contains the old value and new value of the property, so that listeners can react appropriately to the change. For example, changing the connection property of a JClient SessionInfo object fires an event that redraws JDeveloper’s structure pane.

• Constrained: Constrained properties are an extension to bound properties, in that they generate a PropertyChangeEvent when the property is modified, but the listeners handling the event can veto (prevent) the change by throwing PropertyVetoException if the change violates some rule or constraint. For example, resizing a visual component can be vetoed by other components based on layout management rules. The differentiating characteristic between bound and constrained is what occurs when their property values are altered.

Page 107: Java Programming

Oracle10g: Java Programming 3-23

3-23 Copyright © 2004, Oracle. All rights reserved.

Exposing Properties and Methods

Gettermethods(public)

Settermethods

(public void)

T getVar()

T[] getArr()

boolean isVar()

setVar(T val)

setArr(T[] val)

setVar(boolean val)

privateT var;T[] arr;

Property and Method Naming ConventionsGood naming conventions apply to the methods that an application calls to access and alter the properties of a class. In JavaBean classes, the name of the set and get methods are formed from the prefix get or set, followed by the uppercased name of the property or variable that is accessed.The properties are commonly declared private, forcing users to invoke the access methods to interact with the bean. The following is an example of a String property and its corresponding setter and getter methods:private String text;public String getText() { return text };public void setText(String newtext) { text = newtext; }

Note: The property name starts with a lowercase letter, but the method names are setTextand getText, (using the uppercased form of the property name). The return type of the getter method, and the single argument of the setter method must be the same type as the property. For indexed properties, such as arrays, it is common to provide two additional methods to get and set a value at a specified index, for example:private String[] name;public String[] getName() {...} ;public void setName(String[] values) {...};public String getName(int index) {...};public void setName(int index, String value) {...};

Page 108: Java Programming

Oracle10g: Java Programming 3-24

3-24 Copyright © 2004, Oracle. All rights reserved.

JavaBean Standards at Design Time

The benefits at design time include:• A facilitated interaction between designer, tool,

and bean• Instantiated and functioning beans in a visual tool• Highly iterative development environment• Building applications in small bits that plug in and

out• Storage and recovery of instantiated

objects

Benefits of JavaBeans Standards During DesignThe JavaBeans architecture makes the bean easier to use during the design phase. At design time, the JavaBean is alive or “hot,” and exhibits all the behavior found in the deployed application. A JavaBean displaying the time, when included in an application, will start ticking away as soon as it has been placed into the application. The designer can see how the application will behave, as its application is being built, rather than after compiling. This pseudo-live functionality of JavaBeans facilitates a more iterative approach, with the developer building small bits while getting immediate feedback. The system evolves more easily.For JavaBeans to be running during design time, the bean must adhere to a set of standards and protocols that describe how they work. If the protocol is followed, a visual development tool can interrogate the bean structure, understand its interactions, and present them to the developer.All instantiated objects, present at design time, are serialized with the design and, when recovered, retain their values, making them persistent. This functionality is supported through a tool’s Load, Save, Copy, Cut, and Paste functions.

Page 109: Java Programming

Oracle10g: Java Programming 3-25

3-25 Copyright © 2004, Oracle. All rights reserved.

Compiling and Runninga Java Application

• To compile a .java file:

• To execute a .class file:

• Remember that case matters.

prompt> javac SayHello.java

… compiler output …

prompt> java SayHello

Hello world

prompt>

Java Development Kit (JDK) ToolsJ2SE includes javac.exe and java.exe, two executables for compiling and executing a Java program.Compiling Java CodeRun javac.exe from the command prompt to compile .java files into .class files. For example, to compile SayHello.java into a bytecodes file named SayHello.class, enter the following at the command prompt:javac SayHello.java

Running a Java Application from the Command LineThe java.exe executable loads the class, verifies the bytecodes, interprets it into machine language, and executes the code. Start the interpreter by entering the following command at the command prompt:java SayHello

This starts JVM, which loads SayHello.class and tries to call its main() method. JVM expects the SayHello.class to have a main() method, where the program execution will start. If SayHello.class calls methods in other classes, then JVM loads these other classes only when they are required.

Page 110: Java Programming

Oracle10g: Java Programming 3-26

3-26 Copyright © 2004, Oracle. All rights reserved.

The CLASSPATH Variable

• Is defined in the operating system• Directs the JVM and Java applications where to

find .class files• References built-in libraries or user-defined

libraries• Enables interpreter to search paths, and loads

built-in classes before user-defined classes• Can be used with “javac” and “java” commands

Setting the CLASSPATHIf the CLASSPATH variable is not set, then a default is used. The default includes the absolute path to the jdk1.4.2_03\bin,… \lib\, and …\classes\ directories, which house the J2SE packages (contained in the rt.zip file). You can create a …/classes/ directory, add your class files, and CLASSPATH will find them.CLASSPATH examines individual class files, or those stored in .zip or .jar files. Set the CLASSPATH variable by using the commands: setenv in UNIX (in a C-Shell), and set in NT. Separate directories with a semicolon “;” (for example, c:\myClasses;d:\myOtherClasses). Set CLASSPATH to include the directory containing the .class files.The interpreter looks for classes in the directory sequence as they are found in the CLASSPATH variable. If the interpreter cannot find the named class in the first directory, then it searches the second and all the others in the list.If you want the CLASSPATH to point to class files that belong to a package, then you mustspecify a path name that includes the path to the directory one level above the directory that has the name of your package.You can override the CLASSPATH setting in the javac and java commands, by using the “–classpath” option.

Page 111: Java Programming

Oracle10g: Java Programming 3-27

3-27 Copyright © 2004, Oracle. All rights reserved.

CLASSPATH: Example

C:\>set CLASSPATH=D:labs\les03\classes\oe

Setting CLASSPATH

Location of .class files in the oe package

Page 112: Java Programming

Oracle10g: Java Programming 3-28

3-28 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:• J2SE provides basic Java tools.• J2SE provides a rich set of predefined classes and

methods.• Java programs are made up of classes, objects,

and methods.• Adhering to programming standards makes code

easier to read and reuse.

Page 113: Java Programming

Oracle10g: Java Programming 3-29

3-29 Copyright © 2004, Oracle. All rights reserved.

Practice 3: Overview

This practice covers:• Examining the Java environment• Writing and running a simple Java application• Examining the course solution application• Inspecting classes, methods, and variables• Creating class files and an application class with a

main( ) method• Compiling and running an application

Practice 3: OverviewNote: If you close a DOS window or change the location of the .class files, then you must modify the CLASSPATH variable.The practices in lessons 3, 4, and 5 are written to help you better understand the syntax and structure of the Java language. Their sole purpose is to instruct and is not intended to reflect any set of application development best practices. The purpose of the practices from lesson 6 to the end of the course, is different. Starting in lesson 6, you use JDeveloper to build an application employing techniques you will use during real-world development. The practices continue to support the technical material presented in the lesson, while incorporating some best practices that you will use while developing a Java application.

Page 114: Java Programming

Oracle10g: Java Programming 3-30

Practice 3-1: Introducing the Java and Oracle PlatformsGoalThe goal of this practice is to use the Java Development Kit and examine the development environment. You write, compile, and run a simple Java application.Note: If you close a DOS window or change the location of the .class files, then you must set the CLASSPATH variable again.The practices in lessons 3, 4, and 5 are written to help you better understand the syntax and structure of the Java language. Their sole purpose is to instruct and is not intended to reflect any set of application development best practices.Edit and Run a Simple Java Application

1. Open a DOS window and navigate to the E:\labs\temp directory and create a file called HelloWorld.java by using Notepad with the following commands:E:cd \labs\tempnotepad HelloWorld.java

2. In Notepad, enter the following code, placing your name in the comments (after thedouble slashes). Also, make sure that the case of the code text after thecomments is preserved, because Java is case sensitive:// File: HelloWorld.java// Author: <Enter Your Name>public class HelloWorld {

public static void main(String[] args){

System.out.println("Hello World!");}

}

3. Save the file to the E:\labs\temp directory, using the File > Save menu option, but keep Notepad running, in case compilation errors occur requiring you to edit the source to make corrections.

4. Compile the HelloWorld.java file (file name capitalization is important)a. In the DOS window, ensure that the current directory is E:\labs\temp.b. Check whether the Java source file is saved to disk.

(Hint: Type the command dir Hello*. )c. Compile the file by using the command: javac HelloWorld.javad. Name the file that is created if you successfully compiled the code.

(Hint: Type the command dir Hello*. )

Page 115: Java Programming

Oracle10g: Java Programming 3-31

Practice 3-1: Introducing the Java and Oracle Platforms (continued)5. Run the HelloWorld application (again capitalization is important).

a. Run the file by using the command: java HelloWorldb. What was displayed in the DOS window?

6. Modify the CLASSPATH session variable to use the directory where the .class file is stored. In the DOS window, use the set CLASSPATH=E:\labs\temp command to set the variable. The variable will be set for the duration of the DOS session. If you open another DOS window, you must set the CLASSPATH variable, again.

7. Again, run the HelloWorld application (capitalization is important).a. Run the file by using the command: java HelloWorldb. What was displayed in the DOS window?

8. Close Notepad, but do not exit the DOS window, because you continue to work with this environment for some time.

Page 116: Java Programming

Oracle10g: Java Programming 3-32

Practice 3-2: Basic Java Syntax and Coding ConventionsGoalThe goal of this practice is to create, examine, and understand Java code. You create a class representing a command-line application for the Order Entry system that contains the application entry point in the form of a main() method.You use the UML model from the lesson titled “Defining Object-Oriented Principles” as a guide to creating additional class files for your application. You run some simple Java applications, fixing any errors that occur.Creating Order Entry Class Files (Examining the Customer Class)Using the UML model from the lesson titled “Defining Object-Oriented Principles,” create class files to be used in the application.

1. Copy the Customer.java file from the e:\labs directory to your E:\labs\OrderEntry\src\oe directory.

2. In the DOS window, change your current working directory to:E:\labs\OrderEntry\src\oe

3. Using Notepad, review the Customer class and answer these questions:a. Name all the instance variables in Customer.b. How many instance methods are there in Customer?c. What is the return type of the method that sets the customer’s name?d. What is the access modifier for the class?

4. Close the file, and at the DOS prompt compile the Customer.java file by using the following command as a guide:javac -d E:\labs\OrderEntry\classes Customer.javaWhere is the compiled .class file created? (Hint: Type cd ..\..\classes\oe, and then type dir.)

Incorporate the Order.java into Your Application Files5. Add the Order.java file to your application structure, review the code and compile it.

a. In Notepad, open the \labs\Order.java file and save it to the directory for your OE package source code (E:\labs\OrderEntry\src\oe).

b. The attributes are different from those in the UML model. The customer and item information will be incorporated later.

c. Notice two additional attributes (getters and setters) have been added.shipmode (String): Used to calculate shipping costsstatus (String): Used to determine the order’s place in the order fulfillment process

d. Ensure that you are in the E:\labs\OrderEntry\src\oe directory. Use the following command to compile the Order.java file which will place the .class file in the directory with the compiled version of the Customer class: javac –d E:\labs\OrderEntry\classes Order.javaa

Page 117: Java Programming

Oracle10g: Java Programming 3-33

Practice 3-2: Basic Java Syntax and Coding Conventions (continued)Create and Compile the Application Class with a main() Method

6. Create a file called OrderEntry.java containing the main method, as shown below. Place the source file in the same source directory as all the other java files (E:\labs\OrderEntry\src\oe). This file is a skeleton that will be used for launching the course application.

package oe;

public class OrderEntry {public static void main(String[] args){

System.out.println("Order Entry Application");}

}7. Save and compile OrderEntry.java with the following command line:

javac -d E:\labs\OrderEntry\classes OrderEntry.java

8. Run the OrderEntry application.a. Open a DOS window and use the cd command to change the directory to:

E:\labs\OrderEntry\classesb. Run the file by using the command: java oe.OrderEntry

Page 118: Java Programming
Page 119: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Exploring Primitive Data Typesand Operators

Schedule: Timing Topic50 minutes Lecture30 minutes Practice80 minutes Total

Page 120: Java Programming

Oracle10g: Java Programming 4-2

4-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Distinguish between reserved words and other

names in Java• Describe Java primitive data types and variables• Declare and initialize primitive variables• Use operators to manipulate primitive variables• Describe uses of literals and Java operators• Identify valid operator categories and operator

precedence• Use String object literals and the concatenation

operator

Lesson AimThis lesson introduces Java’s decision-making and repetition constructs. You learn how to use those constructs to build nonlinear applications. Java provides eight primitive data types and a large number of operators to manipulate these types. This lesson introduces the primitive types and describes how to use the most common operators to construct simple algorithms.

Page 121: Java Programming

Oracle10g: Java Programming 4-3

Lesson Aim (continued)Primitive Data Types in JavaJava is an object-oriented programming language, which means that a Java program is made up of objects. For example, a Java program dealing with video rentals may have objects representing the various videos and games that are available, the customers who have rented videos, the numerous titles that are available, and so on.If you take a look at one of these objects in more detail, however, you see that it contains fundamental values such as whole numbers, fractions, and characters. Java provides eight predefined data types to represent these atomic entities; the Java community calls these the primitive types, as opposed to object types (user-defined types) that you may define yourself, such as Customer or Title.Declaring and Initializing Primitive VariablesDeclaring primitive variables is quite straightforward. For example, to declare and initialize an integer variable to hold the number of days that a video can be rented, you can write a statement, such as the following:

int numOfDays = 3;

This lesson describes how to declare and initialize variables of each of the eight primitive types.

Page 122: Java Programming

Oracle10g: Java Programming 4-4

4-4 Copyright © 2004, Oracle. All rights reserved.

Reserved Keywords

abstractfinalnativeprivateprotectedpublicstaticsynchronizedtransientvolatilestrictfp

breakcasecatchcontinuedefaultdoelsefinallyforifreturnswitchthrowtrywhile

booleanbytechardoublefloatintlongshortvoid

true falsenull

classextendsimplementsinterfacethrows

instanceofnewsuperthis

importpackage

Reserved Keywords in JavaAll the words in this slide are keywords in the Java language. These reserved words must not be used as variable names. There are 51 reserved words in Java2.Additional Reserved KeywordsIn addition to the keywords listed in the slide, const and goto are reserved and cannot be used as identifiers.

Instructor NoteDo not go through the list of keywords. Briefly describe the category of keywords in each box. Also make students aware of the reserved keywords in the notes.Also, technically speaking, true, false, and null are literals, not keywords as such. Java2 has a new reserved keyword, strictfp. Null is not a Boolean type as in PL/SQL.strictfp is used to allow for “double” variables to perform calculations, where the result is larger than Double.MAX_VALUE. strictfp is equivalent to FP-strict, which allows for a double expression to be evaluated as positive infinity (which the program prints as “Infinity”).

Page 123: Java Programming

Oracle10g: Java Programming 4-5

4-5 Copyright © 2004, Oracle. All rights reserved.

Variable Types

• Eight primitive data types:– Six numeric types– A character type– A Boolean type (for truth values)

• User-defined types:– Classes– Interfaces– Arrays

abc

Variable TypesVariables are the basic storage unit in Java. A variable is a symbolic name for a chunk of memory. Variables can be defined to hold primitive values (which are not real objects in Java) or to hold object references. The object references that they hold can be user-defined classes or Java-defined classes.Primitive Data TypesA variable declaration consists of a type and a name. Consider the following example:

double balanceDue;

This statement declares a variable called balanceDue, whose type is double. double is one of the eight primitive data types that are provided in the Java language. These types are called primitive because they are not objects and they are built into the Java language. Unlike similar types in other languages, such as C and C++, the size and characteristics of each primitive data type are defined by the Java language and are consistent across all platforms.

Page 124: Java Programming

Oracle10g: Java Programming 4-6

Variable Types (continued)Classes, Interfaces, and ArraysClasses, interfaces, and arrays are user-defined types with specific characteristics. After they are defined, you can declare variables of the new type just as you declare primitive variables.

Instructor NotePrimitive types are passed by value, unlike objects. Students who are programmers already will know the concept of “pass-by-value” versus “pass-by-reference.”

Page 125: Java Programming

Oracle10g: Java Programming 4-7

4-7 Copyright © 2004, Oracle. All rights reserved.

Primitive Data Types

Append uppercase or lowercase “L” or “F” to the number to specify a long or a float number.

Integer FloatingPoint Character True

False

byteshort

intlong

floatdouble char boolean

1, 2, 3, 4207

0xff

0

3.0F.3337F

4.022E23

0.0f

'a' '\141''\u0061'

'\n'

‘\u0000’

truefalse

false

Primitive Data TypesIntegerJava provides four different integer types to accommodate different size numbers. All the numeric types are signed, which means that they can hold positive or negative numbers.The integer types have the following ranges:• byte range is –128 to +127. Number of bits = 8.• short range is –32,768 to +32,767. Number of bits = 16.• int range is –2,147,483,648 to +2,147,483,647; int is the most common integer type.

Number of bits = 32.• long range is –9,223,372,036,854,775,808 to +9,223,372,036,854,775,807. Number of

bits = 64.Floating PointThe floating-point types hold numbers with a fractional part and conform to the IEEE 754 standard. There are two types: float and double. double is so called because it provides double the precision of float. float uses 32 bits to store data, whereas double uses 64 bits.

Page 126: Java Programming

Oracle10g: Java Programming 4-8

Primitive Data Types (continued)CharacterThe char type is used for individual characters, as opposed to a string of characters, which is implemented as a String object. Java supports Unicode, an international standard for representing a character in any written language in the world in a single 16-bit value. The first 256 characters coincide with the ISO Latin 1 character set, part of which is ASCII.BooleanThe boolean type can hold either true or false.If a value is not specified, a default one is used. The values in red in the slide are the defaults used. The default char value is null, represented as ?\u0000?, and the default value for boolean is false.

Page 127: Java Programming

Oracle10g: Java Programming 4-9

4-9 Copyright © 2004, Oracle. All rights reserved.

What Are Variables?

• A variable is a basic unit of storage.• Variables must be explicitly declared.• Each variable has a type, an identifier, and a

scope.• There are three types of variables: class, instance,

and method.

int myAge;

boolean isAMovie;

float maxItemCost = 17.98F;

TypeIdentifier

Initial value

Title: “Blue Moon”

What Is a Variable?A variable is a symbolic name for a chunk of memory in which a value can be stored. Because Java is a strongly typed language, all variables must be declared before they can be used.Variables also have a scope that determines where you can use the variable. Scope also determines the life span of the variable. When a variable is defined within a method, the variable is available only within the execution of the method. When the method ends, the variable is released and is no longer accessible. When defining a variable with a local scope use braces.Variables can also be explicitly initialized; that is, given a default value.

Page 128: Java Programming

Oracle10g: Java Programming 4-10

4-10 Copyright © 2004, Oracle. All rights reserved.

Declaring Variables

• Basic form of variable declaration:– type identifier [ = value];

• Variables can be initialized when declared.

public static void main(String[] args) {

int itemsRented = 1;

float itemCost;

int i, j, k;

double interestRate;

}

Declaring VariablesAs mentioned earlier, you must declare all variables before using them. The declaration consists of the type, followed by the variable name. Do not forget to terminate the statement with a semicolon. You can declare a variable anywhere within a block, although it is often preferable to declare it at the start.You can declare several variables in one statement. All the variables that are declared in one statement must be of the same type, such as int, char, float, and so on. The syntax is as follows:

int itemsRented, numOfDays, itemId;

Initializing VariablesYou can declare and initialize a variable in the same statement by using the assignment operator (=). Even though they are in the same statement, each variable is initialized independently. Each variable needs its own assignment and value.

int itemsRented = 0, numOfDays, itemId = 0;

In this case, itemsRented and itemId are initialized, whereas numOfDays is not. The compiler accepts this statement as valid.

Page 129: Java Programming

Oracle10g: Java Programming 4-11

4-11 Copyright © 2004, Oracle. All rights reserved.

Local Variables

• Local variables are defined only within a method or code block.

• They must be initialized before their contents are read or referenced.

class Rental {

private int instVar; // instance variable

public void addItem() {

float itemCost = 3.50F; // local variable

int numOfDays = 3; // local variable

}

}

What Is a Local Variable?A local variable is one that is defined inside a method and can therefore be accessed only inside that method. In contrast, a variable that is defined outside a method can be accessed by any method in that class. Consider the following example:

class Rental {

private int memberId; // Use in any method in the class

public void addItem() {

float itemCost = 3.50F; // Accessible only in addItem()

int numOfDays = 3; // Accessible only in addItem()

}

}

Local Variables Must Be Assigned a Value Before They Can Be UsedA local variable that is declared inside a method must be given a value before it can be used in an expression. If you use a local variable that has not been assigned a value, then the compiler issues an error.Local variables are also known as method variables or even method local variables. In this course, they are referred to as local variables.

Page 130: Java Programming

Oracle10g: Java Programming 4-12

4-12 Copyright © 2004, Oracle. All rights reserved.

Defining Variable Names

• Variable names must start with a letter of the alphabet, an underscore, or a $ symbol.

• Other characters may include digits.

• Use meaningful names for variables, such ascustomerFirstName and ageNextBirthday.

a item_Cost

itemCost _itemCost

item$Cost itemCost2

item#Cost item-Cost

item*Cost abstract

2itemCost

Rules for Legal Variable NamesA variable name must start with a letter of the alphabet, an underscore, or a dollar sign, although most Java programmers avoid the use of underscores and dollar signs. Subsequent characters can include the digits 0 through 9. Note that the Java language is case sensitive, and so lowercase letters are different from uppercase letters.There is a 64 K restriction on the length of variable names, and so it is recommended that you choose meaningful names that combine several words. By convention, the first word must be set in lowercase, and subsequent words must start with uppercase letters, such as customerFirstName.

Examples of Illegal Variable NamesThe variables in the box on the right in the slide are illegal for the following reasons:• item#Cost is illegal because # is not allowed.• item-cost is illegal because – (minus sign, not underscore) is not allowed.• item*Cost is illegal because * is an operator.• abstract is illegal because abstract is a keyword.• 2itemCost is illegal because it starts with a digit.

Instructor NoteVariable names starting with underscore are usually reserved for private variable names.

Page 131: Java Programming

Oracle10g: Java Programming 4-13

4-13 Copyright © 2004, Oracle. All rights reserved.

What Are Numeric Literals?

0 1 42 -23795 (decimal)

02 077 0123 (octal)

0x0 0x2a 0X1FF (hex)

365L 077L 0x1000L (long)

1.0 4.2 .471.22e19 4.61E-9

6.2f 6.21F

Integer literals

Floating-point literals

Six types: byte, short, int, long, float, double

What Is a Literal?Variables hold values, whereas literals are the values themselves.

float itemCost = 4.95F;

The variable is itemCost, and 4.95 is the literal. Literals can be used anywhere in a Java program, just like a variable. The difference is that literals cannot be stored or held without the use of variables.Integer LiteralsBy default, integer literals are 32-bit signed numbers. Integer literals can be specified in decimal, octal, or hexadecimal. When assigning values to a variable, do not use commas to separate thousands. To specify a literal in decimal form, simply use a number (12317.98). Literals with a leading zero are in octal form. Octal numbers are in base 8 and can contain the digits 0 through 7. To specify a hexadecimal value, use a leading 0x or 0X. The valid characters are 0 through 9 and A through F (which can be set in uppercase or lowercase).

Page 132: Java Programming

Oracle10g: Java Programming 4-14

What Is a Literal? (continued)Integer Literals (continued)A long integer is a 64-bit type. It can hold a larger number than the 32-bit version (int). Remember that the 32-bit version can hold up to 2,147,483,647. If you need to store or use a number larger than that, then you must use a long integer. You can force any integer to be treated as long by appending an uppercase or lowercase L.Floating-Point LiteralsFloating-point literals can be specified in standard format, such as 123.4, or in scientific notation, such as 1.234e2. By default, floating-point literals are taken as double precision. You can obtain single precision by appending an uppercase or lowercase F.

Page 133: Java Programming

Oracle10g: Java Programming 4-15

4-15 Copyright © 2004, Oracle. All rights reserved.

What Are Nonnumeric Literals?

True false

'a' '\n' '\t' '\077' '\u006F'

"Hello, world\n"

Boolean literals

String literals

Character literals

What Are Nonnumeric Literals?Boolean LiteralsA Boolean literal can be either true or false, which are Java keywords. Note that true and false are not numeric values and cannot be converted to integers, or vice versa.Character LiteralsCharacter literals are normally printable characters that are enclosed in single quotation marks, such as ‘a’, ‘b’, and ‘c’. To specify a nonprintable character, such as a new line or a tab, you must specify either its octal or hexadecimal Unicode value, or use its corresponding “escape sequence.” An escape sequence consists of the backslash character, followed by another character.

Character Escape Sequence

New Line '\n' Tab '\t' Single quote '\'' Backslash '\\' Unicode values '\u006F'

Page 134: Java Programming

Oracle10g: Java Programming 4-16

What Are Nonnumeric Literals? (continued)String LiteralsString literals consist of any number of characters inside double quotation marks. String literals are different from character literals in that the character primitive holds only one character. String literals hold multiple characters and are delimited by double quotation marks.

Page 135: Java Programming

Oracle10g: Java Programming 4-17

4-17 Copyright © 2004, Oracle. All rights reserved.

Guided Practice: Declaring Variables

Find the mistakes in this code and fix them:

byte sizeof = 200;

short mom = 43;

short hello mom;

int big = sizeof * sizeof * sizeof;

long bigger = big + big + big // ouch

double old = 78.0;

double new = 0.1;

boolean consequence = true;

boolean max = big > bigger;

char maine = "New England state";

char ming = 'd';

1

2

3

4

5

6

7

8

9

10

11

Problems That You May EncounterThis slide highlights some of the problems that you may encounter when declaring variables in Java. Hopefully, you will never write code like this. The following lines are illegal:Line 1The problem here is that 200 may not be assigned to a byte because 200 is treated as an int. The proper assignment is: byte b1 = (byte)200; in this case, b1 = –56.Line 3A token is needed between hello and mom, such as an assignment operator to copy the value of mom into hello. It can be that both these variables are of the same type. In that case, all that is missing is a comma.

Page 136: Java Programming

Oracle10g: Java Programming 4-18

Problems That You May Encounter (continued)Line 5There is no statement terminator (;) at the end of the statement. The // ouch comment is valid.Line 7This statement is illegal because new is a reserved word in Java.Line 10char variables can hold only a single character. Declare a String object instead:

String maine = "New England state";

The string literal is not a primitive, but is here for completeness of specifying literals that Java allows. String is really an object, whose reference to the literal is copied to the variable to which it is assigned.

Page 137: Java Programming

Oracle10g: Java Programming 4-19

4-19 Copyright © 2004, Oracle. All rights reserved.

What Are Operators?

• Operators manipulate data and objects.• Operators take one or more arguments and

produce a value.• There are 44 different operators.• Some operators change the value of the operand.

Operators in JavaOperators are used to manipulate the values that are stored in variables; these variables can be in expressions or they may contain literal values. Most programs that do anything do so by manipulating data. To calculate the due date of a video rental, the program must take the day that the video was rented and add some number of days. This is data manipulation. It is hard to imagine a program that does not use and manipulate data in some way, with the exception of raw queries of the database.Java operators take one or more arguments, or operands, and produce a value. Java provides 44 different operators that manipulate data in one way or another. Some of those operators are more complex than others, and some are used more often.This lesson focuses on the more important operators.Note: It is not possible to extend the functionality of the operators. For example, in C++, you can define your own new meaning for the “–” operator; in Java, you cannot do this. However, the “+” sign in Java is actually the only overloaded operator in Java. It is used as both an arithmetic addition operator and also for String concatenation.

Page 138: Java Programming

Oracle10g: Java Programming 4-20

4-20 Copyright © 2004, Oracle. All rights reserved.

Categorizing Operators

There are five types of operators:• Assignment• Arithmetic• Integer bitwise• Relational• Boolean

OperatorsOperators are special characters that are used to instruct the Java compiler to perform an operation on an operand. Java includes a set of 44 different operators. Most programs need only part of the 44 distinct operators.Assignment OperatorsAssignment operators set the value of a variable to a literal value or the value of another variable or expression.Arithmetic OperatorsArithmetic operators perform mathematic computations on operands. Arithmetic operators operate on all numeric types.Integer Bitwise OperatorsBitwise operators are provided to inspect and modify the internal bits that make up integer numeric types, whereas arithmetic operators modify the values of a variable as a whole unit.Relational OperatorsRelational operators compare two values. You can use relational comparison to set other values or to control program flow.Boolean Logical OperatorsBoolean operators can be used only on Boolean variables or expressions. The result of a Boolean operator is always a Boolean value.

Page 139: Java Programming

Oracle10g: Java Programming 4-21

4-21 Copyright © 2004, Oracle. All rights reserved.

Using the Assignment Operator

The result of an assignment operation is a value and can be used whenever an expression is permitted.• The value on the right is assigned to the identifier

on the left:

• The expression on the right is always evaluated before the assignment.

• Assignments can be strung together:

int var1 = 0, var2 = 0;

var1 = 50; // var1 now equals 50

var2 = var1 + 10; // var2 now equals 60

var1 = var2 = var3 = 50;

Using the Assignment OperatorAfter a variable has been declared, you can assign a value by using the assignment operator. First, the value of the expression on the right side of the assignment operator is determined or evaluated, and then the result is assigned to the variable on the left. Note the following example:

var1 = 10;var2 = var1 + 10; // the right side is evaluated first

var2 now equals 20.Assignments Can Be Strung Together in the Same StatementMultiple assignment operators can be used within a single statement as follows:

var1 = var2 = var3 = 50;

The assignment operator has “right associativity,” which means that the rightmost assignment operator is performed first in this statement. The other assignments are evaluated moving from the right to the left. The statement can be rewritten as follows, to emphasize the order in which the assignments are carried out and to make the code clearer:

var1 = (var2 = (var3 = 50));

The net result is that the value 50 is assigned to all three variables.

Page 140: Java Programming

Oracle10g: Java Programming 4-22

4-22 Copyright © 2004, Oracle. All rights reserved.

Working with Arithmetic Operators

• Perform basic arithmetic operations.• Work on numeric variables and literals.

int a, b, c, d, e;

a = 2 + 2; // addition

b = a * 3; // multiplication

c = b - 2; // subtraction

d = b / 2; // division

e = b % 2; // returns the remainder of division

Simple Arithmetic OperatorsMost of the arithmetic operators in Java are similar to those in other languages. Both operands must be of numeric types and the result of the operation is always numeric. The important things to remember when using the simple arithmetic operators are:

• Integer division results in an integer, and any remainder is ignored.• The multiply, divide, and modulus operators have higher precedence than the add and

subtract operators. In other words, multiplication, division, and modulus operations are evaluated before addition and subtraction operations.

• Arithmetic operations can be performed on variables and literals.• Modulus (mod) returns the remainder of a division operation.

Page 141: Java Programming

Oracle10g: Java Programming 4-23

4-23 Copyright © 2004, Oracle. All rights reserved.

More on Arithmetic Operators

Most operations result in int or long:• byte, char, and short values are promoted to

int before the operation.• If either argument is of the long type, then the

other is also promoted to long, and the result is of the long type.

byte b1 = 1, b2 = 2, b3;

b3 = b1 + b2; // ERROR: result is an int

// b3 is byte

Integer Arithmetic in Java Is Always Performed by Using int or longIn Java, all integer arithmetic is performed with int or long values; byte, char, and shortvalues are automatically widened (promoted) to int before an arithmetic operation commences, and the result is also int. Similarly, if the argument on one side of an arithmetic operator is a long, then the argument on the other side is automatically promoted to a long as well, and the result is a long.Consequently, if the result is to be assigned to a variable of a smaller type, then the compiler signals an error.Promoting floatsIf an expression contains a float, the entire expression is promoted to float. All literal floating-point values are viewed as doubles.

Page 142: Java Programming

Oracle10g: Java Programming 4-24

4-24 Copyright © 2004, Oracle. All rights reserved.

Examining Conversions and Casts

• Java automatically converts a value of one numeric type to a larger type.

• Java does not automatically “downcast.”

byte shortchar int

long

byte longintshortchar

Examining Conversions and CastsThe method that is used to force one variable type to be stored as another variable type is called casting.Java Can Convert Small Numeric Types into Wider Types AutomaticallyJava automatically converts or casts a variable or expression from one numeric type to a wider type if necessary. For example, if you try to assign a byte to a short, then the compiler automatically converts the byte into a short before making the assignment.Java Does Not Convert Large Numeric Types into Narrower Types AutomaticallyJava does not provide an automatic conversion from large numeric types to narrower types because this may result in loss of information. If you assign the value of a larger type to a smaller type, then the compiler will issue an error. However, you can force the compiler to convert a variable of one numeric type to a narrower type by using an explicit cast.

Page 143: Java Programming

Oracle10g: Java Programming 4-25

Examining Conversions and Casts (continued)Java Does Not Convert Large Numeric Types into Narrower Types Automatically (continued)Casting takes the internal bit pattern of the source variable and places it in the target variable’s type. This can result in a loss of data and unpredictable results. If you need to cast a variable, then you must be aware of the possibility of data loss.The syntax for an explicit cast is to put the target type in parentheses in front of the expression or variable. For example,

byte b1 = 1, b2 = 2, b3;b3 = b1 + b2; // error: the result is automatically intb3 = (byte) (b1 + b2);

// this corrects it but may// result in data loss// if the added value is // greater than positive 127

Remember that casts stop the compiler from performing useful checks on the validity of your code.Casting and Arithmetic OperationsBe careful when performing arithmetic operations while casting to a smaller type. Note that performing a narrowing conversion, such as int to byte, may produce the wrong arithmetic result. For example, if you add a byte with the value 100 to another byte with the value 100, the int result is 200. However, if this result is cast to a byte, the value becomes -56 because this is how the bit pattern for 200 is treated in a byte.

Page 144: Java Programming

Oracle10g: Java Programming 4-26

4-26 Copyright © 2004, Oracle. All rights reserved.

Incrementing and Decrementing Values

• The ++ and -- operators increment and decrement by 1, respectively:

• The ++ and -- operators can be used in two ways:

int var1 = 3;

var1++; // var1 now equals 4

int var1 = 3, var2 = 0;

var2 = ++var1; // Prefix: Increment var1 first,

// then assign to var2.

var2 = var1++; // Postfix: Assign to var2 first,

// then increment var1.

Increment and Decrement OperatorsIncrementing or decrementing a value by one is a very common operation in any language. Like C and C++, Java provides special operators for this purpose. Both the increment (++) and decrement (--) operators can be prefixed or postfixed; that is, they can be placed before or after the operand. The placement of the operators affects when the operation takes place.Prefixed OperatorWhen an increment or decrement operator is placed in front of a variable, the variable is incremented before any assignment operation. In other words, the value in the variable is adjusted by 1 (either up or down), and then it is used in the assignment.Postfixed OperatorWhen the operator is placed after the variable, the variable is adjusted after the assignment operation. The value that is assigned is the value of the variable before it is incremented or decremented.

Instructor NoteMany students find these operators confusing. Make sure that they understand the difference between prefix and postfix.

Page 145: Java Programming

Oracle10g: Java Programming 4-27

4-27 Copyright © 2004, Oracle. All rights reserved.

greater thangreater than or equal toless thanless than or equal toequal tonot equal to

>>=<<===!=

Relational and Equality Operators

int var1 = 7, var2 = 13;

boolean res = true;

res = (var1 == var2); // res now equals false

res = (var2 > var1); // res now equals true

Relational and Equality OperatorsJava provides a set of relational and equality operators for comparing the values of two variables or expressions. Unlike many languages, other than C and C++, the equality operator is a double equals sign, ==. The inequality operator is !=.Remember that the assignment operator, the equals sign, sets the value of the variable on the left of the sign to the value of the expression or variable on the right side of the equals sign. The double equals sign tests for equality of both sides. For example:

int goodCreditRating = 3;boolean goodCredit = false;goodCredit = (custRating == goodCreditRating);

In the example, if the customers rating is not 3, then goodCredit will be assigned false, which is the result of comparing the value of goodCreditRating with the customer’s actual rating. If the actual rating was 3, then the result will be true.

Instructor NoteMany students mix up the assignment operator and the equality operator. Emphasize the difference between the two.

Page 146: Java Programming

Oracle10g: Java Programming 4-28

4-28 Copyright © 2004, Oracle. All rights reserved.

Using the Conditional Operator (?:)

• Useful alternative to if…else:

• If boolean_expr is true, the result is expr1; otherwise, the result is expr2:

boolean_expr ? expr1 : expr2

int val1 = 120, val2 = 0;

int highest;

highest = (val1 > val2) ? val1 : val2;

System.out.println("Highest value is " + highest);

The Conditional Operator (?:)The conditional operator (?:) is the only ternary operator in Java, which means it has threeoperands. The conditional operator is an expression that returns a value and is a useful alternative to if…else.The Boolean expression evaluates first and, if true, returns the value of the first expression (expr1) or if false, returns the value of the second expression (expr2). For example, consider the conditional operator:

max = (10 > 8) ? 100: 200;

Because 10 is greater than 8, max is set to 100. The values of the expressions (100 and 200) can be any valid Java expressions including literals.A similar effect can be achieved by using an if…else statement, as follows. Use whichever approach you find more intuitive.

if (10 > 8)

max = 100;

else

max = 200;

Page 147: Java Programming

Oracle10g: Java Programming 4-29

4-29 Copyright © 2004, Oracle. All rights reserved.

Using Logical Operators

Results of Boolean expressions can be combined by using logical operators:

and (with or without short-circuit evaluation)or (with or without short-circuit evaluation)exclusive ornot

&& &|| |^!

int var0 = 0, var1 = 1, var2 = 2;

boolean res = true;highest = (val1 > val2)? val1 : val2;

res = !res;

Logical OperatorsBoolean values and expressions that result in Boolean values can be combined by using the logical operators &, |, and !, which represent AND, OR, and NOT operations, respectively. Short-Circuit EvaluationThe && and ||operators provide support for “short-circuit evaluation”; if the expression on the left of the operator has already determined the outcome of the whole logical expression, then the expression on the right of the operator is not performed.Consider the following example using the && operator:

if (test1() && test2()) If test1 returns false, then there is no need to carry out test2 because a logical ANDrequires both tests to yield true; therefore, test2 is not performed.Likewise, consider the following example using the || operator:

if (test1() || test1())If test1 returns true, there is no need to carry out test2 because a logical OR only requires one of the tests to yield true; therefore, test2 is not performed.Non-Short-Circuit EvaluationIf you have a Boolean expression involving two tests and you want the second test to be performed regardless of the outcome of the first test, use the & operator instead of &&, and the |operator instead of ||. Also, note that there is a ^ operator that performs the exclusive ORoperation.

Page 148: Java Programming

Oracle10g: Java Programming 4-30

4-30 Copyright © 2004, Oracle. All rights reserved.

Compound Assignment Operators

An assignment operator can be combined with any conventional binary operator:

double total=0, num = 1;

double percentage = .50;

total = total + num; // total is now 1

total += num; // total is now 2

total -= num; // total is now 1

total *= percentage; // total is now .5

total /= 2; // total is now 0.25

num %= percentage; // num is now 0

Compound Assignment OperatorsExpressions such as var1 = var1 + 20 are so common that Java provides compound assignment operators as a shorthand equivalent. You can form these compound operators by combining the assignment operator with any of the conventional binary operators. Binary operators are those operators that use two arguments such as +, -, *, / and so on.For example, the expression

rentalDueDate = rentalDueDate + 3;

can be rewritten as follows:rentalDueDate += 3;

This expression takes the current value of rentalDueDate and adds 3. It then places the result into rentalDueDate.The %= operator computes the remainder of dividing the first variable by the second, and then assigns it to the first variable.

Page 149: Java Programming

Oracle10g: Java Programming 4-31

4-31 Copyright © 2004, Oracle. All rights reserved.

Operator Precedence

Operators

++ -- + - ~! (type)* / %+ - +<< >> >>>< > <= >=

instanceof== !=&^|&&||?:= op=

Comments

Unary operators

Multiply, divide, remainderAdd, subtract, add stringShift (>>> is zero-fill shift)Relational, type compare

EqualityBit/logical ANDBit/logical exclusive ORBit/logical inclusive ORLogical ANDLogical ORConditional operatorAssignment operators

Order

1

2345

67 8910111213

Assoc.

R

LLLL

LLLLLLRR

Java OperatorsPrecedence refers to the order in which operators are executed. For example, multiplication is always performed before addition or subtraction. The table in the slide shows the Java operators in order of precedence, where row 1 has the highest precedence. With the exception of the unary, conditional, and assignment operators, which are right associative, operators with the same precedence are executed from left to right.AssociativityOperators with the same precedence are performed in order, according to their associativity. In the slide, the final column in the table shows the associativity for each operator:

• L indicates left-to-right associativity. Most operators fall in this category.• R indicates right-to-left associativity. Only the unary operators (row 1), the conditional

operator (row 12), and the assignment operators (row 13) fall in this category.For example, consider the following statement:

int j = 3 * 10 % 7;The * and % operators have the same precedence, but have left-to-right associativity. Therefore, the * is performed first, as though you had used parentheses as follows:

int j = (3 * 10) % 7; // Same result, 30%7, which is 2

If you choose to place parentheses in a different place, then you get a different result:int j = 3 * (10 % 7);// Different result, 3*3, which is 9

Page 150: Java Programming

Oracle10g: Java Programming 4-32

4-32 Copyright © 2004, Oracle. All rights reserved.

More on Operator Precedence

• Operator precedence determines the order in which operators are executed:

• Operators with the same precedence are executed from left to right (see note in text below):

• Use parentheses to override the default order.

int var1 = 0;

var1 = 2 + 3 * 4; // var1 now equals 14

int var1 = 0;

var1 = 12 - 6 + 3; // var1 now equals 9

Using the Precedence TableThe precedence table defines the order in which operators are evaluated. If you have a complex expression containing many operators, then refer to the precedence table to make sure that the operators are being performed in the order that you expect.To make things simpler, you can use parentheses to override the default order in which operators are executed. Many programmers also use parentheses where they are not strictly necessary to make the code more readable.Note: The second bullet in the slide states that operators with the same precedence are evaluated from left to right. This is true for all operators except the unary operators, the conditional operator, and the assignment operators, which are evaluated from right to left as described on the previous page.Using ParenthesesUse parentheses to control the order of statement evaluation exactly. Consider the following variations:

var1 = 12 - 6 + 3; // var1 now equals 9var1 = 12 - (6 + 3); // var1 now equals 3

Page 151: Java Programming

Oracle10g: Java Programming 4-33

4-33 Copyright © 2004, Oracle. All rights reserved.

Concatenating Strings

The + operator creates and concatenates strings:

String name = "Jane ";

String lastName = "Hathaway";

String fullName;

name = name + lastName; // name is now

//"Jane Hathaway"

// OR

name += lastName; // same result

fullName = name;

Using Operators with StringsOnly three operators can be used with strings: the assignment operator (=), the addition operator (+), and the compound addition assignment operator (+=).Using the Assignment OperatorYou can use the assignment operator to create a new String object or to set the value of an existing String reference to refer to a String object:

String firstName = "John";firstName = "John";

Using the Addition OperatorThe addition operator is very useful with strings because it creates a new String object by concatenating the contents of two String objects. Consider the following code:

String firstName = "John";String lastName = "Doe";fullName = firstName + " " + lastNamefullName is now "John Doe".

If part of a String expression is not a String, then Java automatically converts that part into a String object and then concatenates its contents with the other String object to form a new String as a result.Using the Compound Assignment OperatorYou can also use the += operator to concatenate a String to an existing String.

Page 152: Java Programming

Oracle10g: Java Programming 4-34

4-34 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:• Java has eight primitive data types.• A variable must be declared before it can be used.• Java provides a comprehensive set of operators.• Explicit casting may be necessary if you use data

types smaller than int.• The + and += operators can be used to create and

concatenate strings.

Page 153: Java Programming

Oracle10g: Java Programming 4-35

4-35 Copyright © 2004, Oracle. All rights reserved.

Practice 4: Overview

This practice covers:• Declaring and initializing variables• Using various operators to compute new values• Displaying results on the console

Practice 4: OverviewNote: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les03 directory, and continue with this practice.Remember that if you close a DOS window or change the location of the .class files, then you must set the CLASSPATH variable again.

Page 154: Java Programming

Oracle10g: Java Programming 4-36

Practice 4: Exploring Primitive Data Types and OperatorsGoalThe goal of this practice is to declare and initialize variables, and use them with operators to calculate new values. You will also be able to categorize the primitive data types and use them in code.Note: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want move on to this practice, then change to the les03 directory, and continue with this practice.Your AssignmentYou are now ready to add some code to the simple main() method in the OrderEntry application class created in the last exercise. In the following steps, you declare some variables to hold the costs of some rental items. After displaying the contents of these variables, you perform various tests and calculations on these variables and display the results.Modify the OrderEntry Class and Add Some Calculations

1. Declare variables in the main() method.a. Declare and initialize two variables to hold the cost of two rental items. The values of

the two items must be 2.95 and 3.50. Name the items anything you like, but do not use single-character variable names; instead, use longer meaningful names such as item1 and item2. Also, think about your choice of variable type.Note: Recompile the class after each step, fix any compiler errors that may arise, and run the class to view any output.

b. You may have used four different statements: two to declare your variables, and two more to initialize them. Now try to declare and initialize the variables in a single line. Finally, see whether you can combine the declaration and initialization of both variables into a single statement.

c. Use System.out.println() to display the contents of your variables. After recompiling the class, run the class and see what is displayed.

d. Modify the code you have just written to display more meaningful messages, such as Item 1 cost 2.95.(Hint: Use the + operator.)

e. Now that you have the total for the items, calculate the total for the rental by adding the tax. The tax rate is 8.25%. Create a variable to hold this value. Calculate the total charge for the rental. Also declare and initialize a variable to hold the number of days and to track the line numbers. This variable holds the number of days for which the customer rents the items, and initializes the value to 2 for two days.

f. Display the total in a meaningful way such as Total cost:6.982125.

Page 155: Java Programming

Oracle10g: Java Programming 4-37

Practice 4: Exploring Primitive Data Types and Operators (continued)2. Calculate the total cost, and display the result.

a. Extend the item total to be the item cost * the number of rental days, displaying: Item 1 is 2.95 * 2 days = 5.9

b. Display the results in a meaningful way. Your result must look like the following:Total cost: 13.96425.

3. Compile and run the OrderEntry class. Make sure the .class file has been placed in the correct directory (E:\labs\OrderEntry\classes\oe).Note: Make sure the CLASSPATH variable points to the location of your .class files (E:\labs\OrderEntry\src\oe).

Page 156: Java Programming
Page 157: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Controlling Program Flow

Schedule: Timing Topic60 minutes Lecture30 minutes Practice90 minutes Total

Page 158: Java Programming

Oracle10g: Java Programming 5-2

5-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Use decision-making constructs• Perform loop operations• Write switch statements

Lesson AimThis lesson introduces Java’s decision-making and repetition constructs. You learn how to use those constructs to build nonlinear applications. Like other block-structured languages, Java supports statements to control the flow of execution in a program. This lesson explains how to use decision-making constructs and how to use the loop statements that are provided in Java.

Page 159: Java Programming

Oracle10g: Java Programming 5-3

Lesson Aim (continued)What Is Program Flow?By default, computer programs start execution at, or near, the beginning of the code and move down the code until the end. This is fine if your program does one thing, always in the same order, and never needs to deviate from this path. Unfortunately, this does not happen very often in most businesses.Program control constructs are designed so that the programmer can design and build programs that perform certain parts of code conditionally. There are also constructs so that code can be executed repetitively. These coding structures give you infinite control of what, when, and how many times your program performs a particular task.By providing standard control mechanisms, Java gives programmers control over the exact execution order of their program code.

Page 160: Java Programming

Oracle10g: Java Programming 5-4

5-4 Copyright © 2004, Oracle. All rights reserved.

Categorizing Basic Flow Control Types

Flow control can be categorized into four types:

Sequential

TransferSelection

Iteration

Categorizing Basic Flow Control TypesSequentialSequential is the flow control type where the program flow follows a simple sequential path, executing one statement after another. The primary sequential structure is a compound block statement, which is a series of statements inside braces.SelectionSelection is the flow control type where only one path out of a number of possibilities is taken. Simple selection involves the conditional execution of a statement or block of code, which is guarded by an expression that will have the value true if the guarded code is to be executed. This is the if statement. An if…else statement provides an alternate path of execution: The true or false evaluation of a control expression determines which branch is taken. A switch statement supports a multiway branch based on the value of a control expression.

Page 161: Java Programming

Oracle10g: Java Programming 5-5

Categorizing Basic Flow Control Types (continued)IterationIteration is the type where one statement or block of code is executed repeatedly. A simple loop executes the same code whereas a control expression has a true value, terminating execution when the expression evaluates to false. Java provides three loop forms: while, do…while, and for loops.TransferTransfer is the type where the point of execution jumps to a different point in the program. Transfer is generally considered poor programming style, because it is hard to follow the logic and therefore difficult to maintain the code.Goto The Java language does not have a goto statement. This allows the language to be less complex and eliminates rules about how the goto must operate in for statements. The break and continue statements work in the majority of occasions where a goto would normally be used.

Page 162: Java Programming

Oracle10g: Java Programming 5-6

5-6 Copyright © 2004, Oracle. All rights reserved.

Using Flow Control in Java

• Each simple statement terminates with a semicolon (;).

• Group statements by using the braces { }.• Each block executes as a single statement within

the flow of control structure.

{boolean finished = true;System.out.println("i = " + i);i++;

}

Using Flow Control in JavaSimple StatementsA simple statement is any expression that terminates with a semicolon. For example:

var1 = var2 + var3;var3 = var1++;var3++;

Compound Statements (Blocks)Related statements can be grouped in braces to form a compound statement or block:

{int i;

boolean finished = true;System.out.println("i = " + i);i++;

}

Semantically, a block behaves like a single statement and can be used anywhere a single statement is allowed. There is no semicolon after the closing brace. Java does not use matched block delimiters, such as if and end if, like PL/SQL. Any variables that are declared in a block remain in scope up to the closing brace. After the block is exited, the block variables cease to exist.Blocking improves readability of program code and can help to make your program easier to control and debug.

Page 163: Java Programming

Oracle10g: Java Programming 5-7

5-7 Copyright © 2004, Oracle. All rights reserved.

Using the if Statement

if ( boolean_expr )

statement1;

[else

statement2];

if (i % 2 == 0)

System.out.println("Even");

else

System.out.println("Odd");

… if (i % 2 == 0) {

System.out.print(i);

System.out.println(" is even");

}

General:

Examples:

The if StatementThe if statement provides basic selection processing. A Boolean control expression determines which branch is taken, as follows:

• If the expression evaluates to true, the first branch is taken; that is, the if body is executed.

• If the expression evaluates to false, the second branch is taken; that is, the elsebody is executed. The else clause is optional; if it is omitted, nothing is executed if the control expression evaluates to false.

Exampleif (orderIsPaid) {

System.out.println("send with receipt");}else {

System.out.println("collect funds");}

Common Mistakes When Using if StatementsUse the equality operator (==) rather than the assignment operator (=) in the control expression.

Page 164: Java Programming

Oracle10g: Java Programming 5-8

5-8 Copyright © 2004, Oracle. All rights reserved.

Nesting if Statementsif (speed >= 25)

if (speed > 65)

System.out.println("Speed over 65");

else

System.out.println("Speed >= 25 but <= 65");

else

System.out.println("Speed under 25");

if (speed > 65)

System.out.println("Speed over 65");

else if (speed >= 25)

System.out.println("Speed greater… to 65");

else

System.out.println("Speed under 25");

Nested if StatementsWhere multiple tests are necessary, if statements can be nested. However, this approach is generally not recommended because you have to maintain a mental stack of the decisions that are being made; this becomes difficult if you have more than three levels of nested ifstatements.Also, it is very easy to forget that an else clause always binds to the nearest if statement above it that is not already matched with an else, even if the indentation suggests otherwise. This is sometimes referred to as the “dangling else” problem.The if…else…if ConstructThe “dangling else” problem can be solved with a prudent use of braces, but a cleaner approach is to use the if…else… if construct, as shown in the second example in the slide. Note that these are two separate keywords; unlike some languages, Java does not have an elseif keyword.

Page 165: Java Programming

Oracle10g: Java Programming 5-9

5-9 Copyright © 2004, Oracle. All rights reserved.

Guided Practice: Spot the Mistakes

int x = 3, y = 5;

if (x >= 0)

if (y < x)

System.out.println("y is less than x");

else

System.out.println("x is negative");

int x = 7;

if (x = 0)

System.out.println("x is zero");

int x = 14, y = 24;

if ( x % 2 == 0 && y % 2 == 0 );

System.out.println("x and y are even");

1

2

3

Guided Practice: Spot the MistakesExample 1: Use braces to associate or bind statements and make the code easier to follow.

if (x >= 0) {if (y < x)

System.out.println("y is less than x");}else

System.out.println("x is negative");It is the last if that pairs with an else. Although it does not become a compiler error, it becomes a logic error. Example 2: The second example uses an assignment operator (=) rather than an equality operator (==) in the if test. Fortunately, Java compilers detect this mistake and indicate a compiler error because the expression in the if test must evaluate to a Boolean.Example 3The third example has an extra semicolon at the end of the if test. This is not a compiler error; the compiler treats the semicolon as an empty if body, as follows:

if ( x % 2 == 0 && y % 2 == 0 ); // Null "if" body

Page 166: Java Programming

Oracle10g: Java Programming 5-10

5-10 Copyright © 2004, Oracle. All rights reserved.

Defining the switch Statement

• The switchstatement is useful when selecting an action from several alternative integer values.

• Integer_expr must be byte, int, char, or short.

switch ( integer_expr ) {

case constant_expr1:

statement1;

break;

case constant_expr2:

statement2;

break;

[default:

statement3;]

}

The switch StatementThe switch statement provides a clean way to dispatch to different sections of your code, depending on predefined values. It can be used to choose among many alternative actions, based on the value.Anatomy of the switch StatementThe switch statement is useful when selecting some action from several alternatives. The value inside the test expression must be a byte, char, short, or int. It cannot be aboolean, long, double, float, String, or any other kind of object. The value inside the test expression is compared against the case labels, which are constant expressions.

• If a match is found, then the statements following the label are executed. Execution continues until a break is encountered, which transfers control to the statement following the switch statement.

• If no match is found, then control passes to the statements following the defaultlabel. The default label is optional; if no default label is provided, then the switch statement does nothing when no match is found. It is a good practice to always provide a default label, even if no action is required.

Page 167: Java Programming

Oracle10g: Java Programming 5-11

The switch Statement (continued)The case LabelsThe case labels must be constant expressions and known at compile time. You can use either literal numbers or final variables (constants).

Page 168: Java Programming

Oracle10g: Java Programming 5-12

5-12 Copyright © 2004, Oracle. All rights reserved.

More About the switch Statement

• case labels must be constants.

• Use break to jump out of a switch.

• It is recommended to always provide a default.

switch (choice) {

case 37:

System.out.println("Coffee?");

break;

case 45:

System.out.println("Tea?");

break;

default:

System.out.println("???");

break;

}

More About switchThe slide shows a simple example of a switch statement. There are situations where falling through can be useful. To fall through, simply do not include a break as in the following example:char c = 'b';switch (c) {

case 'a': System.out.println("First letter in alphabet"); break;

case 'b': System.out.println("Second letter in alphabet");case 'c': System.out.println("Third letter in alphabet");case 'd': System.out.println("Fourth letter in alphabet");

}

In the above example, the results that are printed displays the following lines because of the absence of a break statement between each case test for ‘b’, ‘c’, and ‘d.’

Second letter in alphabetThird letter in alphabetFourth letter in alphabet

Page 169: Java Programming

Oracle10g: Java Programming 5-13

5-13 Copyright © 2004, Oracle. All rights reserved.

Looping in Java

• There are three types of loops in Java:– while– do…while– for

• All loops have four parts:– Initialization– Iteration condition– Body– Termination

Looping in JavaWhat Is Looping?Looping in any programming language refers to repeatedly executing a block of code until a specified condition is met. Java provides three standard loop constructs: while,do…while, and for.All Loops Have Four PartsAll loops contain four parts: initialization, iteration, statement body, and termination.Initialization: Initialization sets the initial conditions of the loop. This includes any variable that may be incremented to control execution of the loop.Iteration: The iteration is the code that you want to execute after the body but before you go through the loop again. It is used for control of the loop execution.Body: The body is executed if the termination condition is true.Termination: Termination is the expression that is evaluated to determine if the body must be executed. The expression must be a Boolean expression. If the expression evaluates to true, then the body is executed; if it is false, then the body is not executed.Choosing the appropriate loopUse the while loop to ensure that the termination condition is tested before executing the body of the loop. Use the do…while to ensure that the body executes once before the termination condition is made. The for loop is similar to the while loop.

Page 170: Java Programming

Oracle10g: Java Programming 5-14

5-14 Copyright © 2004, Oracle. All rights reserved.

Using the while Loop

while is the simplest loop statement and contains the following general form:

while ( boolean_expr )

statement;

int i = 0;

while (i < 10) {

System.out.println("i = " + i);

i++;

}

Example:

Anatomy of the while LoopThe simplest loop construct in Java is the while loop. In the while loop, the loop body is executed repeatedly while a boolean control expression evaluates to true. When the control expression evaluates to false, the loop terminates and control passes to the first statement after the closing brace of the loop body. Note that the control expression is evaluated before the loop body is executed. If the control expression evaluates to false the first time, then it does not enter the loop body.Common Mistakes When Using while LoopsA common mistake when using while loops is to forget to iterate the variable that is used in the control expression. This results in an infinite loop. Another common mistake is to put a semicolon at the end of the first line, between the control expression and the loop body. This places the incrementing of the counter outside the loop and results in an infinite loop.

Instructor NoteThis loop will execute 10 times, with loop counter i varying from 0 through 9.

Page 171: Java Programming

Oracle10g: Java Programming 5-15

5-15 Copyright © 2004, Oracle. All rights reserved.

Using the do…while Loop

do…while loops place the test at the end:

do

statement;

while ( termination );

int i = 0;

do {

System.out.println("i = " + i);

i++;

} while (i < 10);

Example:

Anatomy of the do…while LoopThe do…while loop is similar to the while loop except that the control expression is evaluated after the loop body has been executed. This guarantees that the loop body executes at least once. This construct is useful if you want to execute the statement at least once without regard to the while condition.Common Mistakes When Using do…while LoopsA common mistake when using do…while loops is to forget one of the braces of a compound statement or the final semicolon. The compiler detects both of these types of errors.

Page 172: Java Programming

Oracle10g: Java Programming 5-16

5-16 Copyright © 2004, Oracle. All rights reserved.

Using the for Loop

for loops are the most common loops:

How would this for loop look using a while loop?

for (i = 0; i < 10; i++)

System.out.println(i);

for ( initialization; termination; iteration )

statement;

Example:

Anatomy of the for LoopThe for loop combines components of a loop into a single construct with positions for each component. The three components that are enclosed in parentheses are separated by semicolons.Common Mistakes When Using for LoopsA common coding error with for loops is to put a semicolon after the closing parenthesis. This is equivalent to an empty loop body that does nothing on each iteration.for Loops and while Loops ComparedThe for loop shown in the slide is equivalent to the following while loop:

i = 0;

while (i < 10) {

System.out.println(i);

i++;

}

Instructor Note The for loop integrates the four parts (initialization, iteration, body, and termination) in the statement.

Page 173: Java Programming

Oracle10g: Java Programming 5-17

5-17 Copyright © 2004, Oracle. All rights reserved.

More About the for Loop

• Variables can be declared in the initialization part of a for loop:

• Initialization and iteration can consist of a list of comma-separated expressions:

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

System.out.println("i = " + i);

for (int i = 0, j = 10; i < j; i++, j--) {

System.out.println("i = " + i);

System.out.println("j = " + j);

}

More About the for LoopDeclaring Variables in the Initialization Part of a for LoopThe initialization expression in a for loop can include a declaration, as shown in the first example in the slide. Any variable that is declared here is local to the for loop itself. After the execution leaves the loop, the variable is no longer available.Complex Initialization and Iteration ComponentsThe initialization and iteration components can consist of several comma-separated expressions, as shown in the second example in the slide, where two indexes are incremented or decremented in opposite directions.Empty Initialization, Termination, or Iteration ExpressionsAny of the components of a for loop can be omitted. For example, a common way to implement a “do-forever” loop is as follows:

for (;;) { // loop forever…

}

This kind of loop is common in multithreaded programs, where one of the threads loops continually doing some dedicated task. For example, a server program may have a thread that loops forever listening for connections from client programs.

Page 174: Java Programming

Oracle10g: Java Programming 5-18

5-18 Copyright © 2004, Oracle. All rights reserved.

Guided Practice: Spot the Mistakes

int x = 10;

while (x > 0);

System.out.println(x--);

System.out.println("We have lift off!");

int x = 10;

while (x > 0)

System.out.println("x is " + x);

x--;

int sum = 0;

for (; i < 10; sum += i++);

System.out.println("Sum is " + sum);

1

2

3

Guided Practice: Spot the MistakesExample 1The first example contains an extra semicolon at the end of while. This is not a compiler error; the compiler treats the semicolon as an empty loop body, as follows:

while (x > 0); // Null loop body

Example 2The problem with the second example is that x is not changed inside the loop. The x-- term is deemed to be outside the loop because there are no braces. Therefore, if x is greater than zero the first time through the loop, it will always be greater than zero, and the loop will never terminate.Example 3The problem with this example is that i is not initialized anywhere. The rest of the loop is fine. Here is a description of what is happening:

• The loop keeps iterating while i is less than 10.• The semicolon at the end of the for line indicates a null loop body.• The iteration expression in the for loop adds i to sum, and then increments i ready

for the next loop iteration.

Page 175: Java Programming

Oracle10g: Java Programming 5-19

5-19 Copyright © 2004, Oracle. All rights reserved.

The break Statement

• Breaks out of a loop or switch statement• Transfers control to the first statement after the

loop body or switch statement• Can simplify code but must be used sparingly

…while (age <= 65) {

balance = (balance+payment) * (1 + interest);if (balance >= 250000)

break;age++;

}…

Anatomy of the break StatementYou can use a break statement to exit any kind of loop when a specific condition is met. Control is transferred immediately to the first statement following the closing brace of the loop body.Should break Be Used?Many programmers frown upon the use of break because it is not strictly necessary. For example, in the code fragment that is shown in the slide, you could have avoided using break by expanding the control expression as follows:

while (age <=65 && balance < 250000) {…

}

Nevertheless, the use of break statements is useful where you need to abort a loop if some event occurs while executing the loop body. As you have already seen, break statements are also used in switch statements to prevent falling through to a subsequent case label.

Page 176: Java Programming

Oracle10g: Java Programming 5-20

5-20 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:• The primary means of decision-making is the if

statement, with the optional else.• Java also offers the switch statement.• Java provides three loop statements: while,

do…while, and for.• Use break and continue sparingly.

Page 177: Java Programming

Oracle10g: Java Programming 5-21

5-21 Copyright © 2004, Oracle. All rights reserved.

Practice 5: Overview

This practice covers:• Performing tests by using if…else statements• Using loops to perform iterative operations• Using the break statement to exit a loop• Using the &&, ||, and ! operators in Boolean

expressions

Practice 5: OverviewNote: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les04 directory, and continue with this practice.Remember that if you close a DOS window or change the location of the .class files, then you must set the CLASSPATH variable again.

Page 178: Java Programming

Oracle10g: Java Programming 5-22

Practice 5: Controlling Program FlowGoalThe goal of this practice is to make use of flow control constructs that provide methods to determine the number of days in a month, and handle leap years. Note: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les04 directory, and continue with this practice. Remember that if you close a DOS window or change the location of the .class files, then you must set the CLASSPATH variable again.Your AssignmentIn this exercise, you create a program that calculates the return date of a rented item based on the day it was rented and how many days it can be rented. You must determine the number of days in the month and whether it is a leap year.Modify the OrderEntry class to calculate dates

1. Determine the number of days in a month. You use a switch statement to set an integer value to the number of days in the month you specify. For now, add all the code in the main() method of the OrderEntry.java application.

a. Declare three integers to hold a day, a month, and a year. Initialize these variables with a date of your choice.

b. Add a simple statement to display the date; choose whichever format you prefer, such as day/month/year or month/day/year.

c. Declare a variable to hold the number of days in the current month. Then, using a switch statement, determine the value to store in this variable. Use daysInMonth as the name of the variable.Note: The hardest part of this exercise is remembering how many days there really are in each month. Here is a reminder if you need it: There are 30 days in September, April, June, and November. All the rest are 31, except for February, which is 28 (ignore leap years for now). Add a simple statement to display the number of days for the current month.

d. Add a simple statement to display the number of days for the current month:System.out.println(daysInMonth + " days in month");

2. Ensure your CLASSPATH is set correctly (E:\labs\OrderEntry\src\oe).Compile and test the program. Experiment with different values for the month. What happens if you initialize the month with an invalid value, such as 13?

For January 27, 2000, the output should look something like:27/1/200031 days in the month

3. Use a for loop to display dates.a. Using a for loop, extend your program so that it prints out all the dates between

your specified day/month/year and the end of the month. For example:if your day variable is 27,and your month variable is 1 (January), and your year variable is 2000,

Page 179: Java Programming

Oracle10g: Java Programming 5-23

Practice 5: Controlling Program Flow (continued)3. Use a for loop to display dates. (continued)

then your program must display all the dates between 27 January and 31 Januaryinclusive, as follows:

27/1/200028/1/200029/1/200030/1/200031/1/2000

Hint: You must use the result of the switch statement in question 2 to determine the last day in the month.

b. Compile and test your program making sure it works with a variety of dates.c. Modify your program so that it outputs a maximum of 10 dates. For example, if

your day/month/year variables are 19/1/2000, the output must now be as follows:19/1/200020/1/200021/1/200022/1/200023/1/200024/1/200025/1/200026/1/200027/1/200028/1/2000

Make sure your program works for dates near the end of the month, such as 30/1/2000. In this situation, it must output only the following:30/1/200031/1/2000

d. Compile your program, and test it with a variety of dates to make sure it still works.

4. Determine whether the year you specify is a leap year. You use the booleanoperators && and ||.

a. Build a boolean statement that tests year to see whether it is a leap year. A year is a leap year if it is divisible by 4, and it is either not divisible by 100, or it is divisible by 400.

b. Modify your switch statement from question 2, to cater for leap years. Remember that February has 29 days in a leap year and 28 days in nonleap years.

c. Build and test your program with a variety of dates. The following table includes some sample leap years and nonleap years you may want to use as test data:Leap years Non-leap years

1996 19971984 20012000 19001964 1967

Page 180: Java Programming

Oracle10g: Java Programming 5-24

Practice 5: Controlling Program Flow (continued)5. You must calculate the date on which each rental is due. The due date is the current

date plus 3 days. For this test, you use a number of different dates for the current date, not just today’s date.

a. Declare three variables to hold the due date (dueDay, dueMth, dueYr).b. Add a variable to hold the rental period of 3 days.c. Add the due date calculation to your program that adds the rental period to the

date you used in step 1. Display your original date and the due date in a meaningful way. The output must look something like:Rental Date: 27/2/2001Number of rental days: 3Date Due back: 2/3/2001

d. Test your routine with several dates; try 29/2/2001.e. What are the problems you must address?f. Modify your program to catch input dates with invalid months (not 1 to 12).

6. In building a software solution to a problem, you must determine the size and scope of the problem and address all the pertinent issues. One of the issues is what to do if the rental period extends beyond the current month. For example, if the rental date is August 29 and the rental is for three days, the return date must be September 1, but with the current solution, it is August 32, which is an obvious error. Acme Video store rents items only for 10 or fewer days. You must ensure that you take care of the following:

a. Add code to make sure the calculation results in a valid day.b. If the rental crosses into a new month, make sure to increment the month.c. If the rental crosses into a new year, make sure to increment the year.d. Test your routine with several dates.e. Modify your program to catch input dates with invalid months (not 1 to 12).

Page 181: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Building Applications with Oracle JDeveloper 10g

Schedule: Timing Topic45 minutes Lecture30 minutes Practice75 minutes Total

Page 182: Java Programming

Oracle10g: Java Programming 6-2

6-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Create new projects, workspaces, and

applications• Build Java applications in JDeveloper• Enhance user interface frame design• Debug an application by using JDeveloper

debugger• Define classes by using JDeveloper• Describe how JDeveloper can be used to build

enterprise applications

Lesson AimThis lesson introduces you to Oracle JDeveloper. You learn how to create new projects and applications, and how to use the various panes in the IDE to edit source code and modify design of the user interface frame.

Page 183: Java Programming

Oracle10g: Java Programming 6-3

6-3 Copyright © 2004, Oracle. All rights reserved.

What Is Oracle JDeveloper 10g?

• Oracle JDeveloper 10g provides an integrated development environment (IDE).

• Build, compile, and run Java applications by using Oracle JDeveloper.

• Use wizards to help build source code.• View objects from many perspectives: code,

structure, layout, and so on.

Building Applications with Oracle JDeveloper 10gYou can use Oracle JDeveloper 10g to build a number of different types of Java components. This lesson focuses on using the JDeveloper IDE for building applications.Wizard DrivenA wizard is a graphical tool that guides you step-by-step through the process of defining a new element in the IDE. Oracle JDeveloper 10g provides a number of wizards, including:

• Application Workspace Wizard: Defines a new application and associated projects• Applet Wizard: Defines a new Java applet and adds it to the specified project• EJB Wizard: Defines a new Enterprise JavaBean (EJB) and adds it to the specified

project• JSP Wizard: Defines a new JavaServer Page (JSP) and adds it to the specified

project• HTTP Servlet Wizard: Defines a new servlet and adds it to the specified project

Design a User InterfaceOracle JDeveloper 10g provides an interface for designing the visual parts of your program. JDeveloper enables you to specify the following features of the user interface:

• Size and position of controls• Properties for each control, such as labels, enabled or disabled status, font, and so on• Event handler methods

Page 184: Java Programming

Oracle10g: Java Programming 6-4

6-4 Copyright © 2004, Oracle. All rights reserved.

Exploring the JDeveloper Environment

System Navigator Code Editor Property Inspector

Component Palette

The Oracle JDeveloper 10g EnvironmentJDeveloper contains four major user interface components. These components are what you use to edit code, design and manage the user interface, and navigate around your program.Component PaletteProperties are attributes that define how a component appears and responds at run time. In JDeveloper, you set a component’s initial properties during design time, and your code can change those properties at run time. System NavigatorSystem Navigator is made up of two components. The Navigator pane shows a list of files or classes in a project. The files may be Java source files, .class files, graphics files, HTML, XML documents, and so on. The Structure pane lists all the methods, fields, and graphical user interface (GUI) components in a selected class.Code EditorEditors are where most of the work takes place; this is where you write code and design user interfaces. Open an editor by double-clicking the item you want to edit or view. Property InspectorProperty Inspector is the window that shows the properties and events associated with a selected component in the design section of an editor.

Page 185: Java Programming

Oracle10g: Java Programming 6-5

6-5 Copyright © 2004, Oracle. All rights reserved.

Examining Workspaces

• Contain multiple projects• Enable you to view

currently used objectsWorkspace

Navigator pane

Structure pane

Application OrganizationOracle JDeveloper 10g uses a well-defined structure to manage Java programming applications. The structure is hierarchical and supports workspaces, projects, images, .html files, and so on.WorkspacesWorkspace is the highest level in the control structure. It is a view of all the objects you currently need, while you are working. A workspace keeps track of the projects you use and the environment settings while you are developing your Java program. When you open JDeveloper, the last workspace used is opened by default, so you can resume where you last stopped working.Workspaces are stored in files with the extension .jws. You do not edit a workspace file directly. Whenever you save your workspace, you are prompted to save all the current open files. To save the open and modified files, select the Save or Save All option from the File menu. Note: You can view the content of a workspace file by using any text editor.

Page 186: Java Programming

Oracle10g: Java Programming 6-6

Application Organization (continued)Determining WorkspacesConsider workspaces to be a view into the objects currently used. You may choose to create workspaces, which include projects that were created in different workspaces. Workspace object groupings can be based around a business area (Accounts Payable, General Ledger, Accounts Receivable), the phase in a life cycle (analysis, design, deploy) or the structure of the application (UI, business logic, data structure).

Page 187: Java Programming

Oracle10g: Java Programming 6-7

6-7 Copyright © 2004, Oracle. All rights reserved.

What Are Projects?

• Contain related files

• Manage project and environment settings

• Manage compiler and debug options

Project

Projectfiles

ProjectsJDeveloper projects organize file elements used to create your program. A project file has the file extension .jpr and keeps track of the source files, packages, classes, images, and other elements that may be needed for your program. You can add multiple projects to your workspace to easily access, modify, and reuse your source code. You can view the content of a project file by using any text editor.Projects also manage environment variables such as the source and output paths used for compiling and running your program. Projects also maintain compiler, run time, and debugging options, so you can customize the behavior of those tools per project.In the Navigator pane, projects are displayed as the second level in the hierarchy under the workspace.When you select a .java or .html file in the System Navigator, the Structure pane displays the elements of the file in a tree format. For example, when you select a .javasource file, the classes, interfaces, methods, and variables are displayed.To edit source code, double-click the file in the navigation list to display the contents in the appropriate editor. The Structure pane can be used to quickly locate specific areas of code in your Java source files and browse the class hierarchy.When you are working with the visual designer, the Structure pane displays the components of your user interface and their associated event handling methods in a hierarchical tree format.Note: The italic font is used to indicate the file names that have not been saved yet.

Page 188: Java Programming

Oracle10g: Java Programming 6-8

6-8 Copyright © 2004, Oracle. All rights reserved.

Creating JDeveloper Items

• JDeveloper items areinvoked by selecting File > New.

• They are categorized by type:– General– Business Tier– Client Tier– Database Tier– Web Tier

• Create any JDeveloper element.

New ElementsYou can create any JDeveloper item from this window. The context for creating the item must be correct. You must have the correct element selected in the Category column to create the appropriate Item.All J2SE libraries, used during development, must be available in the run-time environment.While creating the workspace, you can define the paths used for the files stored. All the files are stored using the following convention:

workspace\project\package

Use the Filter By drop-down list to view specific types of elements.

Page 189: Java Programming

Oracle10g: Java Programming 6-9

6-9 Copyright © 2004, Oracle. All rights reserved.

Creating an Application Workspace

In the General category, select Application Workspace to invoke the Property pane.

Creating an Application WorkspaceThe aim in this lesson is to create a simple Java application. The first step is to create a new application workspace that acts as a container for all the files in the application. The properties to be completed include:Application Name Enter a name for the application. This name is used to categorize all the files in your application.Directory Name Enter a top-level directory for the application or click Browse to locate one. This is where all your application files are stored during development.Application Package Prefix Enter a prefix for all packages associated with this application. The prefix you assign defines the root package for every project in the application. Application Template Select a template for the application. Click Manage Templates to edit an existing template or to create a new one. An application template provides a way to partition the application into projects that reflect a logical separation of the overall work. Each template provides a different structure to how the files are organized. For this course, use the Java Application [Java, Swing] template.

Page 190: Java Programming

Oracle10g: Java Programming 6-10

6-10 Copyright © 2004, Oracle. All rights reserved.

Specifying Project Details

Project Properties: Specifying Project DetailsA variety of project properties can be created and modified. The properties are categorized and are accessible from the nodes on the left side of the pane.The package name is the default for the project, so any Java source created in the project is automatically put in the specific package, because the package keyword is added to the source file with the name specified.Note: The output directory is added as the first path in the –classpath parameter for applications at compile and run time. In addition, together with this output directory, the libraries selected in the next screen of the wizard form the CLASSPATH for the code in this project.In particular, also note that the package name is implicitly appended to the project source and output directories as the target directories for the saved source (.java) files and for the compiled (.class) files respectively.

Page 191: Java Programming

Oracle10g: Java Programming 6-11

6-11 Copyright © 2004, Oracle. All rights reserved.

Selecting Additional Libraries

Project Properties: Selecting LibrariesIn the Libraries Property, select the version of the J2SE you will be using. You can add any existing libraries and create and add new ones.The libraries listed here are delivered by Oracle, Sun Microsystems, or third-party packages and classes. Typically, they are delivered as classes in a .jar file. Use the existing ones, or add your own.Note: All the selected libraries become part of the project application CLASSPATH in addition to the classes compiled into the project output directory. All the classes in the libraries and output directory will need to be deployed with the application.

Page 192: Java Programming

Oracle10g: Java Programming 6-12

6-12 Copyright © 2004, Oracle. All rights reserved.

Adding a New J2SE

New J2SE definitions include:• Java executable• A classpath• A source path • A doc path

Defining a New J2SE in JDeveloperJDeveloper uses J2SE definitions to describe the installed development kit, or run-time library. Every JDeveloper project is assigned a specific J2EE version, and each project has access to any of the defined J2EE versions. Each project then uses this definition to determine what version of the Java API to use, to compile and run your code.Each J2EE definition includes:

• Java executable used to launch programs• A classpath containing the classes available in the J2SE environment• A source path housing the source files for the J2SE classes• A document path storing the Javadoc files for the J2SE classes

Library TypesA J2SE library can be defined and used as one of the three types:

• System: New system libraries will reside with the predefined system libraries, available to all users of an installation of JDeveloper.

• User: These libraries reside in the user home for a particular user, and only the current user has access to their definitions.

• Project: These libraries are associated with a specific project, and are available to anyone using that project, but only when using that project.

Page 193: Java Programming

Oracle10g: Java Programming 6-13

6-13 Copyright © 2004, Oracle. All rights reserved.

Looking at the Directory Structure

JDeveloper creates and stores .java and .class files by using the following convention:• <ORACLE_HOME>\jdev\mywork

• Followed by the workspacename

• Followed by the project name– \classes\<package name>\– \src\<package_name>\

• Followed by class and src files

Storing Files in JDeveloperWhen installing JDeveloper, the installer creates an ORACLE_HOME directory for the JDeveloper product files. A subdirectory for all the JDeveloper executables and support code is stored in the \jdev\ directory. One of the directories under \jdev\ is \mywork\, which is used to store the files you create in JDeveloper. Each workspace has its own directory, and below it a directory for each project. The name of the project directory is dependent on the type of application workspace you create. For Web development, two projects are created—one for the Model and the other for the View. For a Java\Swing application a single project is created named Client. Each Java file you create is stored in a \src\<package_name>\ directory under the project it was created in. All the compiled files are stored in the \classes\<package_name>\directory. However, you can create your workspace and project directories anywhere in the file system.

Page 194: Java Programming

Oracle10g: Java Programming 6-14

6-14 Copyright © 2004, Oracle. All rights reserved.

Exploring the Skeleton Java Application

Contains application and frame classes

What Files Does the Java Skeleton Application Contain?To summarize the last few pages, following is a list of the three files that have been generated by JDeveloper so far:

• An <application>.java file containing the application class, which is the top-level class in the application. The application class contains the main() method for the program. When the application is executed, Java calls this main() method as the starting point for the whole application.

• A <frame>.java file containing the frame class that specifies the appearance and the behavior of the GUI window in the application

• A <frame_AboutBoxPanel>.java file for the Help/About frame

Instructor NoteDemonstrationTo better show the students some of the other functionalities, do a quick modeling demonstration. After creating a DB connection, you create a new project, right-click and select New > UML Diagram. After you have created it (empty page), scroll into your DB connection and drag the Employees table to the empty page. Then, it writes your UML for you.

Page 195: Java Programming

Oracle10g: Java Programming 6-15

6-15 Copyright © 2004, Oracle. All rights reserved.

Finding Methods and Fields

Find methods and fields by using the Structure pane.

Using the Structure Pane to Navigate Source CodeAs projects evolve, classes can become quite large, containing several methods and fields. To help you find your way around complex classes, JDeveloper provides the Structure pane, which is the bottom pane in the System Navigator.The Structure pane lists all the methods and fields for the currently selected class. If you double-click an item in the Structure pane, JDeveloper takes you to the definition of that item in the source code, displaying and highlighting it in the Code Editor. For example, if you double-click the helpAbout_ActionPerformed entry in the Structure pane, the start of the helpAbout_ActionPerformed method is highlighted in the Code Editor.You can also search the Navigator and Structure pane components for strings by using a [letter]. The search is a hierarchical search based on the first letter of each component. As you type in subsequent letters, the structure list highlights the first component that begins with that set of letters. If there is more than one occurrence, use the up and down arrow keys to scroll through the result set.

Page 196: Java Programming

Oracle10g: Java Programming 6-16

6-16 Copyright © 2004, Oracle. All rights reserved.

Supporting Code Development with Profiler and Code Coach

• Improve code quality with Code Coach.• Evaluate execution stack with Execution Sample

profiler.• Examine heap memory usage with Memory

profiler.• Analyze event occurrence and duration with Event

profiler for:– JVM events– Business Components for Java events– Custom events

Code CoachCode Coach creates more efficient Java programs by helping you write higher quality, better performing code. You run Code Coach on a class, which returns advice on how to make your code better.

ProfilersProfilers gather statistics on your program, which enables you to more easily diagnose performance issues.With Profilers, you can examine and analyze your data.

Code EditorWhen you pause momentarily while typing in Code Editor, JDeveloper automatically scans your code to look for syntax errors. If there are any, you will see them represented in the Structure pane or in the Log window.

Code InsightIf you pause after typing a “.” (period), JDeveloper invokes Code Insight. Code Insight displays valid methods and members from which you can select. JDeveloper also provides Code Insight for parameters when you pause after typing “(” (left parenthesis).

Instructor Note You may want to encourage students to explore these features. JVM is required to use the Code Coach and Profiler features. To use a custom J2SE version (other than the one provided by JDeveloper), they can follow the installation guide provided by JDeveloper on how to install the OJVM on the custom J2SE.

Page 197: Java Programming

Oracle10g: Java Programming 6-17

6-17 Copyright © 2004, Oracle. All rights reserved.

Customizing JDeveloper

Customize the IDE• Look and feel• General environment• Dockable windows• Component Palette• Load preset keymaps

Rename classes and packages by using refactoring.

JDeveloper Coding FeaturesCustomizing the IDEYou can customize JDeveloper’s default display options (such as, whether or not the splash screen is displayed at start up, or whether dockable windows are always on top), as well as other general behavior (such as, whether JDeveloper will automatically reload externally modified files and whether output to the Log window is automatically saved to a file).

• Customize the general environment for the IDE. • Customize dockable windows for the IDE. • Customize the Component Palette. • Load preset keymaps and customize individual accelerators. (You can take advantage

of the several existing keymap sets in JDeveloper or begin with an existing keymap and then customize it to suit your own coding style by changing which keyboard shortcuts, or accelerators, map to which actions.)

• Customize options for the Code Editor.• Add external tools to JDeveloper.

RefactoringRefactoring is the process of improving an application by reorganizing its internal structure without changing its external behavior. When you refactor an application, you may want to move or rename individual classes, or move groups of classes to a different package. In JDeveloper, you can make these changes without breaking any dependent files on which your project relies, as these files are automatically updated for you.

Page 198: Java Programming

Oracle10g: Java Programming 6-18

6-18 Copyright © 2004, Oracle. All rights reserved.

Using the Help System

Using the Help SystemJDeveloper is a comprehensive development tool and provides many features that help you develop Java code quickly and effectively.The JDeveloper Help SystemTo make the best use of the tools, the libraries, and the Java language itself, JDeveloper provides a comprehensive Help system that covers all aspects of Java development.Select Help > Help Topics in the main menu to launch the Help system:

• From the browser, select one of the topics from the contents hierarchy at the left of the window. After you select a topic, the topic expands to display subtopics.

• Select the topic you are interested in and right-click it, to display the Help text in a window.

• Use hypertext links to navigate within a topic or to related topics.

Instructor NoteAt this time, you may want to show a demonstration of the javadoc and explain how to use it. A demonstration should be the best way to explain how to use the javadoc.

Page 199: Java Programming

Oracle10g: Java Programming 6-19

6-19 Copyright © 2004, Oracle. All rights reserved.

Obtaining Help on a Topic

Use [F1] to invoke context-specific Help.

Obtaining Help on a TopicPressing the [F1] key invokes a context-sensitive Help topic window.

JavadocJavadoc is a tool that parses the declarations and documentation comments in a set of source files and produces a set of HTML pages describing the classes, inner classes, interfaces, constructors, methods, and fields. When working in the Java Code Editor, you can quickly access the specific Javadoc entry for any element in the source file. To browse the specific Javadoc entry for a given class, member, or method: Select the appropriate code element, right-click, and choose Quick Javadoc. A pop-up window with Javadoc for just that element now appears.

Page 200: Java Programming

Oracle10g: Java Programming 6-20

6-20 Copyright © 2004, Oracle. All rights reserved.

Oracle JDeveloper 10g Debugger

• Helps find and fix program errors:– Run-time errors– Logic errors

• Allows control of execution• Allows examination of variables

DebuggingDebugging is the process of looking for program errors that keep your program from doing what you intended. There are two basic types of program errors: run-time errors and logic errors. Remember that the compiler catches any syntax problems.If your program successfully compiles but gives run-time exceptions or hangs, then you have a run-time error. That is, your program contains valid statements but is encountering errors when they are executed. For example, you may be trying to open a file that does not exist or you may be trying to divide by zero.Logic errors are errors in the design and implementation of your program. That is, your program statements are valid and do something, but the results are not what you intended. These types of errors are usually the most difficult to find.The debugger enables you to control the execution of your program. It provides the ability to execute parts of the code step-by-step. You can also set breakpoints that pause the program execution when it reaches the line of code you want to examine.While the program is paused, you can inspect and even modify program variables. This helps you examine loops and other control structures to make sure that what is happening is what you intended.

Page 201: Java Programming

Oracle10g: Java Programming 6-21

Debugging (continued)BreakpointsBreakpoints are a convenient way of tracing the cause of a problem in a program. When the debugger encounters a breakpoint, it pauses the program execution. You can resume execution, stepping through the code line-by-line, examining variables and conditions, or stop the program. You can set as many breakpoints as you want.

Page 202: Java Programming

Oracle10g: Java Programming 6-22

6-22 Copyright © 2004, Oracle. All rights reserved.

Setting Breakpoints

Setting breakpoints:• Manage multiple breakpoints• Manage conditional breakpoints• Define columns displayed in window

– Description– Type– Status, and so on

• Control scope of action – Global > Workspace > Project

BreakpointsSetting BreakpointsSet a breakpoint by selecting a line of code in the source code window, right-click and select Toggle Breakpoint. You can click in the left margin to set a new breakpoint. After you start debugging, breakpoints that are known to be valid will have a check mark in the breakpoint icon. A breakpoint without a check mark may mean that this line does not represent code where the debugger can stop, but it may just mean that the debugger does not know yet whether the breakpoint is valid or invalid.Viewing BreakpointsTo view all the currently enabled breakpoints, select View > Breakpoints from the menu bar. A window showing all the breakpoints set in the program appears. To disable or remove a breakpoint, right-click the breakpoint, and select an action from the menu.Conditional BreakpointsTo set the conditions on which you want a breakpoint to be activated, right-click a breakpoint, and select Edit Breakpoint. In the Breakpoint Conditions tab, you can specify information about how and when the breakpoint is activated including valid Java conditional statements and thread-specific conditions.

Page 203: Java Programming

Oracle10g: Java Programming 6-23

Breakpoints (continued)Display SettingsTo select which columns are displayed in the breakpoints window, right-click in the breakpoints window and select Settings. In the dialog box, select Debugger > Breakpoints in the navigator tree on the left, and select the columns to display.Scope SettingsTo select the scope for the debugging, right-click in the breakpoints window, select Change Scope, and select the appropriate value.

Page 204: Java Programming

Oracle10g: Java Programming 6-24

6-24 Copyright © 2004, Oracle. All rights reserved.

Using the Debugger Windows

View Debug information:• Classes: Displays list of loaded classes and status• Watch: Evaluates and displays expressions• Monitors: Displays information about active

monitors• Threads: Displays the names and statuses of all

threads• Smart Data: Analyzes source code near execution

point• … and more

Debugging a Java ApplicationMake sure that the project is selected, and click the Debug icon. Alternatively, from the Menu bar you can select Debug > Debug <Project Name>.jpr. This causes any files to be compiled if necessary and then starts your program in debug mode.Debugging WindowsAs soon as you start the debugger, three tabs are added to a new window at the bottom right side of JDeveloper: the Smart Data tab, the Data tab, and the Watch tab. A new tab is added to the existing message window. This tab enables you to monitor the code as it executes. Fields for each window can be modified in the Tools > Preferences menu, in the Debugger node.

• Smart Data tab: Displays only the data that appears to be relevant to the source code you are stepping through

• Data tab: Displays all the arguments, local variables, and static fields for the current method

• Watch tab: Displays the current value of an expression that you have flagged to be displayed during the execution of the program

Remote DebuggingYou may manually launch the program you want to debug, then start the debugger. In the Host list, select the name of the machine where the program has been started. After the debugger is attached to the running program, remote debugging is similar to local debugging.

Page 205: Java Programming

Oracle10g: Java Programming 6-25

6-25 Copyright © 2004, Oracle. All rights reserved.

Stepping Through a Program

Step through a program by using the buttons on the Debugger toolbar:• Start the debugger.• Resume the program.• Step over a method call.• Step into a method call.• Step out of a method call.• Step to the end of the method.• Pause execution.• Stop the debugger.

Step Through a Program• Start the debugger: Executes the program in debug mode. The program will be

paused when it encounters a breakpoint. If no breakpoints have been set, you can pause program by using the “Pause execution” button.

• Resume the program: Resumes the program after stopping at a breakpoint• Step over a method call: Executes the method at the current position in the program

at full speed rather than tracing into the method line-by-line• Step into a method call: Traces into a method line-by-line. This is useful when you

suspect that the method may be the one that is causing the problem.• Step out of a method call: Enables you to step out of the current method and return

to the next instruction of the calling method• Step to the end of the method: Jumps to the end of the method• Pause execution: Pauses a running program at its current position• Stop the debugger: Stops the execution of a running program. This is a useful way of

killing the program.

Page 206: Java Programming

Oracle10g: Java Programming 6-26

6-26 Copyright © 2004, Oracle. All rights reserved.

Watching Data and Variables

• The Smart Data tab displays analyzed variables and fields.

• The Data tab displays arguments, local variables, and static fields from the current context.

• To watch other variables:– Select a variable in the source window and right-

click.– Select Watch... at Cursor from the context menu.– View the variable in the Watch tab.– Right-click a data item to modify it.

Watching Data and VariablesViewing Analyzed Data in the Smart Data TabThe debugger analyzes the source code near the execution point looking for variables and fields expressions that are used in the lines of code. By default, the debugger analyzes only one line of code for each location. Viewing Local Variables in the Data TabThe Data tab is the lower window that is displayed when you select the Debug tab at the bottom of System Navigator. The Data tab automatically displays a list of local variables, static fields and arguments that are in scope. As you jump from one method to the next, the list of variables displayed in the Data tab changes.Selecting Other Variables and Expressions to WatchOther variables and expressions can be viewed by following the steps described in the slide. Select a variable or expression such as age+10. Right-click the variable or expression and select “Watch… at Cursor” from the context menu. A dialog box appears displaying the selected variable or expression; click OK to accept it and add it to the Watch tabbed page. View the variables you have selected to monitor in the Watch tabbed page. To modify a data value, right-click it and select Modify Value from the context menu.

Page 207: Java Programming

Oracle10g: Java Programming 6-27

6-27 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how:• JDeveloper builds, debugs, and runs all types of

Java applications• JDeveloper can be used to develop:

– Java applications– Java servlets– JSPs– EJBs

• JDeveloper can be used to build enterprise applications

Additional ReadingYou can find out more about the features of JDeveloper on the Oracle Technology Network, http://otn.oracle.com. The following are some examples of the topics covered:OverviewOverview of JDeveloper, The JDev IDE, Creating a BC4J Application, Java Concepts in JDeveloper, Naming Conventions, Debugging the Code, Deployment AlternativesADF Application Development FrameworkReduces the Complexity of J2EE Development by providing Visual and Declarative Development, Increases Development Productivity, Encourages J2EE Best Practices by Implementing Standard J2EE Design Patterns–MVC, Provides a Flexible and Extensible Environment by allowing Multiple Technology Choices and Development StylesJSPsJSP Overview, Creating JSPs, JSP ComponentsAdvanced TopicsHTML in JDev Environment, JavaScript in JDev Environment, Customizing & Extending the IDE, Overview of the Class Modeler, Overview of the Activity Modeler, Security

Page 208: Java Programming

Oracle10g: Java Programming 6-28

6-28 Copyright © 2004, Oracle. All rights reserved.

Practice 6: Overview

This practice covers:• Exploring the Oracle JDeveloper 10g IDE• Creating a workspace and project• Including application files from the earlier lesson

Practice 6: OverviewNote: In this practice, you use the E:\labs\les06 directory.The practices in lessons 3, 4, and 5 are written to help you better understand the syntax and structure of the Java language. Their sole purpose is to instruct and is not intended to reflect any set of application development best practices.The purpose of the practices from lesson 6 to the end of the course is different. Starting in lesson 6, you use JDeveloper to build an application employing techniques you will use during real-world development. The practices continue to support the technical material presented in the lesson, while incorporating some best practices you will use while developing a Java application.In the Applications – Navigator node, expand the OrderEntryWorkspaceLes<nn> – OrderEntryProjectLes<nn> - Application Sources – oe, and double-click the UML Class Diagram1 entry. This diagram displays all the classes created to this point in the course.

Page 209: Java Programming

Oracle10g: Java Programming 6-29

Practice 6: Building Java by Using Oracle JDeveloper 10gGoalIn this practice, you explore using the Oracle JDeveloper 10g IDE to create a workspace and a project, so that you manage your Java files more easily during the development process. You practice how to use the rapid code generation features, such as the text Code Editor and debugger. You practice how to create one or more Java applications and classes by using the rapid code generation features, such as the text Code Editor and debugger.More importantly, you now start using JDeveloper for most of the remaining lab work for this course (occasionally returning to the command line for various tasks). By the end of the course, you will have built and deployed the course GUI application while continuing to develop your Java and JDeveloper skills.Note: In this practice, you use the files found in the E:\labs\les06 directory. They are similar to the ones you created in earlier practices, with subtle differences and the introduction of a class to manage the data, named DataMan. This file will be used in later labs.Your Assignment

• In part 1, you explore JDeveloper default rapid code generation features by creating a new default workspace using the default JDeveloper paths, and then create a default project from an existing code in the E:\labs\les06 directory.

• In the extra credit section, you run and test the application using the debugger.Create a Workspace and ProjectLaunch Oracle JDeveloper 10g from the desktop icon provided, or ask your instructor for instructions on how to start JDeveloper. In this practice, you must use the E:\labs\les06 directory.

1. Create a new Workspace and a new Project.a. Select File > New to invoke the JDeveloper New Gallery window. This a

launching point for creating all your Java source code. The New Gallery window is divided into two columns, Categories and Items. The list of items available depend on the category selected.

b. The General category is selected by default the first time “New” is selected. If it is not highlighted, select it now. Then, either double-click the Workspace item (or click Workspace and then click the OK button).

c. Change the workspace directory name field to E:\labs\les06.You can use the Browse button to locate the directory, if desired.

d. Enter the following workspace file name: OrderEntryWorkspace.jwse ote lear the Add New Empty Project checkbox lick the button and saveyour workspace

2. Create a new project called OrderEntryProject.jpr in the new workspace, and populate the project with files existing in E:\labs\les06\src\oe directory

a. Right-click the OrderEntryWorkspace.jws workspace, and select the New Project… menu item. Then double-click the Project from Existing Source entry in the items of the New Gallery window.

Page 210: Java Programming

Oracle10g: Java Programming 6-30

Practice 6: Building Java by Using Oracle JDeveloper 10g (continued)b. Click the Next button on the Welcome screen. In Project with

Existing Source Wizard – Location, change theroject ame to OrderEntryProject andselect the E:\labs\les06 directory Then, click the Next button.

c. In “Project with Existing Source Wizard - Add Source Files and Directories”, click the Add button. Navigate to the subdirectory containing the Java source files, which are in the src\oesubdirectory of the E:\labs\les06 directory tree.

d. Select all the .java files in the E:\labs\les06\src\oedirectory and click the Open buttonhe wi ard displays the selectedfiles under the Refine Files to Be Added listlick the Next button

e n Project with Existing Source Wizard - Source Paths, confirm the Output Directory is E:\labs\les06\classes, and leave the HTML Root field empty. Then click the Next button.

f. In Project with Existing Source Wizard - Run Settings, select the file OrderEntry.java, under the E:\labs\les06\src\oedirectory as the “Main Entry Point.” Then click the Next button.

g n Project with Existing Source Wizard – Finish, click the Finish button

h ouble click the OrderEntryProject and

select the nput ath node et theefault ackage to oe

i ave all your work hen compile thefiles in the project ight clickOrderEntryProject, and select the Rebuild Projectmenu option r use the Project > RebuildOrderEntryProject.jprmenu item ay

attention to the compilationprogress in the Log window.

j elect the Run > Run OrderEntryProject.jpr menu

item to run the defaultapplication or right click theOrderEntry.java file and select Run OrderEntry.java from the context menu

iew the output results of yourapplication in the Log window

Optional Extra CreditDebugging the Course ApplicationIn this part of the practice, you run the application in debug mode, and examine how the debugger works.

3. Run the OrderEntry application in debug mode.a. Open Order.java file in the Code Editor by double-clicking the file name, or

right-clicking the file name and choosing Code Editor from the context menu.b. Remove the comments lines from the System.out.println, and set

breakpoints on the following two statements:item1Total = item1.getItemTotal();...

Page 211: Java Programming

Oracle10g: Java Programming 6-31

Practice 6: Building Java by Using Oracle JDeveloper 10g (continued)c. In the Navigator, select the OrderEntry.java file, right-click and select

Debug from the context menu.JDeveloper creates a new debugger tabbed page that opens at the bottom right of the JDeveloper window. The execution of the code stops at your first breakpoint, as indicated by a red arrow. The red arrow indicates the next line that is about to be executed when you resume debugging.The Log/Debug window is modified to contain two tabs—a Log tab and a Breakpoints tab— in which you can view all the breakpoints you have set. The Log tab must display the output results generated by the application. Resize the windows, if required.

d. Visually select the Smart Data tab in the bottom right window, known as the Debug window.Note: If the Debug window is not visible, display it by selecting the View > Debug Windows > Smart Data menu item. The check box next to the Data item must be selected to make it visible; otherwise, the tab will be removed from the Debug window displayed.

e. Locate the item1 variable in the Smart Data tabbed page and expand it. Using the values of quantity and unitPrice, calculate the item1Total of the order. What is its present value of item1Total?(Hint: The value for quantity was displayed as 2 and the value for unitPrice was displayed as 2.95.) But the value item1Total was showing “out of scope” in the Smart Data window

f. Select the Debug > Step Over menu item (alternatively, press [F8] or click the appropriate toolbar icon) to calculate the item1Total. Note the changes to the item1Total instance variable in the Smart Data tabbed page of the Debug window. Was your calculation in the previous step correct?

g. In the top toolbar, press the Resume [F9] button (or select the Debug > Resumemenu item). The red arrow in the Code Editor advances and highlights the line with the next breakpoint detected in the code execution sequence.

h. Continue by selecting the Debug|Resume menu (F9 key, or click the toolbar button) until the program is completed. You need to click it only once.

i. Remove the breakpoints from the Order.java source by clicking each breakpoint entry (red dot) in the margin for each line with a breakpoint.

Page 212: Java Programming
Page 213: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Creating Classes and Objects

Schedule: Timing Topic70 minutes Lecture25 minutes Practice95 minutes Total

Page 214: Java Programming

Oracle10g: Java Programming 7-2

7-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Define instance variables and methods• Define the no-arg (default) constructor method• Instantiate classes and call instance methods• Perform encapsulation by using packages to

group related classes• Control access with public and private access

modifiers• Use class variables and methods

Lesson AimThis lesson shows you how to create a new class definition using Oracle JDeveloper.You define instance variables and methods for the class. The lesson also shows how to create objects using new, basic object initialization and how to manipulate the objects using instance methods.

Page 215: Java Programming

Oracle10g: Java Programming 7-3

Lesson Aim (continued)Class DefinitionsJava is an object-oriented programming language. All the data or attributes and behavior of objects are defined within classes. You use classes for everything you do in Java.CodeObject orientation is about modeling real-world objects or concepts in software. Java forces you to think in an object-oriented way, because every piece of Java code must live in a class definition. There are no global functions defined outside the scope of a class.DataJava uses variables to store information about an object. The variables can store primitive values or references to other objects. Variables also are defined only within classes.PackagesPackages group logically related classes by application and provide access control. Java uses packages to control which classes can be seen and accessed by classes outside of the package.

Page 216: Java Programming

Oracle10g: Java Programming 7-4

7-4 Copyright © 2004, Oracle. All rights reserved.

Using Java Classes

Packages

Methods Objects

Objectreferences

Attributes

Contained in a class

What Is a Class?A class is a template or blueprint that is used in creating multiple objects. A class encapsulates all the data and behaviors that make up an object. When you ask Java to create or instantiate a class, Java uses the class definition as a template for building the new object.A class contains attributes that are assigned to all new objects of that class. Attributes are the information or data that describe, classify, categorize, or quantify an object. Each object of a given class has its own set of the class attributes. For example, an object of the Customer class may have a name, a billing address, and a telephone number attribute.Data that is stored in an object can be primitive data types, such as integers or characters, or references to objects.A class also contains methods, or functions, that specify the behavior or actions that an object can perform. For example, a customer may rent a video, make a payment, or change his or her billing address.Java uses packages to group classes that are logically related. Packages consist of all the classes in a subdirectory. They are also used to control access from programs outside of the package.

Page 217: Java Programming

Oracle10g: Java Programming 7-5

7-5 Copyright © 2004, Oracle. All rights reserved.

title: “Gone with…”rating: “PG”

title: “Last Action…”rating: “PG-13”

Comparing Classes and Objects

• An object is an instance of a class.

• Objects have their own memory.

• Class definitions must be loaded to create instances.

public void displayDetails()

private String title;

private String rating;

public void setRating()

Movie

mov1 mov2

Classes and ObjectsA class is a template for building objects of that class. In object-oriented terminology, an object is an instance of a class. Each object of that class has the same data structure and operations. However, the values that are held in this data structure are unique to each object; these values are therefore called instance variables. The operations of an object act on the instance variables in that object.The class contains variables and methods called members. Those members owned by the class are “static members” and those owned by the objects from the class are called “instance members”In the case of the Movie class, each individual movie is an instance of Movie. “Gone with the Wind” is one distinct instance of Movie while “Last Action Hero” is another. Each has its own set of variables that are separate and distinct from the variables of any other movie, or object, of the Movie class.Each new object is identified within Java by a unique object reference. Java distinguishes between objects by using this reference. Objects are uniquely identifiable even if all their properties are the same.

Page 218: Java Programming

Oracle10g: Java Programming 7-6

7-6 Copyright © 2004, Oracle. All rights reserved.

Creating Objects

• Objects are typically created by using the new operator:

• For example, to create two Movie objects:

Movie mov1 = new Movie("Gone ...");

Movie mov2 = new Movie("Last ...");

ClassName objectRef = new ClassName();

title: “Gone with…”rating: “PG”

title: “Last Action…”rating: “PG-13”

Creating New ObjectsIn Java, you can create objects by using the new operator. The new operator creates an instance of a class and returns the reference of the new object. For example:

Movie mov1 = new Movie();

This statement creates an instance variable of the Movie type named mov1. It then creates a new instance of Movie by using the new operator and assigns the object reference to the mov1 instance variable. It is important to remember that the new operator returns a reference to the new object that points to the location of that object in memory.

Page 219: Java Programming

Oracle10g: Java Programming 7-7

7-7 Copyright © 2004, Oracle. All rights reserved.

Using the new Operator

The new operator performs the following actions:• Allocates and initializes memory for the new

object• Calls a special initialization method in the class,

called a constructor• Returns a reference to the new object

Movie mov1 = new Movie("Gone with…");

mov1(When instantiated)

title: “Gone with…”rating: “PG”

Anatomy of the new OperatorThe new operator performs the following three tasks:

• Allocating memory for the new object. It knows how much memory is required by looking in the class definition to see what instance variables are defined in the class.

• Calling a constructor to initialize the instance variables in the new object. A constructor is a special method that is supplied by the class.

• Returning a reference to the newly created object. To refer to this object in the future, you must store this reference in a variable.

Separating Variable Declaration from Object CreationThe declaration of an object reference and the creation of an object are completely independent. In the previous examples, these two parts were combined in a single statement:

Movie mov1 = new Movie();

However, you can achieve the same effect with two separate statements, as follows:Movie mov1; // Declare an object reference,

// capable of referring to a Movie. mov1 = new Movie(); // Create Movie object, and return the

// reference to the mov1 variable.

Page 220: Java Programming

Oracle10g: Java Programming 7-8

7-8 Copyright © 2004, Oracle. All rights reserved.

Comparing Primitives and Objects

Primitive variables hold a value.

int i;

int j = 3; Movie mov1 = new Movie();

Object variableshold references.

title: nullrating: null

mov1

Movie mov1;

mov10

3

i

j

null

Primitive Variables and Object VariablesPrimitive variables are treated very differently from object variables in Java. It is important to understand what are the differences.Primitive VariablesWhen you declare a primitive variable, Java allocates a chunk of memory to hold a variable of the specified primitive type. If you define a primitive variable as an instance or a class variable, then the variable is initialized to 0 if it is a number, false if it is a Boolean, or ‘\0’ if it is a char.Primitive variables hold their values directly—for example, if you declare an int variable and assign it the value 3, then the value is stored directly in the four bytes of the int.Object VariablesWhen you declare an object variable, you also receive a chunk of memory, but this memory is only large enough to hold a reference to an object. You may find it useful to think of a reference as a “pointer” to an object.As mentioned previously, declaring an object variable does not create an object of the specified class. Consequently, an object instance variable is initialized to null to indicate that it does not yet refer to any object. Use the assignment operator to make an object variable refer to an object. The assignment can be to an existing object or a new object by using the new operator.

Page 221: Java Programming

Oracle10g: Java Programming 7-9

7-9 Copyright © 2004, Oracle. All rights reserved.

Using the null Reference

• A special null value may be assigned to an object reference, but not to a primitive.

• You can compare object references to null. • You can remove the association to an object by

setting the object reference to null.

Movie mov1; //Declare object reference

if (mov1 == null) //Ref not initialized?

mov1 = new Movie(); //Create a Movie object

mov1 = null; //Forget the Movie object

More About nullConsider the following statement:

Movie mov1 = null;This declares a variable called mov1 with a special reference called null. This indicates that the reference does not refer to a real object yet.Checking Object References Against nullnull is a keyword in the Java language. You can use it with the equality operator to check whether an object reference has been initialized or not:

if (mov1 == null) {// The mov1 variable has not been initialized, // so do something to initialize it …

}

Discarding an ObjectWhen you have finished using an object, you can set its object reference to null. This indicates that the variable no longer refers to the object. When there are no more live references to an object, the object will be marked for garbage collection.The Java Virtual Machine (JVM) automatically decrements the number of active references to an object whenever an object is dereferenced, goes out of scope, or the stored reference is replaced by another reference.

Page 222: Java Programming

Oracle10g: Java Programming 7-10

7-10 Copyright © 2004, Oracle. All rights reserved.

Assigning References

Assigning one reference to another results in two references to the same object:

Movie mov1 = new Movie("Gone...");

mov1

Movie mov2 = mov1;

mov2

title: “Gone with…”rating: “PG”

Different Object References Can Refer to the Same ObjectAs previously mentioned, when you declare an object reference variable, it is initialized to null. Before you can use that variable, you must initialize it; typically, you initialize it with a reference to a new object by using the following syntax:

Movie mov1 = new Movie();However, it is also possible to initialize an object reference to an existing object as follows:

Movie mov2 = mov1;This is perfectly legal Java syntax, but there is still only one Movie object. When you assign one object reference to another object reference, you end up with two references to the same object, not a copy of the other object.The Object Can Be Accessed Through Either ReferenceYou can access the same object through either reference; however, there is still only one object.You can change either reference to refer to a different object without affecting the other reference. However, if you really need a separate object, rather than multiple references to a single object, then you must create a new object.

Instructor Noteif (mov1 == mov2) returns true because both of them address the same memory space.

Page 223: Java Programming

Oracle10g: Java Programming 7-11

7-11 Copyright © 2004, Oracle. All rights reserved.

title: nullrating: null

title: nullrating: null

Declaring Instance Variables

Instance variables are declared within the class, but outside the methods or instance or static intializers.

public class Movie {

public String title;

public String rating;

public float getPrice(){

return price;

}

}

Movie mov1 = new Movie();

Movie mov2 = new Movie();

mov2

mov1

Create movies:

Declaring Instance VariablesInstance variables must be declared within the class definition. In this example, these instance variables have been declared as public to allow users of the class to access them directly. Although this is not a good practice, it is done here to keep the example simple.Declaring instance variables as public is a violation of encapsulation; after you have seen how to write instance methods, the instance variables will be made private to prevent them from being manipulated directly by users of the class.What Does an Object Look Like?The example creates two instances of the Movie class. To put it in another way, two Movie objects have been created: the first Movie object is referenced by mov1, and the second Movie object is referenced by mov2.Although these two Movie objects are completely independent, they have an identical datastructure. In other words, each object has its own separate and distinct copies of the instance variables that you declared in the Movie class.

Page 224: Java Programming

Oracle10g: Java Programming 7-12

7-12 Copyright © 2004, Oracle. All rights reserved.

Accessing public Instance Variables

public instance variables can be accessed by usingthe dot operator:

public class Movie {

public String title;

public String rating;

}Movie mov1 = new Movie();

mov1.title = "Gone ...";

if (mov1.title.equals("Gone ... ") )

mov1.rating = "PG";

Accessing public Instance VariablesThe example shows how to access public instance variables in an object using the dotoperator. This operator takes an object reference on the left and the name of an instance variable on the right:

objectRef.instanceVarName

Remember that this syntax is allowed only if the instance variable has been declared as public. In a fully encapsulated object, where the instance variables are private, the only way to change the state of an object is by calling a suitable instance method on the object. By exposing the variables as public, anyone using your class can manipulate instance data without validation or control.Users can set the rating to anything they want, regardless of business rules governing that data.Note: equals(...) compares object types.

Page 225: Java Programming

Oracle10g: Java Programming 7-13

7-13 Copyright © 2004, Oracle. All rights reserved.

Defining Methods

A method in Java is equivalent to a function or subroutine in other languages.

modifier returnType methodName (argumentList) {

// method body

};

MethodsWhen you define a class for an object-oriented program, you implement all of the behavior of that class in one or more methods. A Java method is equivalent to a function, procedure, or subroutine in other languages, except that it must be defined inside a class definition. In other words, there is no support for global methods in Java; every method must be defined within a class.Anatomy of an Instance MethodThe key components of an instance method are:

• A modifier, such as public or private. If you specify an instance method as public, then it can be called from anywhere in the program. If you specify a method as private, then it can be invoked only by other methods in the same class. If no modifier is specified, then the method can be invoked by any method in any class in the same package. An instance method may also have a protected or a default modifier.

• A return type. This can be a primitive type, such as int, a class type such as String, or the void keyword, if the method does not return a value.

• The name of the method. A Java naming convention expects method names to begin with a lowercase letter. Compound words in the method name must begin with an uppercase character.

• An optional argument list inside parentheses, separated by commas. If the method does not take any arguments, then simply leave the parentheses empty.

• The method body enclosed in braces

Page 226: Java Programming

Oracle10g: Java Programming 7-14

7-14 Copyright © 2004, Oracle. All rights reserved.

Calling a Method

Objects communicate by using messages:• All methods are defined within a class and are not

defined globally as in traditional languages.• When you call a method, it is always in the context

of a particular object.– myPen.write( ): Object-oriented programming– Write (myPen): Traditional structured

programming

Objects Must Associate with Each OtherObjects must associate with other objects to enable messages to be sent. To send a particular message, an object must know the recipient of the message. This visibility may be achieved dynamically and transiently, or an object can “remember” another object through a reference. (To be pedantic, two classes may associate with each other, and two objects may have a link between them.)A link is simply a relationship between objects. In programming terms, it may be implemented in various ways—for example, a variable in one object containing a reference to the other object.

Page 227: Java Programming

Oracle10g: Java Programming 7-15

7-15 Copyright © 2004, Oracle. All rights reserved.

Specifying Method Arguments: Examples

• Specify the number and type of arguments in the method definition:

• If the method takes no arguments, then leave the parentheses empty:

public void displayDetails() {

System.out.println("Title is " + title);

System.out.println("Rating is " + rating);

}

public void setRating(String newRating) {

rating = newRating;

}

Specifying Method Arguments or SignatureA method can have zero or more arguments, also known as parameters; this is called the method signature. When you define a method in a class definition, you specify its formal arguments in an argument list. Each formal argument is a placeholder for a variable of some type, either a primitive or an object reference. Like any other variable, each argument must be declared in terms of its type, such as String, and a name, such as title.Specifying Multiple ArgumentsIf a method has multiple arguments, then each declaration must be separated by commas, as in the following example:

public void setMovieDetails(String pTitle, String pRating) {title = pTitle;rating = pRating;…

}

Specifying No ArgumentsIf a method has no arguments, then simply leave the parentheses empty in the definition.

Page 228: Java Programming

Oracle10g: Java Programming 7-16

7-16 Copyright © 2004, Oracle. All rights reserved.

Returning a Value from a Method

• Use a return statement to exit a method and to return a value from a method:

• If the return type is void, then no return is needed.• You can use a return without a value to terminate

a method with a void return type.

public class Movie {private String rating;…public String getRating () {return rating

}}

Returning a Value from a MethodA method can return a single value or expression to a caller of that method. If so, then it must be defined with a return type such as int in front of the method name, as follows:

public int getLength() {…

}

Methods are also allowed to return a reference to an object; this can be useful if you want to return more than one value. Here is a method that returns a reference to a String object:

public String getRating() {…

}

The return StatementA return statement is the mechanism by which methods pass the required value back to the calling method. A return statement takes a single value or expression, which must be compatible with the return type that is specified at the beginning of the method.When a return statement is encountered, the method exits immediately, and ignores any statements that lie between the return statement and the closing brace of the method. This can be used for void methods that have no return value or to exit the function immediately:

return; // Use this syntax to return void from a method

Page 229: Java Programming

Oracle10g: Java Programming 7-17

7-17 Copyright © 2004, Oracle. All rights reserved.

Calling Instance Methods

public class Movie {

private String title, rating;

public String getRating(){

return rating;

}

public void setRating(String newRating){

rating = newRating;

}

}Movie mov1 = new Movie();

String r = mov1.getRating();

if (r.equals("G")) …Use the dotoperator:

Use the dot Operator to Call an Instance MethodAs with instance variables, you can use the dot operator to call an instance method on an object. The general syntax is as follows:

objectRef.methodName(arguments … );

If the method takes no arguments, then you still have to include the parentheses when you call the method, but you leave them empty:

objectRef.methodName(); // Call method that takes no args

ExampleIn the example, two instance methods in the Movie class are defined: getRating() and setRating(). You then create a Movie object and check its rating by using getRating():

if ( mov1.getRating.equals("G") ) …

If necessary, the movie rating can be reset by using setRating():mov1.setRating("PG");

Page 230: Java Programming

Oracle10g: Java Programming 7-18

7-18 Copyright © 2004, Oracle. All rights reserved.

Applying Encapsulation in Java

• Instance variables must be declared as private.

• Only instance methods can access private instance variables.

• private decouples the interface of the class from its internal operation.

Movie mov1 = new Movie();

String rating = mov1.getRating();

String r = mov1.rating; // error: private

...

if (rating.equals("G"))

var

aMethod

aMethod()

EncapsulationEncapsulation is a key concept in object-oriented programming. A well-defined class must decouple its public interface from its internal implementation. To achieve this, all instance variables of a class must be made private to hide them from users of the class. Only the instance methods of a class can access the private instance variables of that class.Users of the class must invoke one of the public methods of the class to access (get) or change (set) the state of an object. For example, if the Movie class is properly encapsulated, then it is impossible for a user of the Movie class to directly access instance variables such as title and rating.The Benefits of EncapsulationAs a class evolves, there is every chance that you will need to modify the way in which the class is implemented internally. However, as long as you preserve the same interface to the class, the rest of the program will not need to be modified at all. You preserve the interface by retaining the same public instance methods with exactly the same signatures or parameter lists.By maintaining this encapsulation, you will not break any existing code that uses the Movieclass.

Page 231: Java Programming

Oracle10g: Java Programming 7-19

7-19 Copyright © 2004, Oracle. All rights reserved.

Passing Primitives into Methods

When a primitive or object reference value is passed into a method, a copy of the value is generated:

public void aMethod(int arg) {

if (arg < 0 || arg > 100)

arg = 0;

System.out.println("arg: " + arg);

}

int num = 150;

anObj.aMethod(num);

System.out.println("num: " + num);

arg150

num150

Passing Primitives into a MethodWhen a primitive value is passed into a method, a copy of its value is passed into the method argument. If the method changes the value of the argument in any way, then only the local argument is affected. When the method terminates, this local argument is discarded, and the original variable in the calling method is left unchanged.ExampleThe example in the slide illustrates the way in which primitive variables are “passed by value” into methods. The code on the left declares an int variable called num and assigns it the value 150. When num is passed into aMethod(), a copy of its current value is passed into the method argument, which you have called arg; arg will be 150 initially.Inside aMethod(), arg is reset to 0. However, when aMethod() terminates, arg is discarded and you return to the calling method, where num still has the value of 150.Therefore, this example prints out the following messages:

arg: 0

num: 150

Page 232: Java Programming

Oracle10g: Java Programming 7-20

7-20 Copyright © 2004, Oracle. All rights reserved.

title: “Gone with…”rating: “PG”

Passing Object References into Methods

When an object reference is passed into a method, the object is not copied but the pointer to the object is copied:

public void aMethod(Movie ref2) {

ref2.setRating("R");

}

mov1

ref2

Movie mov1 =

new Movie("Gone…");

mov1.setRating("PG");

anObj.aMethod(mov1);

Passing Object References into MethodsWhen an object reference is passed to a method, a copy of the passed reference is generated, which refers to the original object. The reference contains the address where the object is located in memory. Any changes that the method makes to the argument will change the original object. When the method terminates, any changes that you have made to the object during the method remain in force.ExampleThe example in the slide illustrates the way in which objects are “passed by reference” into methods. The code on the left creates a new Movie object and stores a reference to it in mov1. The movie rating is then set to "PG".When mov1 is passed into aMethod(), the method receives a reference to the original Movie object. Inside aMethod(), the movie rating is changed to "R".When aMethod() terminates, the original Movie object that is referred to by mov1 has a rating of "R", not "PG".

Page 233: Java Programming

Oracle10g: Java Programming 7-21

7-21 Copyright © 2004, Oracle. All rights reserved.

What Are Class Variables?

Class variables:• Belong to a class and are common to all instances

of that class• Are declared as static in class definitionspublic class Movie {

private static double minPrice; // class var

private String title, rating; // inst vars

Movie class variable Movie objects

titlerating

titlerating

titlerating

minPrice

Class VariablesA class variable, which is also called a static variable, is a variable that belongs to a class and is common to all instances of that class. In other words, there is only one instance of a class variable, no matter how many instances of that class exist.Defining Class Variables in JavaIn Java, you declare class variables by using the static keyword. In the example, minPrice has been declared as a class variable, because the minimum price is the same for all Movie objects. Notice that minPrice has been declared private, because it must be be accessed only by methods of the Movie class.In this example, the minPrice is the same for all movies, regardless of title or rating.

Page 234: Java Programming

Oracle10g: Java Programming 7-22

7-22 Copyright © 2004, Oracle. All rights reserved.

Initializing Class Variables

• Class variables can be initialized at declaration.• Initialization takes place when the class is loaded.• Use a static initializer block for complex

initialization.• All class variables are initialized implicitly to

default values depending on data type.

public class Movie {

private static double minPrice = 1.29;

private String title, rating;

private int length = 0;

When Do Class Variables Get Initialized?Class variables are initialized when the class is loaded. Do not initialize class variables in a constructor; constructors are for initializing instance variables, not class variables.Default Initialization of Class VariablesClass variables have the same default values as instance variables: numbers are set to 0, boolean variables are set to false, characters are set to '\u0000', and references are set to null.Explicit Initialization of Class VariablesClass variables can be initialized with nondefault values, just like instance variables. For example, the minPrice variable in the slide has been set to 1.29.Complex Initialization of Class VariablesComplex initialization of class variables is performed in a static initialization block, or static initializer. A static initializer is not named, has no return value, and begins with the static keyword, followed by a block of code inside braces. It is similar to a constructor except that it executes only once and does not depend on any instance of the class.

public class Movie {private static double minPrice;static {

Date todaysDate = new Date();minPrice = getMinPrice(todaysDate);

}

Page 235: Java Programming

Oracle10g: Java Programming 7-23

7-23 Copyright © 2004, Oracle. All rights reserved.

What Are Class Methods?

Class methods are:• Shared by all instances • Useful for manipulating class variables• Declared as static

A class method is called by using the name of the class or an object reference.

public static void increaseMinPrice(double inc) {

minPrice += inc;

}

Movie.increaseMinPrice(.50);

mov1.increaseMinPrice(.50);

Class MethodsA class method, which is also called a static method, is a method that belongs to a class and is shared by all instances of that class. Unlike an instance method, a class method does not operate on a single object, and so it does not have a this reference. A class method can access only the class variables and class methods of its class.Why Use Class Methods?Class methods are an ideal way to access class variables. In fact, they are the only way if no instances of the class currently exist. For example, the increaseMinPrice() method in the slide changes the minimum price of all movies, currently instantiated or not.How Do You Call a Class Method?Class methods are called by using the following general syntax:

ClassName.classMethodName( … argumentList … );

You can also call class methods by using an object reference before the dot, rather than the name of the class, but the method can still access only class variables and class methods.Static MethodsYou may want to create a method that is used outside of any instance context. Declare a method to be static, which may only call other static methods directly. Static methods may not refer to their superclass or its methods.

Page 236: Java Programming

Oracle10g: Java Programming 7-24

7-24 Copyright © 2004, Oracle. All rights reserved.

Guided Practice: Class Methodsor Instance Methods

public class Movie {

private static float price = 3.50f;private String rating;…public static void setPrice(float newPrice) {

price = newPrice;}public float getRating() {

return rating;}

}

Movie.setPrice(3.98f); Movie mov1 = new Movie(…);mov1.setPrice(3.98f);float a = Movie.getRating();float b = mov1.getRating();Legal or not?

Class Methods or Instance MethodsDescribe the definition of the Movie class in the slide. Then, take a look at the test code, where a Movie object is created and various methods are called.Explain the Movie class and the code that uses it. Which statements are legal, and which are illegal? Why or why not?

Instructor Note(+) is correct and (–) is incorrect.Movie.setPrice(3.98f); // calls the class method setPrice (+)Movie mov1 = new Movie(…);// creates a new Movie object (+)mov1.setPrice(3.98f); // uses an object, mov1, but still calls // the class method (+)float a = Movie.getRating(); // illegal -- tries to call an instance // method without //specifying an object (–)float b = mov1.getRating();// calls an instance method with an

// object specified (+)The exact JDeveloper error is: “non-static method getRating() cannot be referenced from a static context”

Page 237: Java Programming

Oracle10g: Java Programming 7-25

7-25 Copyright © 2004, Oracle. All rights reserved.

Examples in Java

Examples of static methods and variables:• main()• Math.sqrt()• System.out.println()

public class MyClass {

public static void main(String[] args) {double num, root; …root = Math.sqrt(num);System.out.println("Root is " + root);

} …

main() Is a Static MethodWhen you run a Java application, the virtual machine locates and calls the main() method of that class. Even though everything in a Java program must be contained within a class, you need not create an instance of the class if main() just calls class methods. If main()accesses instance methods or variables of its own class, then it must first instantiate itself:

public class Movie {public void increaseMinPrice(double increase) { … }

public static void main(String[] args) {Movie myMovie = new Movie();myMovie.increaseMinPrice(.20);

}}

Math.sqrt() Is a Static MethodThe Math class provides class methods to compute many mathematical functions, such as trigonometric functions and logarithms. It also provides several class constants such as E(2.71828…) and PI (3.1415926…).

What Is System.out.println()?The System class provides class variables to represent the state of the entire system. System.out is a class variable that refers to a PrintStream object, which represents the standard output stream; println() is an instance method of PrintStream.

Page 238: Java Programming

Oracle10g: Java Programming 7-26

7-26 Copyright © 2004, Oracle. All rights reserved.

Creating Classes Using the Class Editor

Using JDeveloper’s Class EditorJDeveloper can help you create your classes in the Class Editor. To modify a class, select it, right-click and select Class Editor.The Fields tab allows you to add, remove and edit any fields, as well as specify their scope and type. While adding a new field, you can include the get and set methods, and they will appear in the Methods tab.The Methods tab allows for modification of methods, including the scope, type and parameters.The Events tab allows the class to fire and listen for a set of standard events, or you to create and import your own.

Page 239: Java Programming

Oracle10g: Java Programming 7-27

7-27 Copyright © 2004, Oracle. All rights reserved.

What Are Java Packages?

oe

Customer Order Util

OrderEntry OrderItem

What Is a Java Package?A package is a container of classes that are logically related, either by application or function. A package consists of all the Java classes within a directory on the file system. Package names are used within a Java run-time environment to manage the uniqueness of identifiers as well as to control access from other classes. They also help by segmenting related parts of complex applications into manageable parts.NamespaceJava Virtual Machine (JVM) uses a construct called namespace to manage identifier names within a Java program. A namespace is a chunk of memory that is allocated specifically to manage objects. Objects are placed in specific namespaces depending on the source of the code. For example, a class that is loaded from a local package is loaded into one namespace, whereas one loaded from a network source goes into another separate namespace.Identifier names must be unique within a namespace. Without the internal namespace construct, identifier names will need to be unique across all Java classes. In other words, if the J2SE or any other class that you need uses an identifier named count, your program cannot define a variable named count.Java uses namespaces to manage the identifier names so that you do not have to worry about what names are used by other classes. You have to manage uniqueness only within your program.

Page 240: Java Programming

Oracle10g: Java Programming 7-28

7-28 Copyright © 2004, Oracle. All rights reserved.

Grouping Classes in a Package

• Include the package keyword followed by the package name at the top of the Java source file. Use the dot notation to show the package path.

• If you omit the package keyword, then the compiler places the class in a default “unnamed”package.

• Use the –d flag with the javac compiler to create the package tree structure relative to the specified directory.

• Running a main() method in a packaged class requires:– That the CLASSPATH contains the directory having

the root name of the package tree– That the class name must be qualified by its

package name

Using PackagesThe package represents the organization of the Java bytecode of classes and interfaces. It is not the source code organization, which is represented by the .java files. The Java compiler reads and uses any needed packaged classes that you specify.Note: The CLASSPATH environmental variable is extremely critical when using packages. Most run-time problems with code using packages emanate from a missing directory in the CLASSPATH environment.When running the Java application, you must include the package name in the command.

c:\>java <package_name>.<class>c:\>java practice06.MaintainCustomers

If a class is included in a package, then the compiler can be requested to put the class file in a subdirectory reflecting the package name. To create the package directory names during compile time, use the –d option. For example, if you compile a class called RentItem in a package called rentals as follows:javac -d c:\acmevideo RentItem.java

then the class file that is created is called c:\acmevideo\rentals\RentItem.classThe default behavior for the javac command without the -d option is to put the class file in the same directory as the source file.

Page 241: Java Programming

Oracle10g: Java Programming 7-29

7-29 Copyright © 2004, Oracle. All rights reserved.

Setting the CLASSPATH with Packages

The CLASSPATH includes the directory containing the top level of the package tree:

Package name .class location

C:\>set CLASSPATH=E:\Curriculum\courses\java\les06CLASSPATH

Setting the CLASSPATH with PackagesThe CLASSPATH must point to the directory above the classes. For example, suppose you want the Java interpreter to be able to find classes in the package practice06. If the path to the practice06 classes directory is:E:\Curriculum\courses\java\les06\practice06

then you would set the CLASSPATH variable from an operating system prompt as follows:set CLASSPATH=E:\Curriculum\courses\java\les06

After you exit a DOS prompt, the CLASSPATH reverts to the permanent settings. The CLASSPATH is used by both the compiler and the class loader in the Interpreter (JVM) to locate, resolve references to class names, and load the classes into memory at run time. The CLASSPATH can include:

• A list of directory names (separated by semicolons in Windows, and colons in UNIX):- The classes are in a package tree relative to any of the directories in the list.

• A .zip or .jar file name that is fully qualified with its path name:- The classes in these files must be zipped with the path names that are derived

from the directories formed by their package names.Note: The directory containing the root name of a package tree must be added to the CLASSPATH. Consider putting the CLASSPATH information in the command window or even the Java command, rather than hard-coding it in the environment. For example,

java -classpath E:\Curriculum\courses\java\les06 practice06.AddCustomers

Page 242: Java Programming

Oracle10g: Java Programming 7-30

7-30 Copyright © 2004, Oracle. All rights reserved.

Access Modifiers

private

protected

acmevideo acmetools

public public

Access ModifiersJava controls access to variables and methods through the use of access modifiers. The access modifiers are private, public, protected and default (no modifier).The least restrictive access modifier is public. Variables and methods that are declared as public can be seen and used by any other class.If an access modifier is not specified, called package access (or default access), then the variables and methods can be used by any other class within the same package.The next level of access modifier is protected. Variables and methods that are declared as protected can be seen from any subclass of that class. They can also be seen from any class within the package in which they exist.The most restrictive access modifier is private. A private method or variable cannot be accessed by any other class. The restriction applies to all other classes and subclasses regardless of their package.The final access modifier is default (no modifier). In this modifier, only other members of the same package can access variables and methods.

Page 243: Java Programming

Oracle10g: Java Programming 7-31

Variable or Method Visibility

Member Visibility Modifier

Access in order from least restrictive to most restrictive:• Public: All• Protected: Only other members of the same package or from a different package if

inherited (using extends keyword)• Default (no modifier): Only other members of the same package• Private: Only other members of the same class

Examples:1. A protected double getWage() method is visible in all the classes that are in

the same package as the class in which this method is defined and all subclasses of that class.

2. The int getCount() method is visible in all the classes that are in the same package as the class in which this method is defined.

NNNYNon-Subclass in Different Package

NNYYSubclass in Different Package

NYYYAny Class in Same Package

YYYYSame Class

PrivateDefault (absent)

ProtectedPublicAccessible to

Page 244: Java Programming

Oracle10g: Java Programming 7-32

7-32 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:• A class definition specifies a template for building

objects with identical features, such as instance variables and methods.

• An object is an instance of a particular class.– Create an object by using new.– Manipulate an object by using its public instance

methods.

Class DefinitionsClass definitions serve as templates or blueprints for all objects of that class. The definition includes all attributes and behaviors for that class. The attributes are called instance variables and must be declared as private to achieve proper levels of encapsulation. The behaviors are called instance methods and must be declared as public.

ObjectsAll objects are instances of a particular class. Objects are created by using the new operator. If the classes are declared properly, then all object manipulation must occur by the use of public instance methods.

Page 245: Java Programming

Oracle10g: Java Programming 7-33

7-33 Copyright © 2004, Oracle. All rights reserved.

Practice 7: Overview

This practice covers:• Defining new classes• Specifying the classes’ instance variables and

instance methods• Creating Customer objects in main()• Manipulating Customer objects by using public

instance methods

Practice 7: OverviewNote: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les06 directory, load up the OrderEntryWorkspaceLes06 workspace, and continue with this practice.Viewing the model: To view the course application model up to this practice, load the OrderEntryWorkspaceLes06 workspace. In the Applications – Navigator node, expand the OrderEntryWorkspaceLes06 – OrderEntryProjectLes06 -Application Sources – oe, and double-click the UML Class Diagram1 entry. This diagram displays all the classes created to this point in the course.

Page 246: Java Programming

Oracle10g: Java Programming 7-34

Practice 7: Creating Classes and ObjectsGoalThe goal of this practice is to complete the basic functionality for existing method bodies of the Customer classes. You then create customer objects, and manipulate them by using their public instance methods. You display the Customer information back to the JDeveloper message window.Note: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les06 directory, load the OrderEntryLes06 workspace, and continue with this practice.Your AssignmentIn this pra ctice, you begin refining the application for the Order Processing business area. These classes continue to form the basis for the rest of the application that you are building for the remainder of the course. After creating one or more Customer objects, you associate a customer with an order. Refine the Customer class

1. From the Application Navigator pane, in the OrderEntryProject, make the following changes to the Customer class.

a. Make all instance variables private. To do this, open the Customer.javafile and select the Class tab. This opens the Class Editor. Select the Fields tab, double-click an attribute name, and click the Scope drop-down list to change the value to private.Note: Alternatively, you can also change the scope of the variables in the Source by modifying the Customer.java file.

b. sing the ode ditor or the lassditor assign each of the setXXX() methods to its appropriate field.

c. The get methods must be assigned. Confirm whether the getXXX() methods return their appropriate field values.

Note: The naming convention, such as setId(), setName(), and so on for these methods, makes the classes more intuitive and easier to use.

2. At the moment, there is no way to display most or all details for a Customer object by calling one method.

a. To cover this deficiency, add a new toString() public method to the class, without arguments, and return a String containing the customer’s ID, name, address, and phone number. The resultant string should be a simple concatenation of the attributes that you want to display. For example:public String toString() {return property1 + " " + property2;}

Note: The toString() method is a special method that is called anytime a Stringrepresentation of an object is needed. The toString() method is very useful to add to any class, and thus it is added to almost all the classes that you create. When adding the toString method, a pop-up dialog box with this message is displayed: “OK to override method.” Click “yes.”

b. Save the Customer class, right-click, and select Rebuild to compile it to remove any syntax errors.

Page 247: Java Programming

Oracle10g: Java Programming 7-35

Practice 7: Creating Classes and Objects (continued)Create Customer Objects (OrderEntry class)

3. Modify the main() method in the OrderEntry class to create two customer objects.

a. In the main() method of OrderEntry.java, create two customer objects by using the new operator, assigning each one to a different object reference (use customer1 and customer2).

b. At the end of the main() method, initialize the state of each Customer objectby calling its public setXXX() methods to set the ID, name, address, andphone. Use the table data below:Id Name Address Phone 1Gary Williams Houston, TX 713.555.87652Lynn Munsinger Orlando, FL 407.695.2210

c. Print the two customer objects created, under a printed heading of “Customers:”by calling the toString() method inside the argument of the System.out.println(…) method. For example:System.out.println("\nCustomers:");System.out.println(customer1.toString()); ...

Note: Alternatively, you can just print the customer object reference variableto achieve the same result. For example:System.out.println(customer1);

This latter technique is a feature of Java that is discussed in a subsequent lesson.

d. Save the OrderEntry class, compile, and run the class to view the results.Modify OrderEntry to Associate a Customer to an Order

4. In the main() method of the OrderEntry class, associate one of the customer objects with the order object, and display the order details.

a. Call the setCustomer() method of the order object passing in the object reference of customer1 (or customer2).

b. After setting the customer, call the showOrder() method of the order object.

c. Save, compile, and run the OrderEntry class.

Page 248: Java Programming
Page 249: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Object Life Cycle and Inner Classes

Schedule: Timing Topic70 minutes Lecture40 minutes Practice

110 minutes Total

Page 250: Java Programming

Oracle10g: Java Programming 8-2

8-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Provide two or more methods with the same name

in a class• Provide one or more constructors for a class• Use initializers to initialize both instance and class

variables• Describe the class loading and initializing

process, and the object life cycle• Define and use inner classes

Lesson AimThis lesson explores some of the more advanced issues relating to class definitions. You learn how to provide and use overloaded methods in a class, and how to ensure that the class and object state is initialized to know values when created. The lesson discusses replacing and supplementing the default no-arg constructor with alternative constructors.

Page 251: Java Programming

Oracle10g: Java Programming 8-3

Lesson Aim (continued)Instance MethodsInstance methods are the foundation of encapsulation and are the key in providing a consistent interface to the class. Classes that are defined with proper encapsulation techniques use instance methods to provide class information to the outside world. Without instance methods, a user can inspect and modify class data directly without any program-enforced validation.OverloadingWith overloading, a method call can invoke different behaviors depending on the parameter passed. For example in a Dog class, the smell() method can invoke completely different behaviors depending on the parameter. If the call is smell(cat), then the behavior would be incessant barking and howling, whereas the smell(food)method would invoke salivating and eating or begging.Overloading is a powerful technique in achieving a uniform appearance of your class to the outside world.ConstructorsConstructors ensure that regardless of who creates an object, the object has all of the expected characteristics of the class. Upon creation of an object, the constructor method is called implicitly, providing a place for initialization routines. This is key in object-oriented programming, because you do not know exactly who will be creating new objects of your class.Garbage CollectorThe garbage collector is the process that handles the memory allocation. It is in charge of cleaning the memory space that is allocated to objects that are not used anymore.Inner ClassesIn releases of the Java language before release 1.1, all top-level classes must be declared as members of a package. As of Java Development Kit (JDK), release 1.1, this restriction is removed allowing classes to be declared in any scope. Classes declared inside other classes are called nested classes, and one common type of nested class is called an inner class.

Page 252: Java Programming

Oracle10g: Java Programming 8-4

8-4 Copyright © 2004, Oracle. All rights reserved.

Overloading Methods

• Several methods in a class can have the same name.

• The methods must have different signatures.

public class Movie {

public void setPrice() {

price = 3.50F;

}

public void setPrice(float newPrice) {

price = newPrice;

} …

}

Movie mov1 = new Movie();

mov1.setPrice();

mov1.setPrice(3.25F);

Method OverloadingTwo or more methods in a class can have the same name, provided that they have different signatures. A method signature is formed from its name, together with the number and types of its arguments. The method return type is not considered part of the method signature.Defining two or more methods with the same name but different signatures is called method overloading. This technique is useful in presenting a unified interface to the outside world. The exact method that is called is determined by the parameters that are included in the call. Without method overloading, each method would require a unique name. For example, if you want to retrieve customer information by customer ID or by name, then you would need two methods: getCustomerByID(id) and getCustomerByName(name). With overloading, you will have two methods named getCustomer(), one with the ID parameter and the other with the name parameter.How Does the Compiler Decide Which Overloaded Method to Call?When a user of a class calls an overloaded method, the compiler chooses the correct method to call by comparing the argument types that are passed in the call with all the methods of that name in the class definition. If the compiler cannot find a compatible match, even after performing possible type conversions, then it flags an error. Likewise, if more than one match is possible, then the compiler flags an error, because the method call is ambiguous.Can Overloaded Methods Differ in Return Type Only?No. Overloaded methods must be distinguishable by comparing their argument lists alone. If overloaded methods differ in their return type only, then the compiler flags an error.

Page 253: Java Programming

Oracle10g: Java Programming 8-5

8-5 Copyright © 2004, Oracle. All rights reserved.

Using the this Reference

Instance methods receive an argument called this, which refers to the current object.

public class Movie {

public void setRating(String newRating) {

this.rating = newRating;

}

void anyMethod() {

Movie mov1 = new Movie();

Movie mov2 = new Movie();

mov1.setRating("PG"); …title: null

rating: nullmov2

mov1

title : nullrating: “PG”

this

All Methods Receive a Reference to “This Object”All instance methods receive an implicit argument called this, which can be used inside any method to refer to the current object. The current object is the object on which the method was called. The this argument is an implicit reference to the calling object and as such is not required in most cases.How Is this Used Inside an Instance Method?Inside an instance method, any unqualified reference to an instance variable or instance method is implicitly associated with the this reference. For example, the two following statements are equivalent:

public void setRating(String inRating) {rating = inRating;this.rating = inRating;

}There are two circumstances where you must use an explicit this reference:

• When the name of an instance variable is hidden by a formal argument of an instance method. For example, if there is an instance variable called name, and an argument that is also called name, then the argument hides the instance variable. Any reference to name accesses the argument, not the variable. To access the instance variable, you must use this.name.

• When you need to pass a reference to the current object as an argument to another method

Page 254: Java Programming

Oracle10g: Java Programming 8-6

8-6 Copyright © 2004, Oracle. All rights reserved.

Initializing Instance Variables

• Instance variables can be explicitly initialized at declaration.

• Initialization happens at object creation.

• All instance variables are initialized implicitly to default values depending on data type.

• More complex initialization must be placed in a constructor.

public class Movie {

private String title;

private String rating = "G";

private int numOfOscars = 0;

Initialization of Instance VariablesWhen an object is created, Java automatically performs default initialization for all the instance variables in the object:• char variables are set to '\u0000'.• byte, short, int, and long variables are set to 0.• boolean variables are set to false.• float and double variables are set to 0.0.• Object references are set to null.

Explicit Initialization of Instance VariablesTo initialize an instance variable to a nondefault value, you can specify initializers. This allows instance variables to be assigned an explicit value. For example:

public class Movie {private String rating = "G";…

}

Complex Initialization of Instance VariablesInitializers are fine if you want to assign a simple value to an instance variable, but if you want to carry out more sophisticated initialization, then you must use a constructor. A constructor is a special instance method that is used to initialize new instances of a class.

Page 255: Java Programming

Oracle10g: Java Programming 8-7

8-7 Copyright © 2004, Oracle. All rights reserved.

What Are Constructors?

• For proper initialization, a class must provide a constructor.

• A constructor is called automatically when an object is created:– It is usually declared public. – It has the same name as the class.– It must not specify a return type.

• The compiler supplies a no-arg constructor if and only if a constructor is not explicitly provided.– If any constructor is explicitly provided, then the

compiler does not generate the no-arg constructor.

ConstructorsWhen an object is created, its instance variables are initialized to their default values. However, you will generally need to provide one or more constructors in a class to initialize its instance variables properly and to allow users of the class to specify the initial state of an object.For example, with the Movie class, you have already seen examples, such as:

Movie mov1 = new Movie ("Gone with the Wind");

For a user to create an object in this way, the Movie class must provide a constructor that initializes the state of a Movie object with the specified title of the movie.How and When Are Constructors Called?A constructor is a special method that is called automatically by the run-time system when an object is created. A constructor has the same name as the class; it can have arguments but must not specify a return type. Constructors must be declared as public unless you want to restrict who can create instances of the class.What Happens If You Do Not Provide a Constructor?If you do not provide any constructors, then a default no-argument (no-arg) constructor is provided for you. This constructor takes no arguments and does nothing, but does at least allow objects to be created. The no-arg constructor invokes the no-arg constructor of its parent class.Note: If you want a specific no-arg constructor as well as constructors that take arguments, then you must explicitly provide your own no-arg constructor.

Page 256: Java Programming

Oracle10g: Java Programming 8-8

8-8 Copyright © 2004, Oracle. All rights reserved.

Defining and Overloading Constructors

public class Movie {

private String title;

private String rating = "PG";

public Movie() {

title = "Last Action …";

}

public Movie(String newTitle) {

title = newTitle;

}

}Movie mov1 = new Movie();

Movie mov2 = new Movie("Gone …");

Movie mov3 = new Movie("The Good …");

The Movie classnow provides two

constructors.

Anatomy of a ConstructorA constructor is a special method that is called automatically when an object is created. A constructor must have the same name as the class. It can have arguments, but it must not specify a return type.Overloaded ConstructorsAs with overloaded methods, if you want to provide more than one constructor in a class, then each one must have a different signature. Because each constructor must have the same name anyway, this simply means that each constructor must have different numbers or types of arguments.ExampleIn the example, the Movie class has two simple constructors: one with no arguments, and the other that takes a String argument for the title of the movie. Users of the Movie class can now create movies with different titles. When you create a new Movie object, the compiler decides which constructor to call based on the arguments that are specified in parentheses in the new statement. For example:Movie mov1 = new Movie(); // calls the no-arg

constructorMovie mov2 = new Movie(“Last ...”); // calls the constructor with

the String argument

Page 257: Java Programming

Oracle10g: Java Programming 8-9

8-9 Copyright © 2004, Oracle. All rights reserved.

Sharing Code Between Constructors

public class Movie {

private String title;

private String rating;

public Movie() {

this("G");

}

public Movie(String newRating) {

rating = newRating;

}

}

A constructor can call another constructor by using this().

Movie mov2 = new Movie();

What happens here?

Sharing Code Between ConstructorsA constructor can call another constructor of the same class by using the this() syntax.

public Movie() { // First constructorthis("G");

}public Movie(String r) { // Second constructor

rating = r;}

The first constructor calls the second constructor, passing "G" as an argument. The second constructor then copies the string into the rating instance variable. Using this technique ensures that the default rating for all Movies is "G" without duplicating the code in multiple constructors.By using this(), you avoid duplicate code in multiple constructors. This technique is especially useful if the initialization routine is complex. All the complex code goes into one constructor that is called from all the others.Syntax RulesWhen one constructor calls another by using the this() syntax, there are a few rules of syntax that you need to be aware of:

• The call to this() must be the first statement in the constructor.• The arguments to this() must match those of the target constructor.

Page 258: Java Programming

Oracle10g: Java Programming 8-10

8-10 Copyright © 2004, Oracle. All rights reserved.

final Variables, Methods, and Classes

• A final variable is a constant and cannot be modified.– It must therefore be initialized.– It is often declared public static for external

use.• A final method cannot be overridden by a

subclass.• A final class cannot be subclassed.public final class Color {

public final static Color black=new Color(0,0,0);

}

final VariablesBy default, all variables may be modified, and methods may be overridden. Specifying a variable as final prevents modification of its value, making a constant value. This is useful for guaranteeing that a value is consistent across all users of the class. These variables are usually declared public static final, as classwide constants.

final MethodsA final method is one that cannot be overridden in a subclass. In other words, if a programmer inherits from the class, then he or she is not allowed to provide an alternative version of this method. This is a useful technique to prevent programmers inadvertently or maliciously redefining core methods that must work a certain way.

final ClassesYou may also declare a class to be final. A final class is one that cannot be inherited from. In fact, the Color class that is shown in the slide is a final class. By declaring a class as final, you are making a strong design decision that the class is complete enough to meet all its current and future requirements and will never need to be extended to provide additional functionality.

Page 259: Java Programming

Oracle10g: Java Programming 8-11

8-11 Copyright © 2004, Oracle. All rights reserved.

Reclaiming Memory

• When all references to an object are lost, the object is marked for garbage collection.

• Garbage collection reclaims memory that is used by the object.

• Garbage collection is automatic.• There is no need for the programmer to do

anything, but the programmer can give a hint to System.gc();.

Garbage CollectionMemory management in Java is automatic. When an object is created, memory is allocated for the object from a heap. When there are no more references to that object, it is marked for garbage collection. When the garbage collector runs, it searches for marked memory and returns it to the heap.There are no free() or delete() functions in Java as there are in C++. To force an object to be marked for garbage collection, simply remove all references to that object by setting the references to null.When Does Garbage Collection Occur?Garbage collection is implementation specific. Some environments run garbage collection when the amount of free memory that is available to Java Virtual Machine (JVM) falls below some arbitrary threshold. JVM performs garbage collection in a low-priority thread. When JVM has nothing else to do, the garbage collector thread receives some CPU time to see whether any memory can be reclaimed.You can explicitly request the garbage collector to run by calling the gc() method as follows:

System.gc();However, this is only a request for garbage collection; there is no guarantee that JVM will take the hint. Because of this internal garbage collection process, you do not automatically know when an object is deleted and whether the necessary amount of memory that is needed for this object is still in use.

Page 260: Java Programming

Oracle10g: Java Programming 8-12

8-12 Copyright © 2004, Oracle. All rights reserved.

Using the finalize() Method

• If an object holds a resource such as a file, then the object should be able to clean it up.

• You can provide a finalize() method in that class.

• The finalize() method is called just before garbage collection.public class Movie {

public void finalize() {

System.out.println("Goodbye");

}

}

Any problems?

Destructors and the finalize() MethodIn some languages, such as C++, a class can provide a destructor. A destructor is similar to a constructor, except that it is called automatically just before an object is destroyed. A destructor is normally used to free up resources that are held by the object, such as any secondary memory that is allocated by the object, open files, and so on.Java Does Not Support DestructorsJava manages memory automatically, so an object need not explicitly free any secondary memory that it may have allocated. Consequently, Java does not support destructors. Instead, to allow an object to clean up resources other than memory, such as open files, Java allows a class to provide a finalize() method.Anatomy of the finalize() MethodThe finalize() method is called automatically when an object is garbage-collected. Unfortunately, as you have already seen, there is no guarantee regarding when this will happen or that it will happen before the program exits. The virtual machine reserves the right to not immediately collect the memory that is associated with an object after calling the finalizer. Such objects are known as phantoms.Alternatives to finalize()The unpredictability of when finalize() is called is unacceptable if resources are scarce. The only solution is to manage such resources manually. To take control of the process, you can define a public dispose() method in your class, which users of your class must call when they have finished using an object of your class. You can still keep your finalize() method if you want to, as a final effort to clean up resources.

Page 261: Java Programming

Oracle10g: Java Programming 8-13

8-13 Copyright © 2004, Oracle. All rights reserved.

What Are Inner Classes?

• Inner classes are nested classes, defined in a class or method.

• They enforce a relationship between two classes.• They are of four types:

– Static– Member– Local– Anonymous

public class Outer { …

class Inner { …

}

}

Enclosing class

Inner Class DefinitionAn inner class is simply a class that is defined within a class.You define inner classes because they functionally support the outer class or because they make sense in the context of the enclosing class.Inner classes have different privileges when accessing outer class members according to the type of inner class they are.There are four different types of inner classes:

• Defined in a class:- Static Inner Class- Member Inner Class

• Defined in a method:- Local Inner Class: Used within the scope of the method it was declared in- Anonymous Inner class: Used globally outside of the method it was declared in

You must be careful when using inner classes, because they can make the code more difficult to read, especially for people who have to maintain the application.Inner classes result from the combination of block structure with class-based programming, which was pioneered by the Beta programming language. Using block structure with inner classes makes it easier for the Java programmer to connect objects together, because classes can be defined closer to the objects that they need to manipulate, and can directly use the names that they need.

Page 262: Java Programming

Oracle10g: Java Programming 8-14

8-14 Copyright © 2004, Oracle. All rights reserved.

Using Member Inner Class

• It is declared within another class.• Nesting is allowed.• It can access variables within its own class and

any enclosing classes. • It can only declare final static methods.public class CalendarPopup {...class MonthSelector {

class DayOfMonth{...};DayOfMonth[] NumberOfDaysInMonth...

}}

Member Inner Class: ExampleTo better understand Member Inner classes, look at this example:You have an application with a few date items, such as booking date and return date, and you want to allow the users to select a specific booking date from a pop-up calendar. You can put a button on the user interface, which when clicked, invokes a pop-up calendar displaying the current date. The user can then select a different month for the booking or select a specific day. In this example, a top-level class can be used to control the pop-up calendar. The month selector class can be implemented as a Member Inner class of the calendar. The MonthSelector class will then populate an array with the appropriate days in the month. The DayOfMonth class is a Member Inner class, because it is created within a class and not a method.

Instructor NoteThe Member Inner class can inherit static members even if constant, but cannot declare static members.

Page 263: Java Programming

Oracle10g: Java Programming 8-15

8-15 Copyright © 2004, Oracle. All rights reserved.

Using Local Inner Class

• It is declared within a code block (inside a method).

• All final variables or parameters declared in the block are accessible by the methods of the inner class.

public class CalendarPopup {...public void handlerMethod(){

class DateHandler{…};DateHandler sc = new DateHandler();...

}}

Local Inner Class: ExampleTo better understand Local Inner classes, look at this example: You have the same application as before, with a few date items, such as booking date and return date.You can put a button on the user interface, which when clicked, invokes a pop-up calendar displaying the current date. The user can then select a different month for the booking or select a specific day. In this example, a top-level class can be used to control the pop-up calendar functionality. The DateHandler class can be implemented as a Local Inner class of the CalendarPopup. After a booking day button is clicked, and then accepted, the action handler method invoked can create a Local Inner class to store the booking date and calculate the return date. In this case, the Local Inner class will be used within the action handler and nowhere else. The Local Inner class is used only with the scope of the action handler.

Page 264: Java Programming

Oracle10g: Java Programming 8-16

8-16 Copyright © 2004, Oracle. All rights reserved.

Defining Anonymous Inner Classes

• They are defined at method level.• They are declared within a code block.• They lack the class, extends, and implements

keywords.• They cannot have a constructor.public class Outer {...public void outerMethod(){

...myObject.myAnonymous(new SomeOtherClass(){...} )

}}

Anonymous Inner ClassesAnonymous inner classes are Local Inner classes with no class name. The class keyword is omitted and so are public, protected, extends, and implements. They are commonly used to implement user interface adapters to perform event handling when using AWT or Swing events.Anonymous inner classes have the same restriction as Local Inner classes concerning the visibility on the outer class elements.The generic anonymous class syntax takes the form: Class Outer {

…AnInnerAnonymousClass (new SuperClass ( ) {

. . .} );. . .

}The anonymous class is derived from a superclass that allows the use of the methods of thissuperclass. Anonymous inner classes can implicitly extend or implement only other classes or interfaces. The use of anonymous classes is most effective when they implement only a single or very few small methods. Reading the code can get confusing when the definition of the inner class is long.Anonymous inner classes have the same accessibility rules as Local Inner classes. It is primarily used to create a one-time implementation class of an interface.

Page 265: Java Programming

Oracle10g: Java Programming 8-17

8-17 Copyright © 2004, Oracle. All rights reserved.

Using the Calendar Class

• It converts between a date object and a set of integer fields.

• It represents a specific moment in time.• Subclasses interpret a date according to the

specific calendar system.public class Order {...public void String getShipDate(){

...Calendar c = Calendar.getInstance();c.setTime(orderDate); ...} )

}}

The Calendar ClassCalendar is an abstract base class for converting between a Date object and a set of integer fields such as YEAR, MONTH, DAY, HOUR, and so on. (A Date object represents a specific instant in time with millisecond precision.) Specific subclasses of Calendar interpret a Date according to the rules of a specific calendar system. One concrete example of a Calendar subclass is GregorianCalendar.Using the Calendar ClassThe Calendar object can produce all the time field values needed to implement the date–time formatting for a particular language and calendar style (for example, Japanese–Gregorian, Japanese–Traditional, and so on). Calendar defines the range of values returned by certain fields, as well as their meanings. For example, the first month of the year has value MONTH == JANUARY for all calendars. Like other locale-sensitive classes, Calendar provides a class method, getInstance, for getting a generally useful object of this type. A Calendar’s getInstance method returns a Calendar object whose time fields have been initialized with the current date and time:

Calendar rightNow = Calendar.getInstance(); The setTime method sets this Calendar’s current time with the given Date.

Instructor NoteThis slide is included here, because the class is used in the practice. Do not get too involved, explaining all the details.

Page 266: Java Programming

Oracle10g: Java Programming 8-18

8-18 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:• Methods can be overloaded in Java.• Instance methods receive a this reference to the

current object.• Most classes provide one or more constructors to

initialize new objects.• Class variables and class methods can be defined

for classwide properties and behaviors.• Classes can be defined in various ways within a

class.

Page 267: Java Programming

Oracle10g: Java Programming 8-19

8-19 Copyright © 2004, Oracle. All rights reserved.

Practice 8: Overview

This practice covers:• Defining and using overloaded methods• Providing a no-arg constructor for a class• Providing additional constructors for a class• Defining static variables and static methods for

classwide behavior• Using static methods

Practice 8: OverviewNote: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les07 directory, load up the OrderEntryLes07 workspace, and continue with this practice.Viewing the model: To view the course application model up to this practice, load the OrderEntryWorkspaceLes07 workspace. In the Applications – Navigator node, expand the OrderEntryWorkspaceLes07 – OrderEntryProjectLes07 -Application Sources – oe, and double-click the UML Class Diagram1entry. This diagram displays all the classes created to this point in the course.

Page 268: Java Programming

Oracle10g: Java Programming 8-20

Practice 8: Object Life Cycle ClassesGoalThe goal of this practice is to gain experience with creating and using constructors, classwide methods, and attributes. You also use an existing DataMan class to provide a data access layer for finding customers and products in the OrderEntry application. Partof the practice is to understand method overloading by creating more than one constructor and/or method with the same name in the same class.Note: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les07 directory, load up the OrderEntryLes07 workspace, and continue with this practice.Your AssignmentCreate at least one or more suitable constructors to properly initialize the Customerobjects when instantiated. Examine the Order class and the new instantiations. Copy and examine a DataMan class to provide classwide (static) attributes of customer objects to be used by the OrderEntry application when it associates a customer object to an order.Modify Customer InformationThe Customer class will have two constructors:

1. Create a no-arg constructor to provide default initialization, and another constructor to set the actual name, address, and phone properties. The no-arg constructor will be invoked by the second constructor.

a. Add a no-arg constructor to the Customer class, which is used to generate the next unique ID for the customer object by first declaring a class variable, called nextCustomerId, as a private static integer initialized to zero.

b. In the OrderEntry class, comment out the customer.setId, customer.setName, customer.setAddress, and customer.setPhone statements for both customer1 and customer2.

c. Back in the Customer class, create a no-arg constructor, increment the nextCustomerId, and use the setID() method with nextCustomerIdto set the ID of the customer.

d. Add a second constructor that accepts a name, address, and phone as Stringarguments. This constructor must set the corresponding properties to these values.

e. In the first line of the second constructor, chain it to the first constructor by invoking the no-arg constructor by using the this() keyword. This is done to ensure that the ID of a customer is always set regardless of the constructor used.

f. Save, compile, and run the OrderEntry class to check the results. Including the order and item details that are displayed as output, you should see"Customer: 1 null null null".

Replace and examine the Order.java File2. In Windows Explorer, copy the Order.java class from the E:\labs\temp directory

into your current working …\src\oe directory. For example if you are working in les06 directory then copy the files under E:\les06\src\oe.

a. Select your workspace and select the Open menu option. Navigate to your current …\src\oe directory and select the Order.java file. Click the Open button, and it will be included in the list of files.

Page 269: Java Programming

Oracle10g: Java Programming 8-21

Practice 8: Object Life Cycle Classes (continued)The new version of the Order class also has one constructor:

3. Examine the way in which the order date information is managed:a. Notice the orderDate variable that had been commented out is now a

private variable.b. After the package statement at the top of the class, notice the import statements

(before the class declaration):import java.util.Date;import java.util.Calendar;

c. Notice the orderDate type to be Date instead of String, and that the three integer variables–day, month, and year–have been removed.

4. Examine the methods that depend on three integer date variables (which were removed in step 3c) to use orderDate.

a. The return type and value of the getOrderDate() method are replaced as follows:public Date getOrderDate(){

return orderDate;}

In addition, included is an overloaded void setOrderdate() method that accepts a Date as its argument and sets the orderDate variable.

b. The getShipDate() method had used the Calendar class to calculate the ship date. The body of getShipDate() has been replaced with the following code:int daysToShip = Util.getDaysToShip(region);Calendar c = Calendar.getInstance();c.setTime(orderDate);c.add(Calendar.DAY_OF_MONTH, daysToShip);return c.getTime().toString();

c. The setOrderDate() method body is coded to set the orderDate by using the Calendar class methods, using the three input arguments: The following date initialization code has been deleted:day = 0;month = 0;year = 0;

d. Notice the setOrderDate() method has been modified. The following three bold lines of code:if ((m > 0 && m <= 12) && (y > 0 )) {

day = d;month = m;year = y;

}have been replaced with these three lines of code:Calendar c = Calendar.getInstance();c.set(y, m - 1, d); orderDate = c.getTime();

Page 270: Java Programming

Oracle10g: Java Programming 8-22

Practice 8: Object Life Cycle Classes (continued)5. A no-arg constructor has been created to initialize the order number, date, and total.

a. Notice a new class (private static int) variable called nextOrderIdhas been created and initialized to 100.

b. In the no-arg constructor, the ID of the order is set to the value in nextOrderId. It then increments nextOrderId. The orderTotal is set to 0, and the orderDate is set as follows:orderDate = new Date();

Load the DataMan.java Class File into JDeveloperThe DataMan class is used to create the data that will be used to test the application. The file creates the customer objects, and later will be used to access a database for information. This class is really a convenience class that simplifies your application testing. However, after this class is completed, it can be changed to retrieve data from a database without impacting your application.

6. In Windows Explorer, copy the DataMan.java class from the E:\labs directory into your current working …\src\oe directory.

a. Select your workspace and select the Open menu option. Navigate to your current …\src\oe directory and select the DataMan.java file. Press OK, and it will be included in the list of classes.

b. Save and compile the DataMan.java class.Note: You can compile DataMan.java by right-clicking the file and selecting the Make menu option.

c. Save, compile, and run the OrderEntry class to test if the code still works. You can compile OrderEntry.java by right-clicking on the file and selecting the Make menu option.

Modify OrderEntry to Use DataMan7. Modify the main() method in OrderEntry to use customer objects from the

DataMan class.a. Use the class name “DataMan.” as the prefix to all customer references

variables customer1 and customer2. For example, change the code:order.setCustomer(customer1);to become:order.setCustomer(DataMan.customer1);Note: You are accessing a class variable via its class name; that is, there is no need to create a DataMan object. In addition, the customer variables inDataMan are visible to OrderEntry because they have default (package) access.

b. Save, compile, and run the OrderEntry class to test if the code still works. Replace customer1 with customer3 or customer4 from DataMan to confirm that your code is using the customer objects from DataMan.

Page 271: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Using Strings, String Buffer, Wrapper,and Text-Formatting Classes

Schedule: Timing Topic70 minutes Lecture and guided practices25 minutes Practice95 minutes Total

Page 272: Java Programming

Oracle10g: Java Programming 9-2

9-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Create strings in Java• Use the conversion methods that are provided by

the predefined wrapper classes• Use the StringBuffer class for manipulating

character data• Introduce the DateFormat, DecimalFormat, and

MessageFormat classes• Examine standard output and serialization

Lesson AimThis lesson shows how to use the Java String class and the StringBuffer class to manipulate character strings. You also use the Java wrapper classes to convert primitive types into other formats.

Instructor NoteThis lesson covers a number of classes: String, Stringbuffer, and the various wrapper classes with their own set of methods. It would be beyond the scope of the course notes to list the complete syntax of every method that is mentioned, so you may find it useful to show the J2SE online documentation for the various classes as a way of describing selected methods and classes in more detail. The String, StringBuffer, and wrapper classes are in the java.lang package, and the DateFormat, DecimalFormat, and MessageFormatclasses are in the java.text package.

Page 273: Java Programming

Oracle10g: Java Programming 9-3

9-3 Copyright © 2004, Oracle. All rights reserved.

What Is a String?

• String is a class.• A String object holds a sequence of characters.• String objects are read-only (immutable); their

values cannot be changed after creation.• The String class represents all strings in Java.

Strings in JavaAs with most programming languages, strings are used extensively throughout Java, so the Java application programming interface (API) provides a String class to help you work with strings of character data. Literal string values in Java source code are turned into String objects by the compiler. The String objects can be used directly, passed as arguments to methods, or assigned to String object reference variables:

System.out.println( "Hello World..." );String str = "Action";

Strings Cannot Be ModifiedThe String class represents an immutable string. This means that after you have created a String object, you cannot change it. If you want to modify the contents of the string, then you must use the StringBuffer class.

Page 274: Java Programming

Oracle10g: Java Programming 9-4

9-4 Copyright © 2004, Oracle. All rights reserved.

Creating a String

• Assign a double-quoted constant to a Stringvariable:

• Concatenate other strings:

• Use a constructor:

String category = "Action";

String empName = firstName + " " + lastName;

String empName = new String(“Bob Smith");

Creating StringsThe easiest way to create a string is from a double-quoted constant, as shown in the first example in the slide. You can use the + operator to concatenate two String objects. This is explained in more detail in the following slides.The String class provides several constructors. The following are some of the more useful ones:• String() creates an empty string, with the value "". • String(String str) creates a copy of the specified String object, str.• String(char[] arr) creates a string from the characters in a character array.

You can find a list of constructors in the online J2SE documentation for the String class, which is available in JDeveloper’s online Help.Using Strings in Your CodeThe String class is part of the java.lang package. java.lang is automatically imported into all Java classes, so you do not need to add any import statements to your code to use String objects.

Page 275: Java Programming

Oracle10g: Java Programming 9-5

9-5 Copyright © 2004, Oracle. All rights reserved.

Concatenating Strings

• Use the + operator to concatenate strings.

• You can concatenate primitives and strings.

• The String class has a concat() instance method that can be used to concatenate strings.

System.out.println("Name = " + empName);

int age = getAge();

System.out.println("Age = " + age);

Concatenating StringsJava uses +, which is the only overloaded operator in Java, for string concatenation. The concat() method in the String class is another way to concatenate strings.The following code produces equivalent strings:

String name = "Sam Wong";String name = "Sam " + "Wong";String name = "Sam ".concat("Wong");

The second example in the slide shows a primitive (in this case, an int) being concatenated with a String; the primitive is implicitly converted to a String.Literal strings cannot span lines in Java source files, but you can concatenate lines to produce the same effect:

String song ="What good is sitting alone in your room" + "\n" +"Come hear the music play" + "\n" +"Life is a cabaret old chum" + "\n" +"Come to the cabaret" + "\n";

Page 276: Java Programming

Oracle10g: Java Programming 9-6

9-6 Copyright © 2004, Oracle. All rights reserved.

Performing Operations on Strings

• Find the length of a string:

• Find the character at a specific index:

• Return a substring of a string:

int length(); String str = "Comedy";

int len = str.length();

char charAt(int index); String str = "Comedy";

char c = str.charAt(1);

String substring

(int beginIndex,

int endIndex);

String str = "Comedy";

String sub =

str.substring(2,4);

Performing Operations on StringsFind the Length of a StringThe length() method returns the number of characters in a string. In the example in the slide, len is set to 6.Return the Character at a Specified IndexThe charAt() method returns the character at the specified index (indexing starts at 0). In the example in the slide, c is set to "o".Return a Substring of a StringThe substring() method returns a specified substring (starting at beginIndex, ending at endIndex - 1) of the string. In the example in the slide, sub is set to "me".

Instructor NoteThe following statements point the object reference str to a new location in memory, rather than changing the contents of the string:

String str = "Action";str = "Comedy";

The second statement creates a second String object that is also read-only. This distinction is theoretical in most cases; the real significance of immutability for the programmer is that you cannot manipulate the characters within a string, as you can with C pointers or character arrays.

Page 277: Java Programming

Oracle10g: Java Programming 9-7

9-7 Copyright © 2004, Oracle. All rights reserved.

Performing More Operations on Strings

• Convert to uppercase or lowercase:

• Trim whitespace:

• Find the index of a substring:

String toUpperCase();

String toLowerCase();

String caps =

str.toUpperCase();

String trim(); String nospaces =

str.trim();

int indexOf (String str);

int lastIndexOf

(String str);

int index =

str.indexOf("me");

Performing More Operations on StringsConvert to Uppercase or LowercaseThe toUpperCase() method returns a new string containing an uppercase version of the original string. Similarly, the toLowerCase() method returns a new string containing a lowercase version of the original string.Trim WhitespaceThe trim() method returns a new string containing a copy of the old string with whitespace removed from both ends.Find the Index of a SubstringThere are two accessors that return the position of a specific character or string:

indexOf and lastIndexOfThe indexOf() method returns the index of a specified substring. It returns a zero-based position of substring within str or –1 if not found. The lastIndexOf() method returns the index of the last occurrence of a specified substring.Note: There are multiple versions of both these methods. Check the online J2SE documentation for the String class for details of each one.

Page 278: Java Programming

Oracle10g: Java Programming 9-8

9-8 Copyright © 2004, Oracle. All rights reserved.

Comparing String Objects

• Use equals()if you want case to count:

• Use equalsIgnoreCase()if you want to ignore case:

• Do not use ==.

String passwd = connection.getPassword();

if (passwd.equals("fgHPUw"))… // Case is important

String cat = getCategory();

if (cat.equalsIgnoreCase("Drama"))…

// We just want the word to match

Comparing String Objectsboolean equals(Object anObj) returns true if the specified strings contains the same text. It does not return true if anObj is null or is not a String object.boolean equalsIgnoreCase(String s2) is similar to equals(), except that it ignores case.Do not use the == operator to compare String objects or to compare any types of objects. With objects, == returns true only if the two references point to the same object.

Page 279: Java Programming

Oracle10g: Java Programming 9-9

9-9 Copyright © 2004, Oracle. All rights reserved.

Producing Strings from Other Objects

• Use the Object.toString() method.• Your class can override toString().

• System.out.println() automatically calls an object’s toString() method if a reference is passed to it.

public Class Movie {…

public String toString () {

return name + " (" + Year + ")";

}…

Movie mov = new Movie(…);

System.out.println(mov);

Strings from ObjectsThe toString method for a class object returns a string consisting of the name of the class of which the object is an instance, the “@” (at sign) character, and the unsigned hexadecimal representation of the hash code of the object. The toString() method is invoked automatically whenever you use any object reference in a string concatenation expression, or pass it to System.out.println. In the example in the slide, the Movie class provides a toString() method that prints the name and year of the movie.What Happens If a Class Does Not Provide a toString() Method?If a class does not provide its own toString() method, then it inherits one from the Object class. The string that is produced by Object.toString() is not very user-friendly; it consists of the name of the class of which the object is an instance and a hexadecimal number representing a hash code. The equivalent code that is inherited from the Object.toString() method is:

public String toString() {return getClass().getName() +

'@' + Integer.toHexString(hashCode());}

Page 280: Java Programming

Oracle10g: Java Programming 9-10

9-10 Copyright © 2004, Oracle. All rights reserved.

Producing Strings from Primitives

• Use String.valueOf():

• There is a version of System.out.println()for each primitive type:

String seven = String.valueOf(7);

String onePoint0 = String.valueOf(1.0f);

int count;

System.out.println(count);

Strings from PrimitivesThe String class provides a static method valueOf() that returns a string representation of a primitive type. However, a String does not have a valueOf() method for byte or short. There is a version of valueOf() for each remaining primitive type. The example in the slide uses two versions:

String valueOf(int i)String valueOf(float f)

Printing PrimitivesWhen a primitive is concatenated with a string, it is automatically converted to a string by calling String.valueOf(). When a primitive is passed to System.out.println()on its own, the appropriate version of println() is called; there is a version for each primitive type.

Page 281: Java Programming

Oracle10g: Java Programming 9-11

9-11 Copyright © 2004, Oracle. All rights reserved.

Producing Primitives from Strings

• Use the primitive wrapper classes.• There is one wrapper class for each primitive type:

– Integer wraps the int type.– Float wraps the float type.– Character wraps the char type.– Boolean wraps the boolean type.– And so on…

• Wrapper classes provide methods to convert a String to a primitive, and primitives to a String.

Primitive Wrapper ClassesFor each primitive type, Java provides a corresponding wrapper class that allows a primitive to be handled like an object. Each wrapper class provides a static method to convert a String to the corresponding primitive type. The following slide shows how to use these conversion methods.Other Uses of Wrapper Classes

• Wrapper classes are useful if you need to treat a primitive type as an object. For example, you cannot store primitive types in a Vector, which holds objects. Thus, you will convert an int to an Integer object by using the Integer(int) constructor.

• Wrapper classes provide conversion methods that are related to primitive data type. For example, the Integer class has a number of methods, including Integer.parseInt(), that convert a String containing digits to an int.

• Wrapper classes also provide variables that are related to the type. For example, Integer.MAX_VALUE is the largest possible value of an int.

Instructor NoteEach wrapper class has a toString() method. The following two statements convert an int i to a String:

String str = String.valueOf(i);String str = Integer.toString(i);

Page 282: Java Programming

Oracle10g: Java Programming 9-12

9-12 Copyright © 2004, Oracle. All rights reserved.

Wrapper Class Conversion Methods

Example: Use the methods to process data from fields as they are declared.

String qtyVal = "17";

String priceVal = "425.00";

int qty = Integer.parseInt(qtyVal);

float price = Float.parseFloat(priceVal);

float itemTotal = qty * price;

Wrapper Class Conversion MethodsThe example in the slide shows hardcoded String variables containing numeric values. These values are used to perform a calculation. The qtyVal string is being converted into a int by using the Integer.parseInt() method and the priceVal is being converted into a float by using the Float.ParseFloat() method.Note that the conversion methods were called without instantiating either an Integer object or a Float object. The wrapper classes serve as a home for their conversion methods and need not be instantiated when the methods are called.What Happens If the Strings Contain a Value That Cannot be Converted?If the string contains a noninteger value in the first field, then Integer.parseInt() will fail and throw an exception. To handle such a case, you must add code to catch and handle this exception and to catch and handle a similar exception that is thrown by Float.parseFloat().

Instructor NoteTypically, string data comes from a user in a form, rather than be hardcoded in the application.

Page 283: Java Programming

Oracle10g: Java Programming 9-13

9-13 Copyright © 2004, Oracle. All rights reserved.

Changing the Contents of a String

• Use the StringBuffer class for modifiable strings of characters:

• Use StringBuffer if you need to keep adding characters to a string.

Note: StringBuffer has a reverse() method.

public String reverseIt(String s) {

StringBuffer sb = new StringBuffer();

for (int i = s.length() - 1; i >= 0; i--)

sb.append(s.charAt(i));

return sb.toString();

}

Introducing the StringBuffer ClassStringBuffer represents strings that can be modified and extended at run time. The following example creates three new String objects, and copies all the characters each time a new String is created:

String quote = "Fasten your seatbelts, ";quote = quote + "it’s going to be a bumpy night.";

It is more efficient to preallocate the amount of space that is required by using the StringBuffer constructor and its append() method as follows:

StringBuffer quote = new StringBuffer(60); // alloc 60 charsquote.append("Fasten your seatbelts, ");quote.append(" it’s going to be a bumpy night. ");

StringBuffer also provides several overloaded insert() methods for inserting various types of data at a particular location in the StringBuffer.

Instructor NoteThe example in the slide uses StringBuffer to reverse the characters in a string. A StringBuffer object is created, with the same length as the string. The loop traverses the String parameter in reverse order and appends each of its characters to the StringBuffer object by using append(). The StringBuffer therefore holds a reverse copy of the String parameter. At the end of the method, a new String object is created from the StringBuffer object, and this String is returned from the method.

Page 284: Java Programming

Oracle10g: Java Programming 9-14

9-14 Copyright © 2004, Oracle. All rights reserved.

Formatting Classes

The java.text package contains:• An abstract class called Format with the format

() method shown in the following example:

• Classes that format locale-sensitive information such as dates, numbers, and messages– DateFormat, NumberFormat, and MessageFormat

public abstract class Format … {public final String format(Object obj){//Formats an object and produces a string. }…

}

Formatting ClassesThese formatting methods define the programming interface for formatting locale-sensitive objects into strings and for parsing strings back into objects (the parseObject(…)method). Any string that is formatted by the format(…) method is guaranteed to be parseable by parseObject.If there is no match when parsing, parseObject(String) throws a ParseException, and parseObject(String, ParsePosition) leaves the ParsePosition index member unchanged and returns null.Below hierarchy of Format class.

Format

NumberFormat

ChoiceFormat

DecimalFormat

Format

MessageFormat

Format

DateFormat

SimpleDateFormat

Page 285: Java Programming

Oracle10g: Java Programming 9-15

9-15 Copyright © 2004, Oracle. All rights reserved.

Using the SimpleDateFormat Class

The SimpleDateFormat:• Is a concrete class for formatting and parsing

dates in a locale-sensitive manner• Allows you to start by choosing any user-defined

patterns for date–time formatting• Uses time-pattern string to display the date:

– y year 1996– M month in year July or 07– m minute in hour 30

Example of SimpleDateFormatimport java.text.SimpleDateFormat;

: SimpleDateFormat df = new SimpleDateFormat("dd-MMMM-yyyy"); System.out.println(df.format(new java.util.Date() ));

Format Pattern Result“yyyy.MM.dd G ‘at’ hh:mm:ss z” 1996.07.10 AD at 15:08:56 PDT“EEE, MMM d, “yy” Wed, Jul 10, ’96“hh ‘o”clock’ a, zzzz” 12 o’clock PM, Pacific Daylight Time“K:mm a, z” 0:00 PM, PST“yyyyy.MMMMM.dd GGG hh:mm aaa” 1996.July.10 AD 12:08 PM

Page 286: Java Programming

Oracle10g: Java Programming 9-16

9-16 Copyright © 2004, Oracle. All rights reserved.

Using the MessageFormat Class

The MessageFormat:• Is a concrete class for constructing language

neutral messages, displayed for end users• Takes a set of objects, formats them, and then

inserts the formatted strings into the pattern at the appropriate places

• Differs from other Format classes, in that you create a MessageFormat object

• Is typically set dynamically at run time

Example of MessageFormatMessageFormat provides a means to produce concatenated messages in a language-neutral way. You use this to construct messages displayed for end users.The MessageFormat takes a set of objects, formats them, and then inserts the formatted strings into the pattern at the appropriate places. It differs from the other Format classes in that you create a MessageFormat object with one of its constructors.

Object[] arguments = { new Integer(7), new Date(System.currentTimeMillis()), "a disturbance in the Force" };

String result = MessageFormat.format("At {1,time} on {1,date}, there was {2} on planet

{0,number,integer}.", arguments);

Output: At 12:30 PM on Jul 3, 2053, there was a disturbance in the Force on planet 7.

Page 287: Java Programming

Oracle10g: Java Programming 9-17

9-17 Copyright © 2004, Oracle. All rights reserved.

Using DecimalFormat

The DecimalFormat:• Is a concrete subclass of NumberFormat for

formatting decimal numbers• Allows for a variety of parameters and for

localization to Western, Arabic, or Indic numbers • Uses standard number notation in format

public DecimalFormat(String pattern);

Using the DecimalFormatSpecial characters are used in the parts of the pattern. For example, if you are using the decimal format constructor to create a format pattern for displaying decimal numbers, then the structure of the pattern can be represented by the symbols in the following chart:

Symbol Meaning0 a digit# a digit; zero shows as absent. placeholder for decimal separator, placeholder for grouping separator; separates formats- default negative prefix% multiply by 100 and show as percentageunicode \u2030 multiply by 1000 and show as per milleunicode \\u00A4 currency sign; replaced by currency symbol; if doubled, replaced by

international currency symbol

Page 288: Java Programming

Oracle10g: Java Programming 9-18

9-18 Copyright © 2004, Oracle. All rights reserved.

Guided Practice

1. What is the output of each code fragment?a.

b.

String s = new String("Friday");

if(s == "Friday")

System.out.println("Equal A");

if(s.equals("Friday"))

System.out.println("Equal B");

int num = 1234567;

System.out.println(String.valueOf(num).charAt(3));

Instructor NoteStudents must be able to answer these questions on paper (or interactively, as a class discussion) with reference to the online J2SE documentation.Answers1a. Equal B

s == "Friday" tests whether the string s and the string "Friday" point to exactly the same location in memory. This is not true, so "Equal A" is not printed.

s.equals("Friday") tests whether the string s and the string "Friday" contain exactly the same characters, which is true, so "Equal B" is printed. 1b. 4

String.valueOf(num) converts the integer 1234567 to the string "1234567". "1234567".charAt(3) returns the character at index 3. Indexes always start from zero, so the character at index 0 is 1, and the character at index 3 is 4.

Page 289: Java Programming

Oracle10g: Java Programming 9-19

9-19 Copyright © 2004, Oracle. All rights reserved.

Guided Practice

2. What is the output of each code fragment?a.

b.

String s1 = "Monday";

String s2 = "Tuesday";

System.out.println(s1.concat(s2).substring(4,8));

// s3 begins with 2 spaces and ends with 2 spaces

String s3 = " Monday ";

System.out.println(s3.indexOf("day"));

System.out.println(s3.trim().indexOf("day"));

Instructor NoteAnswers2a. ayTuThe result of s1.concat(s2) is "MondayTuesday"."MondayTuesday".substring(4,8) returns the substring beginning at 4 and ending at 7 (remember that substring(beginIndex, endIndex) returns a substring beginning at beginIndex and ending at endIndex - 1).Counting from the beginning of the string, starting with index 0, gives:

MondayTuesday01234567

Characters 4, 5, 6, and 7 are "a", "y", "T", and "u".2b. 5

3You want to find out the index of the first character of "day" in " Monday ". The first two characters of " Monday " are spaces. Counting from the left, starting with index 0, gives index 5 for "d".The result of " Monday ".trim() is "Monday". Again, counting from the left, starting with index 0, gives index 3 for "d".

Page 290: Java Programming

Oracle10g: Java Programming 9-20

9-20 Copyright © 2004, Oracle. All rights reserved.

Using Regular Expressions

• Matches character sequences against patterns specified by regular expressions

• Includes a Matcher class which is the engine that performs match operations

• Employs a Pattern class to provide a compiled representation of a regular expression

Pattern p = Pattern.compile("a*b");

Matcher m = p.matcher("aaaaab");

boolean b = m.matches();

Using Regular ExpressionsA regular expression is a pattern of characters that describe a set of strings. You can use the java.util.regex package to find, display, or modify some of the occurrences of a pattern in an input sequence.Pattern ClassAn instance of the Pattern class represents a regular expression that is specified in string form in a syntax similar to that used by Perl. A regular expression, specified as a string, must first be compiled into an instance of this class. The resulting pattern can then be used to create a Matcher object that can match arbitrary character sequences against the regular expression. All of the states involved in performing a match resides in the matcher; so, many matchers can share the same pattern.Matcher ClassA matcher is created from a pattern by invoking the pattern’s matcher method. After it is created, a matcher can be used to perform three different kinds of match operations:

• The matches method attempts to match the entire input sequence against the pattern.• The lookingAt method attempts to match the input sequence, starting at the

beginning, against the pattern.• The find method scans the input sequence looking for the next subsequence that

matches the pattern.

Page 291: Java Programming

Oracle10g: Java Programming 9-21

Regular Expression ExamplesString class has new methods matches(regExpr), replaceFirst(regExpr), replaceAll(regExpr) and split(regExpr).Example 1String p = "^[A-Z].*[\\.?!]$"; // ^ and $ irrelevant

String s = "Java is fun!";

System.out.println(s.matches(p)); //returns true. Note: matches(..) always matches entire string

New classes for regular Expressions: java.util.regex.Pattern, java.util.regex.Matcher andjava.util.regex.PatternSyntaxException

Example 2String p = "^[A-Z].*[\\.?!]$";

String s = "Java is fun!";

Pattern pc1 = Pattern.compile(p, Pattern.CASE_INSENSITIVE);

Matcher m1 = pc1.matcher(s);

//Also possible: Pattern.matches(“regExp”,”string”). Less efficient for repeated matches

System.out.println(m1.matches()); //returns true.

Example 3Pattern pc2 = Pattern.compile("\\bis");

Matcher m2 = pc2.matcher("Java is a language. This is fun");

while (m2.find())

System.out.println(m2.start());//2 matches at 5 and 25

m2.reset("John is an actor. His movies are grisly.");

while (m2.find())

System.out.println(m2.start());//1 match at 5 only

Page 292: Java Programming

Oracle10g: Java Programming 9-22

Regular Expression Examples (continued)Example 4Pattern pc2 = Pattern.compile("\\bis");

String frags = pc2.split("Java is a language. This is fun");

for (int i=0; i < frags.length; i++)

System.out.print("\"" + frags[i] + "\"\t");

output:"Java “ " a language. This " " fun"

Flags used by Pattern.compile(String regex, int flags):CASE_INSENSITIVE: Matching is not case sensitive.DOTALL: If set, the “.” character matches any character; otherwise, it matches all characters except the end-of-line character.MULTILINE: If set, the ^ and $ characters match not only the beginning and end of the string but also matches the beginning and end of each line within the string.UNIX_LINES: If set, then only the newline character (‘\n’) is considered a line terminator; otherwise, the line terminators can be \n,\r and \r\n.Special Metacharacters (Short List):\escape character. \\, \n, \r, \t,\f matches \, newline, carriage return, tab, and formfeed respectively.^ matches beginning of string (or line if MULTILINE is set).$ matches end of string (or line if MULTILINE is set).\b matches on a word boundary.xy matches x followed by y.x | y matches either x or y.(…) grouping operator groups into a unit that can be repeated with *,+ or ?Character classes: [a-d] matches a single character ‘a’ through ‘d’.[^a-d] matches any character except a-d.Repetition: x? matches zero or one occurrence of x

x* matches 0 or more occurrences of xx+ matches 1 or more occurrences of x

Page 293: Java Programming

Oracle10g: Java Programming 9-23

9-23 Copyright © 2004, Oracle. All rights reserved.

About System.out.println

Understanding System.out.println()• System is a class in the java.lang package.• out is a public final static (class) variable.

– Declared as a PrintStream object reference• println() is an overloaded method of the

PrintStream class.– PrintStream is a FilterOutputStream that

subclasses OutputStream.• System.err is also provided as a PrintStream

object reference to write to standard error.

Understanding System.out.println()The principal way in which your Java program has been exposed to the external environment in previous lessons is through System.out.println() where you have sent data to the console output.Most Java programs execute in an environment that has a notion of the console, to which both output and errors can be directed. If you run your program from a UNIX or DOS command-line shell, the Java run-time environment binds the console to the shell or command window. Two of the three System items, standard output and standard err, are derived from the PrintStream class. The third System stream is an in, which typically reads input entered by the user.public final static PrintStream out = …; // standard output public final static PrintStream err = …; // standard error

About the PrintStream ClassThe PrintStream class, a subclass implementation of an OutputStream, allows you to print data in a platform-independent way, such as primitive values and objects formatted as strings (that is, in their textual representations). This is achieved by calling one of the overloaded implementations of the println() methods defined in the PrintStreamclass.

Page 294: Java Programming

Oracle10g: Java Programming 9-24

9-24 Copyright © 2004, Oracle. All rights reserved.

About OutputStream and PrintStream

• OutputStream provides basic byte I/O operations:– write(int b) to write one byte– write(byte[] b) to write an array of bytes– write(byte[] b,int off,int len) to write a

subset of an array of bytes– flush() and close() to flush and close the stream

• PrintStream is a subclass of (Filter)Output Stream, which– Converts Unicode to environment byte encoding– Terminates lines in a platform-independent way– Flushes the output stream

About OutputStream and PrintStreamThe OutputStream class provides basic methods for low-level byte I/O operations. The methods are:• write(int b) to write one byte• write(byte[] b) to write an array of bytes• write(byte[] b, int off, int len) to write a subset of an array of bytes• flush() and close() flushes and closes the stream

Using an OutputStream object is not very useful for printing text terminated by a new line in a platform-independent way. However, PrintStream, a subclass of FilterOutputStream, extends the basic I/O capabilities of OutputStream in the following ways:

• It converts Java Unicode strings into the byte encoding of the environment, such that you can see the text in a readable format.

• It terminates a line in a platform-independent way. In JDK releases before 1.2, new lines written were not platform independent.

• It flushes the stream. In general, there is no guarantee that data written will be visible immediately. Flushing the stream explicitly requests that the data be displayed now.

Page 295: Java Programming

Oracle10g: Java Programming 9-25

9-25 Copyright © 2004, Oracle. All rights reserved.

What Is Object Serialization?

Serialization is a lightweight persistence mechanism for saving and restoring streams of bytes containing primitives and objects.• A class indicates that its instances can be

serialized by:– Implementing java.io.Serializable or

java.io.Externalizable interface– Ensuring that all its fields are serializable, including

other objects referenced– Using the transient modifier to prevent fields

from being saved and restored

Object SerializationObject serialization is the process of encoding an object, and the objects it references, into a stream of bytes. Object serialization also provides mechanisms for reconstructing the object, and its referenced objects from the stream.Serialization can be used for lightweight persistence (for example, permanent storage in file on disk) or used for communication between distributed Java applications.The object saved and the relationship it has with other objects, via object references, is called an object graph. When an object is saved and restored, the objects it references must also be maintained. By default, when an object is stored, all of the objects that are reachable from that object are stored as well; that is, the object graph is stored.For an object to be saved to and restored from a stream, its class can implement one of the following:

• The java.io.Serializable interface• The java.io.Externalizable interface

Only the identity of the class of an Externalizable instance is written in the serialization stream and it is the responsibility of the class to save and restore the contents of its instances.

Page 296: Java Programming

Oracle10g: Java Programming 9-26

Serialization: Examplepackage serdemo; import java.io.ObjectInputStream; import java.io.FileInputStream; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.FileOutputStream;

public class SerializationDemo { public static void main(String[] args) { Person p1 = new Person("John", 'M', null); Person p2 = new Person("Mary", 'F', p1); p1.setSpouse(p2); try{

ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("person_graph.ser") );

os.writeObject(p1); //entire object graph is written os.close();

ObjectInputStream is = new ObjectInputStream(new FileInputStream("person_graph.ser") );

Person p3 = (Person) is.readObject(); //entire object graph is read

is.close(); System.out.println(p3); Person p4 = p3.getSpouse(); //Object obtained from graph. System.out.println(p4);

} catch(Exception ioe){

ioe.printStackTrace(); } }//end main()

} class Person implements Serializable{ private String name; private char gender; private Person spouse;

Page 297: Java Programming

Oracle10g: Java Programming 9-27

Serialization: Example (continued)Person(){ } Person(String name, char gender, Person spouse){

setName(name); setGender(gender); setSpouse(spouse);

} public String getName() { return name;

}

public void setName(String newName) { name = newName;

}

public char getGender() { return gender;

}

public void setGender(char newGender) { gender = newGender;

}

public Person getSpouse() { return spouse;

}

public void setSpouse(Person newSpouse) { spouse = newSpouse;

} public String toString(){

return "\nName=" + name + "\nGender=" + gender + "\nSpouse=" + getSpouse().getName();

} }

Page 298: Java Programming

Oracle10g: Java Programming 9-28

9-28 Copyright © 2004, Oracle. All rights reserved.

Serialization Streams, Interfaces,and Modifiers

• Example of implementing java.io.Serializable– Mark fields with the transient modifier to prevent

them from being saved; that is, to protect the information.

• Write object with java.io.ObjectOutputStream.• Read object with java.io.ObjectInputStream.

import java.io.Serializable;public class Member implements Serializable {

private int id;private String name;private transient String password;…

}

Serialization Streams, Interfaces, and ModifiersAs already stated, for an object to be serialized, its class must implement the Serializable interface, as shown in the slide, or the Externalizable interface. Implementing the Serializable interface does not require that you write any methods and acts as a marker to the Java serialization system that the object can be serialized.Use the transient modifier for variables whose values you do not want saved when the object contained is serialized (for example, to prevent sensitive information from being stored). However, if a variable in your serializable object references another object that is not serializable, then that variable must be made transient; otherwise, serialization will fail. The java.io.NotSerializableException exception is thrown if serialization fails.Stream for Writing ObjectsWriting objects to a stream is accomplished by using the ObjectOutputStream class, whose constructor accepts another OutputStream. Thus, wrapping another stream in an ObjectOutputStream is quite common. For example, wrapping a FileOutputStream in an ObjectOutputStream stores objects in a file.Stream for Reading ObjectsReading objects from a stream is possible by using the ObjectInputStream class whose constructor accepts another InputStream.

Page 299: Java Programming

Oracle10g: Java Programming 9-29

9-29 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:• Create strings in Java• Use the conversion methods that are provided by

the predefined wrapper classes• Use the StringBuffer class for manipulating

character data• Manipulate objects by using the DateFormat,

DecimalFormat, and MessageFormat classes

Page 300: Java Programming

Oracle10g: Java Programming 9-30

9-30 Copyright © 2004, Oracle. All rights reserved.

Practice 9: Overview

This practice covers:• Creating a new Order class• Populating and formatting orderDate• Formatting existing orderDate values with the

GregorianCalendar class• Formatting orderTotal

Practice 9: OverviewNote: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les08 directory, load up the OrderEntryWorkspaceLes08 workspace, and continue with this practice.In this practice, you use the GregorianCalendar class. This class allows you to get a date value for a specific point in time. You can specify a date and time and see the behavior of your class respond to that specific date and time. The class can then be based on the values you enter, not just the system date and time.Viewing the model: To view the course application model up to this practice, load the OrderEntryWorkspaceLes08 workspace. In the Applications – Navigator node, expand the OrderEntryWorkspaceLes08 – OrderEntryProjectLes08 -Application Sources – oe, and double-click the UML Class Diagram1 entry. This diagram displays all the classes created to this point in the course.

Page 301: Java Programming

Oracle10g: Java Programming 9-31

Practice 9: Using Strings, StringBuffer, Wrapper, and Text-Formatting ClassesGoalThe goal of this practice is to modify the Util class to provide generic methods to support formatting the order details, such as presenting the total as a currency and controlling the date string format that is displayed. This should give you exposure in using some of the java.text formatting classes.Note: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les08 directory, load the OrderEntryLes08 workspace, and continue with this practice.Your AssignmentYou create a method called toMoney() to return a currency formatted string for the order total. You also create a method called toDateString() that formats the date in a particular way. You then modify the Order class to use these methods to alter display of order details, such as the order date and total.Add Formatting Methods to the Util Class

1. Create a static method called toMoney() that accepts an amount as a doubleand returns a String.

a. Add the following import statement to the class:

import java.text.DecimalFormat;

b. Add the following toMoney() method code to the class, to format a double:

public static String toMoney(double amount) {DecimalFormat df = new DecimalFormat("$##,###.00");return df.format(amount);

}

c. Save and compile the Util class.2. Add the following static toDateString() method to format a date.

a. Add the following import statements to the Util class:

import java.util.Date;import java.text.SimpleDateFormat;

b. Use the following code for your method:

public static String toDateString(Date d) {SimpleDateFormat df =new SimpleDateFormat("dd-MMMM-yyyy");

return df.format(d);}

c. Save and compile the Util class.

Page 302: Java Programming

Oracle10g: Java Programming 9-32

Practice 9: Using Strings, StringBuffer, Wrapper, and Text-Formatting Classes (continued)

3. In this step of the practice, you use the GregorianCalendar class. This class allows you to get a date value for a specific point in time. You can specify that date and time, see the behavior of your class based on the values you enter, not just the system date and time.Create another static method called getDate() that accepts three integers representing the day, month, and year, and returns a java.util.Date object representing the specified date (For Example: month = 1 which represents January on input). Because many of the methods in the Date class that could have been used are deprecated, you use the GregorianCalendar class to assist with this task.

a. Import the java.util.GregorianCalendar class.b. Use the following for the method:

public static Date getDate(int day,int month,int year){

// Decrement month, Java interprets 0 as January.GregorianCalendar gc =

new GregorianCalendar(year, --month, day);return gc.getTime();

}c. Save and compile the Util class.

Use the Util Formatting Method in the Order Class4. In the Order class, modify the toString() method to use the Util class methods

toMoney() and toDateString() altering the display format..a. In the toString() method, replace the return value with the following text.

When shipMode is not specified, you do not need to display the information for "Shipped: ".

return "Order: " + id + " Date: " + Util.toDateString(orderDate) +" Shipped: " + shipMode +" (" + Util.toMoney(getOrderTotal()) + ")";

b. Save and compile the Order class, and then run the OrderEntry class to viewthe changes to the displayed order details.

c. Now import the java.text.MessageFormat class in the Order class, and use this class to format the toString() return value, as follows:import java.text.MessageFormat;Object[] msgVals = {new Integer(id),

Util.toDateString(orderDate), shipMode,Util.toMoney(getOrderTotal()) };

return MessageFormat.format("Order: {0} Date: {1} Shipped: {2} (Total: {3})",

msgVals);

Page 303: Java Programming

Oracle10g: Java Programming 9-33

Practice 9: Using Strings, StringBuffer, Wrapper, and Text-Formatting Classes (continued)

d. Save and compile the Order class, and then run the OrderEntry class to view the results of the displayed order. The change to the displayed total must appear.

Optional Extra CreditUse Formatting in OrderItem Class

5. In the OrderItem class, modify the toString() method to use the Util.toMoney() methods to alter the display format of item total.

a. In the toString() method, replace the return statement with the following:

return lineNbr + " " + quantity + " " +Util.toMoney(unitPrice);

b. Save and compile the OrderItem class, and then run the OrderEntry class to view the changes to the order item total.

Use Util.getDate() to Set the Order Date6. In the OrderEntry class, alter the second order object creation statement to use the

Util.getDate() method to provide the value for the first argument in the constructor. Choose the previous day’s date for the values of the day, month, and year arguments supplied to the Util.getDate() method.

a. The call to the constructor should look like:

Order order2 =new Order(Util.getDate(7, 3, 2002), "overnight");

b. Save, compile, and run the OrderEntry class to confirm that the orderdate has been set correctly.

Page 304: Java Programming
Page 305: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Reusing Code with Inheritanceand Polymorphism

Schedule: Timing Topic80 minutes Lecture30 minutes Practice

110 minutes Total

Instructor NoteThis lesson reviews the inheritance and polymorphism properties that were introduced in the lesson titled “Defining Object-Oriented Principles,” but from a Java-language point of view.

Page 306: Java Programming

Oracle10g: Java Programming 10-2

10-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Define inheritance• Use inheritance to define new classes• Provide suitable constructors• Override methods in the superclass• Describe polymorphism• Use polymorphism effectively

Lesson AimThis lesson shows how to extend an existing class in Java, and illustrates the power of polymorphism in object-oriented programs. You learn how to extend existing classes to meet specific application needs. You also learn how to override superclass methods to fine-tune object characteristics and behaviors.

Page 307: Java Programming

Oracle10g: Java Programming 10-3

10-3 Copyright © 2004, Oracle. All rights reserved.

Key Object-Oriented Components

• Inheritance• Constructors referenced by subclass• Polymorphism• Inheritance as an OO fundamental

InventoryItem

Movie Game Vcr

Superclass

Subclasses

Key Object-Oriented ComponentsWhat Is Inheritance?Inheritance defines a relationship between classes where one class shares the data structure and behaviors of another class. Inheritance is a valuable technique because it enables and encourages software reuse by allowing you to create a new class based on the properties of an existing class. As a result, the developer is able to achieve greater productivity than would otherwise be possible.Inheritance and ConstructorsConstructors are blocks of code that are executed when an object of that class is created. By using an inheritance model, each subclass has access to the superclass’s constructor. Any common constructor code can be put in the superclass constructor and called by the subclass. This technique minimizes the need for duplicated code and provides for consistent object creation.PolymorphismPolymorphism describes the ability of Java to execute a specific method based on the object reference that is used in the call. By using this technique, you can define a method in the superclass and override it in the appropriate subclass. You can now write method calls to the superclass, and if the method is overridden in a subclass, then Java automatically calls the right method. This is a very powerful construct that you can use to define superclass methods before knowing the details of any subclasses.

Page 308: Java Programming

Oracle10g: Java Programming 10-4

10-4 Copyright © 2004, Oracle. All rights reserved.

Example of Inheritance

• The InventoryItem class defines methods and variables.

• Movie extends InventoryItem and can:– Add new variables – Add new methods– Override methods in InventoryItem class

InventoryItem

Movie

The InventoryItem ClassThe InventoryItem class defines the attributes and methods that are relevant for all kinds of inventory items. The attributes and methods may include:

• Attributes, such as the date of purchase, purchase cost, and condition• Methods, such as calculating a deposit, changing the condition, and setting the price

Dealing with Different Types of InventoryItemDepending on what you are trying to do in your program, you may need to represent a specific type of InventoryItem in a particular way. You can use inheritance to define a separate subclass of InventoryItem for each different type of InventoryItem. For example, you may define classes such as Movie, Game, and Vcr.Each subclass automatically inherits the attributes and methods of InventoryItem, but can provide additional attributes and methods as necessary. For example, the Movie class may define the following additional attributes and methods:

• Attributes, such as the title of the movie, the director, and the running length• Methods, such as reviewing the movie and setting the rating

Subclasses can also override a method from the superclass if they want to provide more specialized behavior for the method. In this example, the movie could override the InventoryItem calculating a deposit method. A movie may have an additional amount calculated into the deposit.

Page 309: Java Programming

Oracle10g: Java Programming 10-5

10-5 Copyright © 2004, Oracle. All rights reserved.

Specifying Inheritance in Java

• Inheritance is achieved by specifying which superclass the subclass extends.

• Movie inherits all the variables and methods of InventoryItem.

• If the extends keyword is missing, then the java.lang.Object is the implicit superclass.

public class InventoryItem {

}public class Movie extends InventoryItem {

}

Specifying Inheritance in JavaWhen you define a subclass, you must provide code only for the features in the subclass that are different from those of the superclass. In a very real way, the subclass is extending the superclass. The syntax for specifying inheritance in Java makes use of the extends keyword. For example:

public class InventoryItem {// Definition of the InventoryItem class

}public class Movie extends InventoryItem {

// Additional methods and attributes, to distinguish a// Movie from other types of InventoryItem

}Characteristics of Inheritance in Java

If you have experience with another OO language, such as C++, then note that Java allows only single inheritance. In other words, a class can specify only one immediate superclass. Also, remember that all classes in Java are automatically inherited from the root class called Object, which sits at the top of the inheritance tree. If a class does not specify an explicit superclass, as is the case with InventoryItem in the slide, then the class is deemed to extend directly from Object, as if it were defined as follows:

public class InventoryItem extends Object { …The java.lang.Object class is the root class for all the classes in Java.

Page 310: Java Programming

Oracle10g: Java Programming 10-6

10-6 Copyright © 2004, Oracle. All rights reserved.

Defining Inheritanceby Using Oracle JDeveloper 10g

• When specifying a class, JDeveloper asks for its superclass:

• JDeveloper generates the code automatically.

Defining Inheritance by Using Oracle JDeveloper 10gTo define a new class that inherits from another class, follow these steps:

1. Select File > New from the Main menu bar.2. A dialog box is displayed that prompts you for the kind of feature you want to create.

Select the “General” category, and double-click the Java Class icon. This launches the New Class dialog box.

3. Specify the name for your class, and browse to the name of the superclass that you want to extend. In the Browse window, JDeveloper brings up all packages (and the classes that are contained inside them) that it currently holds in memory. The default superclass name is java.lang.Object; that is, the Object class that is located in the java.lang package.

4. Click the OK button. JDeveloper generates a skeleton class to get you started, as follows:package practice17;public class Movie extends InventoryItem {}

Page 311: Java Programming

Oracle10g: Java Programming 10-7

10-7 Copyright © 2004, Oracle. All rights reserved.

What Does a Subclass ObjectLook Like?

A subclass inherits all the instance variables of itssuperclass.

Movie

titlelength

pricecondition

public class

Movie extends InventoryItem {

private String title;

private int length; …

}

public class InventoryItem {

private float price;

private String condition; …

}

Variables in Superclass and SubclassThe superclass defines the variables that are relevant for all kinds of InventoryItem, such as the purchase date and condition. The subclass, Movie, inherits these variables for free and has to specify only the Movie-specific variables, such as the title.What Does an Object Look Like?If you create a plain InventoryItem object, then it contains only the instance variables that are defined in InventoryItem :InventoryItem i = new InventoryItem (…);

// an InventoryItem has a price and conditionHowever, if you create a Movie object, then it contains four instance variables: the two inherited from InventoryItem, plus two added in Movie:

Movie m = new Movie(…); // A Movie object has a price and condition, because a// Movie is a kind of InventoryItem.// The Movie object also has a title and length.

Declaring Instance Variables as privateInstance variables must normally be declared as private, which means that instances of subclasses inherit the values, but cannot access them directly. You must define methods to access private variables. You can define methods in the subclass or inherit them from the superclass.

Page 312: Java Programming

Oracle10g: Java Programming 10-8

10-8 Copyright © 2004, Oracle. All rights reserved.

Default Initialization

• What happens when a subclass object is created?

• If no constructors are defined:– First, the default no-arg

constructor is called in the superclass.

– Then, the default no-arg constructor is called in the subclass.

Movie movie1 = new Movie(); Movie

titlelength

pricecondition

Default Provision of ConstructorsA class does not inherit any constructors from its superclass. Therefore, the InventoryItem class has only the constructors explicitly declared in its definition or a default no-arg constructor if there are no other constructors at all.What Happens When a Subclass Object Is Created?The example in the slide creates a movie1 object. For the moment, assume that neither the Movie class nor the InventoryItem class provides any constructors; all they have is the default no-arg constructor that is provided automatically by Java.What happens when a movie1 object is created? Objects are always constructed from the top class down to the bottom class; that is, from the Object class down to the class that is being instantiated using new. This ensures that a constructor in a subclass can always rely on proper construction of its superclass. In the example, when you create a movie1 object, the no-arg constructor of InventoryItem is called first to initialize the InventoryItem instance variables with default values. The price is set to 0 and condition is set to its default: excellent. After the superclass is initialized, the no-arg constructor of Movie is then called to initialize the title and length instance variable with default values.

Page 313: Java Programming

Oracle10g: Java Programming 10-9

10-9 Copyright © 2004, Oracle. All rights reserved.

The super Reference

• Refers to the base, top-level class• Is useful for calling base class constructors• Must be the first line in the derived class

constructor• Can be used to call any base class methods

The super ReferenceThe super reference is useful only when a class has an ancestor. A subclass inherits all of the superclass methods and variables as well as creates its own. Methods in the superclass may be overridden in the subclass by creating methods with the same name and signature in the subclass. You can use the super keyword to specifically access methods in the superclass even though they have been overridden in the subclass.Calling ConstructorsOne of the more common uses of super is to invoke a constructor provided by the superclass. When the superclass was designed, it probably had a constructor to ensure proper initialization of any new objects. Because a subclass inherits all of the superclass variables, they must be initialized for subclass objects as well.The syntax rule is that super() must be the first line in the subclass constructor. Add the super reference within the subclass constructor to access the superclass constructor:

- subclass() { // constructor for the subclass- super(); // call the superclass constructor- … ; // subclass specific constructor code- }

The super keyword may also be used to call any superclass methods.

Page 314: Java Programming

Oracle10g: Java Programming 10-10

10-10 Copyright © 2004, Oracle. All rights reserved.

The super Reference Example

public class InventoryItem {

InventoryItem(String cond) {

System.out.println("InventoryItem");

}

}

class Movie extends InventoryItem {

Movie(String title) {

Movie(String title, String cond)

{super(cond);

System.out.println("Movie");

}

}

Base class constructor

Calls baseclass

constructor

The super Reference ExampleIn the example, there are initialization routines that must happen for all inventory items. Those routines are placed in the InventoryItem constructor. These routines must be used regardless of the type of InventoryItem that is being constructed, whether it is a Movie, Game, or a Book.There are also constructors in each of the subclasses to take care of subclass-specific routines. The Movie constructor reuses the InventoryItem constructor by referencing it with the super keyword. This statement is the first statement in the Movie constructor and may be followed by whatever other statements are necessary to fully construct a Movieobject.

Page 315: Java Programming

Oracle10g: Java Programming 10-11

10-11 Copyright © 2004, Oracle. All rights reserved.

Using Superclass Constructors

Use super() to call a superclass constructor:

public class InventoryItem {

InventoryItem(float p, String cond) {

price = p;

condition = cond;

} … public class Movie extends InventoryItem {

Movie(String t, float p, String cond) {

super(p, cond);

title = t;

} …

Nondefault Initialization with InheritanceThe superclass and subclass often have constructors that take arguments. For example, InventoryItem may have a constructor that takes arguments to initialize price and condition:

public InventoryItem (float p, String cond) {

price = p;

condition = cond;

}

Likewise, the Movie class may have a constructor that takes enough arguments to initialize its attributes. This is where things get interesting. A Movie object has three attributes: price and condition that are inherited from InventoryItem, plus title, which is defined in Movie itself. The Movie constructor may therefore take three arguments:

public Movie(float p, String cond, String t) { … }

Page 316: Java Programming

Oracle10g: Java Programming 10-12

Nondefault Initialization with Inheritance (continued)Rather than initializing price and condition explicitly, all the Movie constructor has to do is call the superclass constructor. This can be achieved by using the super keyword; the call to super(…) must be the first statement in the constructor.

public Movie (float p, String cond, String t) {

super (p, cond); // Call superclass constructor

title = t; // Initialize Movie-specific attributes

If you do not explicitly call super(…), then the compiler calls the superclass no-arg constructor by default. If the superclass does not have a no-arg constructor, then a compiler error occurs.

Page 317: Java Programming

Oracle10g: Java Programming 10-13

10-13 Copyright © 2004, Oracle. All rights reserved.

Specifying Additional Methods

• The superclass defines methods for all types of InventoryItem.

• The subclass can specify additional methods that are specific to Movie.

public class InventoryItem {

public float calcDeposit()…

public String calcDateDue()…

… public class Movie extends InventoryItem {

public void getTitle()…

public String getLength()…

Methods in the Superclass and SubclassThe slide shows some of the methods that are declared in the superclass and the subclass. The superclass defines the methods that are relevant for all kinds of InventoryItem, such as the ability to calculate a deposit or the due date for the item. The subclass, Movie, inherits these methods from the superclass and has to add only the Movie-specific methods, such as getting the title and getting the length.

Page 318: Java Programming

Oracle10g: Java Programming 10-14

Methods in the Superclass and Subclass (continued)What Methods Can Be Called?When you create an object, you can call any of its public methods plus any publicmethods that are declared in its superclass. For example, if you create an InventoryItemobject, then you can call the public methods that are defined in InventoryItem, plus any public methods that are defined in its superclass, Object:InventoryItem i = new InventoryItem (…);

i.getId(); // Call a public method in InventoryItem

i.getClass(…); // Call a public method in Object

If you create a Movie object, then you can call any public methods that are defined in Movie, InventoryItem, or Object:

Movie m = new movie(…); // Create a Movie object

m.getTitle(); // Call a public method in Movie

m.getId(); // Call a public method in InventoryItem

m.getClass(…); // Call a public method in Object

Page 319: Java Programming

Oracle10g: Java Programming 10-15

10-15 Copyright © 2004, Oracle. All rights reserved.

Overriding Superclass Methods

• A subclass inherits all the methods of its superclass.

• The subclass can override a method with its own specialized version.– The subclass method must have the same signature

and semantics as the superclass method.

public class InventoryItem {

public float calcDeposit(int custId) {

if …

return itemDeposit;

}

public class Vcr extends InventoryItem {

public float calcDeposit(int custId) {

if …

return itemDeposit;

}

Overriding Superclass MethodsA subclass inherits all of the methods of its superclass. However, a subclass can modify the behavior of a method in a superclass by overriding it, as shown in the slide.To override a superclass method, the subclass defines a method with exactly the same signature and return type as a method somewhere above it in the inheritance hierarchy. The method in the subclass effectively hides the method in the superclass. It is important to make sure that the method in the subclass has the return type and signature as the one that it is overriding.Which Method Is Called?In the example that is shown in the slide, the InventoryItem class provides a calcDeposit() method, and the Vcr class overrides it with a more specialized version. If you create an InventoryItem object and call calcDeposit(), then it calls the InventoryItem version of the method. If you create a Vcr object and call calcDeposit(), then it calls the Vcr version of the method.

Page 320: Java Programming

Oracle10g: Java Programming 10-16

Overriding Superclass Methods (continued)Overriding and OverloadingDo not confuse “method overloading” with “method overriding”:

• Method overloading is a process by which you define multiple methods with different signatures. Overloaded methods are resolved at compile time, based on the arguments that you supply.

• Method overriding is a process by which you provide a method with exactly the same signature as a method in a superclass. Overridden methods are resolved at run time, unlike overloaded methods.

Page 321: Java Programming

Oracle10g: Java Programming 10-17

10-17 Copyright © 2004, Oracle. All rights reserved.

Invoking Superclass Methods

• If a subclass overrides a method, then it can still call the original superclass method.

• Use super.method() to call a superclass method from the subclass.

public class InventoryItem {

public float calcDeposit(int custId) {

if …

return 33.00;

}

public class Vcr extends InventoryItem {

public float calcDeposit(int custId) {

itemDeposit = super.calcDeposit(custId);

return (itemDeposit + vcrDeposit);

}

Invoking Superclass MethodsCalling an Overridden Method from the Client ProgramAs previously mentioned, when a subclass overrides a method in a superclass, it hides that method. For example, if the client program creates a Vcr object and calls the calcDeposit() method, then it always executes the Vcr version of calcDeposit():

Vcr v = new Vcr(…); // Create a Vcr object

v.calcDeposit(); // Executes Vcr calcDeposit() method

Page 322: Java Programming

Oracle10g: Java Programming 10-18

Invoking Superclass Methods (continued)Calling an Overridden Method from the SubclassWithin the Vcr version of calcDeposit(), you can call the InventoryItem version of calcDeposit() that is defined in the superclass by using the super keyword. The super keyword is similar to this, except that it acts as a reference to the current object as an instance of its superclass.Calling an overridden superclass method by using super helps to avoid duplicating the code that is contained in the overridden method; by reducing the amount of duplicate code, the code is more consistent and easier to maintain.The syntax for an example of overriding a method is:

super.calcDeposit();

Working in JDeveloperYou can take advantage of JDeveloper’s built-in functionality to see all the methods of a given class, plus its inherited methods (taken from the superclass). To do this, select the class (for example, Game, which extends InventoryItem), right-click and select Class Editor, and then click the Methods tab (the third tab from the left). Toggle the Show Inherited Methods check box to display methods. The same behavior is available in the Fields tab.

Page 323: Java Programming

Oracle10g: Java Programming 10-19

10-19 Copyright © 2004, Oracle. All rights reserved.

Example of Polymorphism in Java

Recall that the java.lang.Object class is the root class for all Java Class.• Methods in the Object class are inherited by its

subclasses.• The toString() method is most commonly

overridden to achieve polymorphic behavior.• For example: public class InventoryItem {

public String toString() {

return "InventoryItem value";

}

}InventoryItem item = new InventoryItem();

System.out.println(item); // toString() called

Polymorphism and the toString MethodPolymorphism returns a string representation of the object. In general, the toStringmethod returns a string that “textually represents” this object. The result must be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.The toString method for the Object class returns a string consisting of the name of the class of which the object is an instance, the “@” (at sign) character, and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:getClass().getName() + '@' + Integer.toHexString(hashCode())

Page 324: Java Programming

Oracle10g: Java Programming 10-20

10-20 Copyright © 2004, Oracle. All rights reserved.

Treating a Subclass as Its Superclass

A Java object instance of a subclass is assignable to its superclass definition.• You can assign a subclass object to a reference

that is declared with the superclass.

• The compiler treats the object via its reference (that is, in terms of its superclass definition).

• The JVM run-time environment creates a subclass object, executing subclass methods, if overridden.

public static void main(String[] args) {

InventoryItem item = new Vcr();

double deposit = item.calcDeposit();

}

Subclass and Its SuperclassAny Java subclass object can be assigned to an object reference variable that is declared as its superclass, or as the same class as itself. The slide example shows that a Vcr object is assigned to the item object reference, which is declared as an InventoryItem. The Vcr must previously be declared as a class that extends InventoryItem. The Java compiler accepts this as valid syntax. This is necessary for polymorphism. There are two ways to look at the code example:The Compiler ViewThe compiler sees the Vcr object as if it were a “kind of” InventoryItem. Therefore, all methods that are called from the item object reference can only be those defined in the InventoryItem class, because item is defined as an InventoryItem. In essence, you are writing generic code to deal with common functionality of any kind of inventory item object.The Run-Time ViewAt run time, JVM dynamically creates the Vcr object. Thus, when you call a method, such as item.calcDeposit(), it is the Vcr’s calcDeposit() method that is invoked if it overrides its superclass definition. Otherwise, the inherited method is called. JVM uses a run-time type checking mechanism to ensure that the call is valid; otherwise, it throws an exception.

Page 325: Java Programming

Oracle10g: Java Programming 10-21

10-21 Copyright © 2004, Oracle. All rights reserved.

Browsing Superclass Referencesby Using Oracle JDeveloper 10g

Oracle JDeveloper makes it easy to browse the contents of your superclass.

3

1

2

Browsing Superclass References by Using Oracle JDeveloper 10gYou can use the structure pane on the bottom left of JDeveloper to browse the contents of any of your superclass references. The following sections describe what to do:

1. Select your class in the navigation pane.The structure pane at the top left of the navigation pane lists all the classes in your project. Select the subclass that you want to start with, such as Individual.

2. Select the superclass in the structure pane.The structure pane at the bottom left of the navigation pane lists all the methods, variables, and constructors for the current class. It also contains an icon to represent the superclass, which in this case is Customer.

3. View the superclass reference in the subclass code.Select the extends superclass text in the Structure pane (in this case, extendsCustomer) and the Code Editor displays the reference.

Page 326: Java Programming

Oracle10g: Java Programming 10-22

10-22 Copyright © 2004, Oracle. All rights reserved.

Acme Video and Polymorphism

• Acme Video started renting only videos.• Acme Video added games and Vcrs.• What is next?• Polymorphism solves the problem.

Acme Video and PolymorphismAcme Video started as a simple video rental business that only rented videos. As business began to improve, Acme Video decided to branch out and add video games to its inventory. It soon started getting requests for Vcrs and for video game devices.Each of the different items Acme is now renting has unique properties, and it handles each type in a slightly different manner. For example, it requires a deposit on the Vcrs and video game devices, but not on videos and games. The deposit is based on the type of equipment and the customer. Regular, established customers with good credit are not required to leave a deposit, whereas new customers are.When the customer checks out, Acme must determine the price of the items as well as any required deposit. Its application must be flexible enough to accept new types of items without having to change or recompile existing code each time its business is expanded. It accomplishes this goal by using Java’s polymorphic abilities.Acme designed the ShoppingBasket class to simply accept and process InventoryItems, whatever type they may be. It then allows Java determine the type of the item and call the correct methods based on that type.By using this technique, Acme can add as many new item types as you need without having to change or recompile existing code.

Page 327: Java Programming

Oracle10g: Java Programming 10-23

10-23 Copyright © 2004, Oracle. All rights reserved.

ShoppingBasket

Using Polymorphism for Acme Video

void addItem(InventoryItem item) {

// this method is called each time

// the clerk scans in a new item

float deposit = item.calcDeposit();

}

InventoryItem

Vcr Movie

calcDeposit(){…}

calcDeposit(){…}calcDeposit(){…}

Using Polymorphism for Acme VideoWhen Acme designed its video rental application, it did not know all the types of InventoryItem that would be rented in the long term. In non-OO programming, this would create a problem that would be solved by modifying code each time a new type was added.In Java, you can use polymorphism to solve the problem. Here’s how you can do it:The calcDeposit() method in the InventoryItem class is overridden in the Vcrand Movie classes to provide object-specific calculation logic. The ShoppingBasketclass includes an addItem(InventoryItem item) method that calls the calcDeposit() method by using an InventoryItem object.

Page 328: Java Programming

Oracle10g: Java Programming 10-24

Using Polymorphism for Acme Video (continued)At run time, Java interrogates the argument to determine its actual object type and determines whether the type has an overriding method. If it does, then Java uses the subclass method in place of the superclass method.For example, if movie is a variable of type Movie and Vcr is a variable of type Vcr:addItem(movie); // calls the Movie version of calcDeposit()addItem(vcr); // calls the Vcr version of calcDeposit()

The addItem method accepts any kind of InventoryItem object, including the plug-compatible subclass objects.The significance is that the ShoppingBasket or InventoryItem classes do not need to change as new InventoryItem types are added to the business. The OO-designed code will continue to work.

Page 329: Java Programming

Oracle10g: Java Programming 10-25

10-25 Copyright © 2004, Oracle. All rights reserved.

Using the instanceof Operator

• You can determine the true type of an object by using an instanceof operator.

• An object reference can be downcast to the correct type, if necessary.

public void aMethod(InventoryItem i) {

if (i instanceof Vcr)

((Vcr)i).playTestTape();

}

The instanceof OperatorYou can use the instanceof operator to determine the type of an object at run time. It is useful in situations where you need to call some subclass-specific operation on an object, but you must first verify that the object is the correct type.The syntax of the instanceof operator is as follows:

objectRef instanceof classNameThe instanceof operator returns a Boolean value. If the object that is referred to by objectRef is an instance of the specified className, or one of its subclasses, then the instanceof operator returns true. Otherwise, it returns false.ExampleThe method in the slide takes an object reference whose compile-time type is declared as InventoryItem. However, at run time, the object that is passed into the method may be any kind of InventoryItem, such as Vcr, Movie, or Game.Inside the method, you use instanceof to test whether you have a Vcr object. If so, then you convert the compile-time type of the object reference into the Vcr type, and then call a Vcr-specific method. This is often called downcasting.DowncastingThe downcast is necessary in this example. Without it, the compiler allows you to call only those methods that are defined in the InventoryItem class. Having said that, you must use downcasting sparingly. There are usually alternative designs that obviate the need for excessive downcasting.

Page 330: Java Programming

Oracle10g: Java Programming 10-26

10-26 Copyright © 2004, Oracle. All rights reserved.

Limiting Methods and Classes with final

• You can mark a method as final to prevent it from being overridden.

• You can mark a whole class as final to prevent it from being extended.

public final class Color {

}

public final boolean checkPassword(String p) {

}

final MethodsMethods and classes are made final for two primary reasons: security and optimization.If a method is performing some vital operation, such as identity validation or authorization checking, then it must be declared final to prevent anyone from overriding the method and circumventing your security checks. Many of the methods that are defined in java.net classes are final. For example,

final ClassesIf you declare a class as final, then it can never be extended by any other class. This is a strong design statement that the class is sufficient to cater to all current and future requirements. The implication is clear: You do not even need to think about inheriting from this class. For example, the Color class in java.awt is declared final.

final Classes and final Methods Yield More Efficient Codefinal classes enable the compiler to produce more efficient code. Because a final class cannot be extended, if the compiler encounters an object reference of that type, and you call a method by using that object reference, then the compiler does not need to perform run-time method binding to cater to any subclasses that may have overridden the method. Instead, the compiler can perform static binding; that is, the compiler can decide which method to call and avoid the overhead of run-time polymorphic lookup.This is true for individual final methods as well. If you call a final method anywhere in your program, then the compiler can call that method statically, without worrying about whether the method may be overridden by some subclass.

Page 331: Java Programming

Oracle10g: Java Programming 10-27

10-27 Copyright © 2004, Oracle. All rights reserved.

Ensuring Genuine Inheritance

• Inheritance must be used only for genuine “is a kind of” relationships:– It must always be possible to substitute a subclass

object for a superclass object.– All methods in the superclass must make sense in

the subclass.• Inheritance for short-term convenience leads to

problems in the future.

Inheritance Represents an “Is-a-Kind-of” RelationshipUse inheritance only to model a genuine “is a kind of” relationship. In other words, do not use inheritance unless all of the inherited methods apply to the subclass. If you cannot substitute a subclass object for a superclass object, then you do not have a genuine “is a kind of” relationship. In this case, the classes may be related, but not hierarchically.If you do use inheritance, then exploit the polymorphic nature of the instance methods in the inheritance hierarchy. For example, if you find that you need to test for the type of an object in an inheritance tree, then use polymorphism to avoid having to write separate code to handle objects of each class. This maximizes the reusability of your code and makes your code easier to maintain in the future.

Page 332: Java Programming

Oracle10g: Java Programming 10-28

10-28 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:• A subclass inherits all the variables and methods

of its superclass.• You can specify additional variables and methods

and override methods. • A subclass can call an overridden superclass

method by using super.• Polymorphism ensures that the correct version of

a method is called at run time.

Page 333: Java Programming

Oracle10g: Java Programming 10-29

10-29 Copyright © 2004, Oracle. All rights reserved.

Practice 10: Overview

This practice covers:• Defining subclasses of Customer• Providing subclass constructors• Adding new methods in the subclasses• Overriding existing superclass methods

Practice 10: OverviewNote: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les09 directory, load the OrderEntryWorkspaceLes09 workspace, and continue with this practice.Viewing the model: To view the course application model up to this practice, load the OrderEntryWorkspaceLes09 workspace. In the Applications – Navigator node, expand the OrderEntryWorkspaceLes09 – OrderEntryProjectLes09 -Application Sources – oe, and double-click the UML Class Diagram1 entry. This diagram displays all the classes created to this point in the course.

Page 334: Java Programming

Oracle10g: Java Programming 10-30

Practice 10: Reusing Code with Inheritance and PolymorphismScenarioIn this practice, you add a few new classes as subclasses. The new classes that are added are Company and Individual and they inherit from the Customer class. Here is a Class diagram to show the relationship between Customer, Company, and Individual. Each box represents a class. The name of the class appears at the top of each box. The middle section specifies the attributes in the class, where underlined attributes represent class variable. The lower section specifies the methods in the class.Notice the arrow on the line connecting Company and Individual to Customer. This is the UML notation for inheritance.

Person class

Customer

int nextCustomerIdint idString name String addressString phone

toString()getNamen()setName()getAddress()setAddress()…

Person class

Company

String contactint discount

toString()setContact()getContact()setDiscount()getDiscount()

Person class

Individual

String licNumber

toString()setLicNumber()getLicNumber()

Page 335: Java Programming

Oracle10g: Java Programming 10-31

Practice 10: Reusing Code with Inheritance and Polymorphism (continued)GoalThe goal of this practice is to understand how to create subclasses in Java, and use polymorphism with inheritance through the Company and Individual subclasses of the Customer class. Refine the subclasses and override some methods and add some new attributes, making use of the Class Editor in JDeveloper.Note: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les09 directory, load the OrderEntryWorkspaceLes09 workspace, and continue with this practice.Your AssignmentAdd two classes, Company and Individual, that inherit from Customer. The owners of the business have decided to expand their business and sell their products to companies as well as individuals. Because companies have slightly different attributes than individuals, you have decided to create subclasses for Company and Individual. Each of the subclasses will have a few of their own methods and will override the toString()method of Customer. In JDeveloper, continue to use your workspace and project (OrderEntryWorkspace and OrderEntryProject) from the previous practice containing the files from the previous practices.Define a New Company Class

1. Define a Company class that extends Customer and includes the attributes and methods that were defined in the object model on the first page of this practice (scenario section).

a. Right-click the OrderEntryProject.jpr project and select the New…option from the pop-up menu. In the New Gallery window, select the Generalcategory (if not selected by default) and Java Class from the Items list. Then, click OK.

b. In the Create Java Class Wizard, enter Company in the Name field, then click the Browse… button next to the Extends field. In the Class Browser window, locate and expand the oe package, select the Customer class, and click the OK button. The oe.Customer class must be shown in the Extends field. Leave the Optional Attributes in their default state, and click the OK button. When the source code for the generated class is displayed, save your work.

c. Select Company.java file in the Navigator and then select the Class tab at the bottom of the code window. This displays the Class Editor. In the Class Editor, select the Fields tab.

d. In the Fields tab, for each attribute, click the +Add button in the Declared Fields area to add the following private attributes:

private String contact;private int discount;

For each attribute in the Fields Setting dialog box, enter:- A Field name (for example, Contact)- A Field type (appropriate for the variable)- A Scope set to private

Page 336: Java Programming

Oracle10g: Java Programming 10-32

Practice 10: Reusing Code with Inheritance and Polymorphism (continued)Note: In the Accessors section, note that Create get() method and Create set() method check boxes are selected. Then, click the OK button to create each field.

e. After adding the attributes, click the Methods tab to view the get and set methods that JDeveloper has generated for each attribute. The methods are named according to JavaBean coding standards. Modify the code created by JDeveloper to match the code below, if required.

f. Save your changes.2. Alter the Company constructor to have arguments.

a. Add the following arguments to the no-arg constructor:

public Company(String aName, String aAddress,String aPhone, String aContact, int aDiscount) { …

}b. Use the arguments to initialize the object state (including the superclass state).

Hint: Use the super(…) method syntax to pass values to an appropriate superclass constructor to initialize the superclass attributes. For example:

super(aName, aAddress, aPhone);contact = aContact; ...

3. Add a public String toString() method in the Company class to to return the contact name and discount. Include in the return value the superclass details, and format as follows:(Scott Tiger, 20%)return super.toString() + " ("+ contact + ", "+ discount

+ "%) ";a. You can manually enter the toString() method signature to the class, or get

JDeveloper to generate the toString() method signature as described in step (b). Skip step (b) if you manually enter the method.

b. Select the Tools> Override Methods... menu, to launch the Override Methods Wizard. Ensure that oe.Company is visible in the Class field. Select the toString(): String method from the Methods list and then click the OK button. Scroll down to the end of the source code in the Company class to view the results and modify the code for the method body to match with the displayed code.

c. Save and compile the Company.java class.Define a New Individual Class As a Subclass of Customer

4. Define an Individual class extending Customer, and include the attributes and methods that are defined in the object model on the first page of this practice.

a. Create the Individual class similarly as mentioned for the Company class in point 1:a. Add the licNumber attribute as a String, with a private scope and ensure that the get and set methods are created to retrieve the values.

Page 337: Java Programming

Oracle10g: Java Programming 10-33

Practice 10: Reusing Code with Inheritance and Polymorphism (continued)b. Alter the no-arg constructor to accept four arguments for the name, address,

phone, and the license number

c omplete the constructor bodyinitiali ation by assigning thearguments to the appropriateinstance variables in the Individual

class and its superclassd verride the toString() method that is

defined in the superclass andappend the license number enclosedin brackets to the superclassinformationNote: You can write the code in bold without manually having to select the Tools – Override menu option.

e ave and compile the Individual class

Modify the DataMan Class to Include Company and Individual Objects

ou add two new class variables to theDataMan class one for a Company object and theother for an Individual5 pen DataMan in the Code Editor and add twonew class variables called customer5 andcustomer6a reate a Company variable called

customer5 and initiali e the variableby using the Company constructor or

example

static Company customer5 = new Company("Oracle","Redw…","80…","Larry…",20);

b reate an Individual variable calledcustomer6 and initiali e by using theconstructor from the Individual class

c ave and compile DataMan.java by right

clicking the file and selecting Make from the shortcut menu

Test Your New Classes in the OrderEntry.java Applicationodify the OrderEntry code that assigns a

customer object to each of the two orderobjects in the main() method6 pen OrderEntry.java in the Code Editor

a ocate the line assigning customer3

with the first order objector example find

order.setCustomer(DataMan.customer3);int se Ctrl + F to display a searchd alog box

Page 338: Java Programming

Oracle10g: Java Programming 10-34

Practice 10: Reusing Code with Inheritance and Polymorphism (continued)Optional Extra CreditRefine the Util and Customer Classes and Test Results

t is not obvious to the casual user thatdata that is printed for a customercompany or individual objectsrepresent different objects unless theuser is made aware of the meaning of thesubtle differences in the displayeddata herefore you are asked to modifyyour code to explicitly indicate theobject type name in the text that isprinted before the rest of the objectdetails as follows

[Customer] <customer details>

[Company] <company details>

[Individual] <individual details>

f you manually add the bracketed textstring before the return values of thetoString() methods in the respective

classes then it produces a result thatconcatenates [Company] to [Customer], and[Individual] to [Customer] for the subclasses ofCustomer herefore the solution is to useinherited code called from the Customer

class that dynamically determines therun time object type name

ou can determine the run time objecttype name of any ava object by callingits getClass() method which is inheritedfrom the java.lang.Object class he getClass()method returns java.lang.Class object

reference through which you can call agetName() method returning a String

containing the fully qualified run timeobject name or example if you add thisline to the ustomer class

String myClassName = this.getClass().getName();

he variable myClassName will contain a fully

qualified class name that includes thepackage name he value that is stored inmyClassName will be oe.Customer

o extract only the class name you muststrip off the package name and the dotthat precedes the class name his can bedone by using a lastIndexOf() method in the

Page 339: Java Programming

Oracle10g: Java Programming 10-35

Practice 10: Reusing Code with Inheritance and Polymorphism (continued)8 pen Customer.java in the ode ditor

a refix a call to the Util.getClassName()

method before the rest of thereturn value data in the toString()

method as followsreturn "[" + Util.getClassName(this) + "] " + id +…;

b ave and compile Customer.javac un the OrderEntry.java application to

view the resultsd n the above code what does this

represent nd why do you pass aparameter value this to theUtil.getClassName() method

xplain why the compiler acceptsthe syntax that is used

Page 340: Java Programming
Page 341: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Using Arrays and Collections

Schedule: Timing Topic60 minutes Lecture30 minutes Practice90 minutes Total

Page 342: Java Programming

Oracle10g: Java Programming 11-2

11-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Describe how to create arrays of primitives and

objects• Process command-line variables• Work with vectors• Explore other Java collections such as

Enumerators, Iterators, ArrayLists, and Hashtables

• Process command-line and system properties

Lesson AimThis lesson shows how to use Java collection objects, introducing the Java array of primitive, array of Object references and other collection classes such as Vectors, Hashtables, Properties, Enumerators and Iterators.

Page 343: Java Programming

Oracle10g: Java Programming 11-3

11-3 Copyright © 2004, Oracle. All rights reserved.

What Is an Array?

An array is a collection of variables of the same type.• Each element can hold a single item.• Items can be primitives or object references.• The length of the array is fixed when it is created.

1

2

4

8

[0]

[1]

[2]

[3]

Action

Comedy

Drama

[0]

[1]

[2]

ArraysArrays are useful when you want a group of objects that you can manipulate as a whole. For example, if you are writing a program to allow users to search for a movie, you would probably store the list of categories in an array.The slide shows an array of four integers and an array of three strings. The following slides show how to create and initialize the arrays. As you will soon see, an array in Java is an object.

Page 344: Java Programming

Oracle10g: Java Programming 11-4

11-4 Copyright © 2004, Oracle. All rights reserved.

Creating an Array of Primitives

1. Declare the array:

type is a primitive, such as int and so on.2. Create the array object:

3. Initialize the array elements(optional).

NullarrayName

arrayName1

2

4

0

0

0

arrayName

type[] arrayName;

… or …

type arrayName[];

// Create array object syntax

arrayName = new type[size];

Creating an Array of Primitives1. Declaration: Create the variable that references the array.2. Creation: Create an array object of the required type and size, and store a reference

to the array in the array variable.3. Initialization: Initialize the array elements to the values that you want. This is

optional for an array of primitives, because the elements are initialized to default values when the array object is created. The following slides explain these three steps in detail.

Page 345: Java Programming

Oracle10g: Java Programming 11-5

11-5 Copyright © 2004, Oracle. All rights reserved.

Declaring an Array of Primitives

• Create a variable to reference the array object:

• When an array variable is declared:– Its instance variable is initialized to null until the

array object has been created

– Its method variable is unknown until the object is created

int[] powers; // Example

nullpowers

Declaring an ArrayThere are two ways to declare an array:

Most Java programmers use the first style because it separates the variable type (in the example, an array of int) from the variable name, making the code clearer to read.When you declare an array variable, it refers to null initially, until you initialize the array by using new.

Instructor NoteAlthough an array is an object, there is no array class. Instead, for every primitive type or class, Java automatically provides an array class.

Syntax Example type[] arrayname; int[] powers; type arrayname[]; int powers[];

Page 346: Java Programming

Oracle10g: Java Programming 11-6

11-6 Copyright © 2004, Oracle. All rights reserved.

Creating an Array Object foran Array of Primitives

• Create an array of the required length and assign it to the array variable:

– The array object is created by using the newoperator.

• The contents of an array of primitives are initialized automatically.

int[] powers; // Declare array variable

powers = new int[4]; //Create array object

00

powers

00

Creating an Array ObjectIf you are using the new operator, you must specify the array size inside the brackets. The size must be an integer, but does not have to be a constant number; it could be an expression that is evaluated at run time.After the array object has been created, its length is fixed for the lifetime of the array.Default Initialization of Array ElementsAll elements in a new array of primitives are initialized automatically with default values, as follows:• char elements are set to '\u0000'.• byte, short, int, and long elements are set to 0.• boolean elements are set to false.• float and double elements are set to 0.0.

Note: '\u0000' is Unicode 0000. Java uses the Unicode character set.

Examples of Valid Array CreationExample 1

final int SIZE = 4;

int[] powers = new int[SIZE]; // SIZE is a constant

Page 347: Java Programming

Oracle10g: Java Programming 11-7

Examples of Valid Array Creation (continued)Example 2int[] examMarks;int num = askUserHowManyStudents(); // set the value of numexamMarks = new int[num]; // array is a fixed size

Examples of Invalid Array CreationExample 1int powers[4]; // Invalid syntax: you can’t set the size of

// the array in the declaration statement.

Example 2int num;

int[] examMarks = new int[num]; // Compilation error: num hasnot been initialized

Instructor NoteArrays can be created and initialized at the same time; the syntax for doing this is covered in the following slide.

Page 348: Java Programming

Oracle10g: Java Programming 11-8

11-8 Copyright © 2004, Oracle. All rights reserved.

Initializing Array Elements

• Assign values to individual elements:

• Create and initialize arrays atthe same time:

int[] primes = {2, 3, 5, 7};

type[] arrayName = {valueList};

primes[0][1][2]

2357 [3]

arrayName[index] = value;

powers[0] = 1;powers

[0][1][2]

1000 [3]

Initializing Array ElementsFirst Method: Assign a Value to Each Array ElementTo refer to an element in an array, use an index in brackets ([]) as shown in the slide. Array elements are numbered from 0 to n-1, where n is the number of elements in the array. In other words, the index of the first element in an array is 0, not 1.Second Method: Use Array InitializersAs shown in the slide, there is a shorthand technique for creating and initializing an array of primitives. Here, there is no need to use the new operator, and the length of the array is set automatically. Note the use of the braces, and remember the semicolon at the end.Array initializers are very useful for creating lookup tables, as in the following example:

int[] daysInMonth = {31, 28, 31, 30, 31, 30,31, 31, 30, 31, 30, 31};

This method is useful only if the value of each element is known when the array is created.

Page 349: Java Programming

Oracle10g: Java Programming 11-9

11-9 Copyright © 2004, Oracle. All rights reserved.

Creating an Array of Object References

1. Declare the array:

2. Create the array object:

3. Initialize the objects in the array.

nullarrVar

null

null

null

arrVar

Action

Comedy

Drama

arrVar

ClassName[] arrVar;

… or …

ClassName arrVar[];

// Create array object syntax

arrVar = new ClassName[size];

Creating an Array of ObjectsThe steps for creating an array of object references are the same as for arrays of primitives, with one exception: You must initialize the elements in the array, because this is not done automatically.

1. Declaration: The syntax is the same as for arrays of primitive objects. For example, String[] categories;declares a variable that can point to an array of String. If the variable is the instance variable, the variable is set to null initially.

2. Creation: The syntax is the same as for arrays of primitive objects. For example, categories = new String[3];creates an array object of the correct type (String) and a size of 3. Initially, all of the elements are set to null.You can declare and create an array in the same statement. For example, String[] categories = new String[3];

3. Initialization: Initialize the array elements to the values that you want. This is described in the next slide.

Instructor NoteIt is important to emphasize that step 2 creates an array of three nulls and that this is not the same as an array of three empty strings.

Page 350: Java Programming

Oracle10g: Java Programming 11-10

11-10 Copyright © 2004, Oracle. All rights reserved.

Initializing the Objects in the Array

• Assign a value to each array element:

• Create and initialize the array at the same time:

String[] categories =

{"Action", "Comedy", "Drama"};

// Create an array of four empty Strings

String[] arr = new String[4];

for (int i = 0; i < arr.length; i++) {

arr[i] = new String();

}

Initializing the Objects in an ArrayAs with arrays of primitives, there are two ways of initializing an array of object references. You can initialize the array by assigning a value to each array element or by initializing the array when you create it.The length PropertyEvery array has a length attribute that contains the number of elements in the array. Byusing length, you can avoid the need to hardcode or store the size of an array in your code. Because the index of the first element in an array is 0, the index of its last element is length – 1.The example in the slide uses length to loop through all the elements of an array to create an array of empty strings.Incidentally, the System class provides a useful method for copying all or part of an array to another array. For more information, refer to System.arraycopy() in the Java Development Kit (JDK) documentation.

Instructor NoteIt is a good practice to initialize an array of object references immediately after it is created. That way you can be sure that the rest of your code can safely reference the contents of the array. If you do not know the value of the array elements at creation time, you must initialize each element to an empty object, like the example in the slide does.

Page 351: Java Programming

Oracle10g: Java Programming 11-11

11-11 Copyright © 2004, Oracle. All rights reserved.

Using an Array of Object References

• Any element can be assigned to an object of the correct type:

• Each element can be treated as an individual object:

• An array element can be passed to any method; array elements are passed by reference.

System.out.println

("Length is " + categories[2].length());

String category = categories[0];

Passing Arrays to MethodsBecause arrays behave like objects when an array is passed into a method, it is passed by reference like any other object. Therefore, if the method changes the contents of the array, these changes operate on the original array, not a copy.

Instructor NoteThe second example calls the method String.length() to determine the length of one of the strings in the array. Assuming that the array has been initialized to {"Action","Comedy", "Drama"} as in the previous slide, this code fragment prints the following line:

Length is 5

(That is the length of the string "Drama".)

Page 352: Java Programming

Oracle10g: Java Programming 11-12

11-12 Copyright © 2004, Oracle. All rights reserved.

Arrays and Exceptions

• ArrayIndexOutOfBoundsException occurs when an array index is invalid:

• NullPointerException occurs when you try to access an element that has not been initialized:

Movie[] movieList = new Movie[3];

// The following will throw NullPointerException

String director = movieList[0].getDirector();

String[] list = new String[4];//The following throws ArrayIndexOutOfBoundsExceptionSystem.out.println(list[4]);

Arrays and ExceptionsThe slide shows the exceptions, or errors, that occur when you try to perform an invalid operation on an array. Exceptions are covered in more detail in the lesson titled “Throwing and Catching Exceptions”; these are included in this slide because you are likely to seethese errors if your code attempts to perform one of the operations that is described in the slide.If you try to access an invalid array index, then your program will crash with the error "ArrayIndexOutOfBoundsException".If you try to access an array element that has not been initialized, your program will crash with the error "NullPointerException".

Instructor NoteIn the first example, the code is trying to access an element beyond the bounds of the array. The array length was fixed to 4 when the array was created.In the second example, the code is trying to access a method of one of the elements of the array, but the array has not been initialized; at this point, it is an array of three nulls.

Page 353: Java Programming

Oracle10g: Java Programming 11-13

11-13 Copyright © 2004, Oracle. All rights reserved.

Multidimensional Arrays

Java supports arrays of arrays:

type[][] arrayname = new type[n1][n2];

int[][] mdarr = new int[4][2];

mdarr[0][0] = 1;

mdarr[0][1] = 7;

[0]

[1]

[2]

[3]

1 7

0 0

0 0

0 0

mdarr

[0][0] [0][1]

Multidimensional ArraysJava supports multidimensional arrays; that is arrays of arrays:

int[][] tax = new int[5][4];

This declares and creates a two-dimensional matrix; the matrix contains five rows, each of which contains four columns. Individual elements can be accessed as follows:

tax[rowIndex][colIndex] = value;

Advanced Topic: Nonsquare Multidimensional ArraysThe following example creates a multidimensional array with 10 rows, but the number of columns in each row is different: the first row has one element, the second row has two elements, and so on.

int[][] a = new int[10][];for (int i = 0; i < a.length; i++) {

a[i] = new int[i + 1];}

Page 354: Java Programming

Oracle10g: Java Programming 11-14

11-14 Copyright © 2004, Oracle. All rights reserved.

main() Revisited

• main() has a single parameter, args.• args is an array of Strings that holds command-

line parameters:

public class SayHello {

public static void main(String[] args) {

if (args.length != 2)

System.out.println("Specify 2 arguments");

else

System.out.println(args[0]+" "+args[1]);

} …

C:\> java SayHello Hello World

Passing Command-Line Parameters to main()A reference to an array can be passed to any method. A good example is the main()method that is used in Java applications. When you start a Java application, as opposed to a Java applet, the system locates and calls the main() method for that class. The main() method has a single parameter, which is a reference to an array of Stringobjects. Each String object holds a command-line parameter; the first element in the array contains the first command-line parameter, not the name of the program as in C and C++. Command-Line Parameters Are Always Converted to StringsIt is important to note that command-line parameters are always represented by Stringobjects. Inside the main() method, you may need to convert a parameter to a primitive type. For example, if one of the command-line parameters represents a number, you may need to convert it into an int to perform some arithmetic with it. Specifying Command-Line Parameters in JDeveloperJDeveloper has a dialog box that you can use to specify command-line parameters for a Java application. When you run the application from the JDeveloper environment, JDeveloper passes the parameters into the main() method, as usual.To specify command-line parameters in JDeveloper, select the Project > Project Properties item from the menu bar, and click the Run/Debug tab. This tab has a field where you can define command-line parameters.

Page 355: Java Programming

Oracle10g: Java Programming 11-15

11-15 Copyright © 2004, Oracle. All rights reserved.

Working with Variable-Length Structures

The Vector class implements a “resizable” array of any type of object:• Creating an empty vector:

• Creating a vector with an initial size:

Vector members = new Vector();

// Create a vector with 10 elements. The vector //

can be expanded later.

Vector members = new Vector(10);

VectorsThe Vector class, belonging to the java.util package, provides a resizeable collection of objects. Remember that Java arrays are fixed in size, so a vector is useful when you do not know how large an array will be at the time when you create the array. For example, you may get a list of names from a server and want to store the names in a local array. Before you fetch the data from the server, you have no idea how large the list is.You cannot create a vector of int, float, or any other primitive. Instead, you must use the wrapper classes, which were discussed in the lesson titled “Using Strings, StringBuffer, Wrapper and Text-Formatting Classes,” and create a vector of Integer, Float, and so on.The Vector class provides methods to modify and access the vector. The following slides show some of these methods; the JDK 1.4 online documentation provides complete information.

Instructor NoteTo use vectors, you must import the Vector class:

import java.util.Vector;

Page 356: Java Programming

Oracle10g: Java Programming 11-16

11-16 Copyright © 2004, Oracle. All rights reserved.

Modifying a Vector

• Add an element to the end of the vector:

• Add an element at a specific position:

• Remove the element at a specific index:

String name = MyMovie.getNextName();

members.addElement(name);

// Remove the first element

members.removeElementAt(0);

// Insert a string at the beginning

members.insertElementAt(name, 0);

Modifying a VectorWhen you add an element to a vector, the vector is automatically expanded by one element. When you remove an element from a vector, the size of the vector decreases automatically. When you insert an element at a specific position, all elements after that position increase their indexes by 1.

Page 357: Java Programming

Oracle10g: Java Programming 11-17

11-17 Copyright © 2004, Oracle. All rights reserved.

Accessing a Vector

• Get the first element:

• Get an element at a specific position:

• Find an object in a vector:

• Get the size of a vector:

String s = (String)members.firstElement();

int size = members.size();

String s = (String)members.elementAt(2);

int position = members.indexOf(name);

Vector IndexingThe index of the first element of a vector is 0. Note that a vector always contains objects. It can contain objects of different types. When you get an element from a vector, you must cast it to the type of object that you added to the vector.

Example of a Vector Containing Different ObjectsThe Vector.addElement() method accepts an Object as its parameter type. By applying the principle of object reference substitution (subclass object plug-compatibility with its superclass), the parameter can be any subclass of the java.lang. The Object class, which includes just about every object that you can create. Here is a simple example, assuming that you have a class called Member:

Vector v = new Vector();v.addElement(new Member());v.addElement("pat");v.addElement(new Integer(10));

You must be sure of the type of object that you are getting returned from methods such as Vector elementAt() or firstElement(). You can use the instanceofoperator to determine the object type that is returned by these methods.

Page 358: Java Programming

Oracle10g: Java Programming 11-18

11-18 Copyright © 2004, Oracle. All rights reserved.

Java Collections Framework

Java Collections Framework is an API architecture for managing a group of objects that can be manipulated independently of their internal implementation. It is:• Found in the java.util package• Defined by six core interfaces and some

implementation classes:– Collection interface: Generic group of elements– Set interface: Group of unique elements– List interface: Ordered group of elements– Map interface: Group of unique keys and their

values– SortedSet and SortedMap for a sorted Set and

Map

Java Collections FrameworkJava Collections Framework is an API architecture for managing a collection of objects that can be manipulated independently of their internal implementation. The framework is a unified architecture for representing and manipulating collections. All collections frameworks contain three things: Interfaces, Implementations, and AlgorithmsThe framework is built around six core interfaces and many implementation classes that are found in the java.util package. The Collection interface is inherited by the Setand List interfaces. The SortedSet is a subclass of Set, and SortedMap is a subclass of Map.

Page 359: Java Programming

Oracle10g: Java Programming 11-19

Java Collections Framework (continued)The Collection interface is an abstraction representing a group of objects called elements.The Set interface models mathematical set abstraction. It is a collection that cannot contain duplicate elements. The implementation classes are HashSet and TreeSet.The List interface represents an ordered collection (or sequence) of elements, including duplicates. Lists provide control over where each element is inserted. Elements can be accessed by their integer index (position). Implementing classes are ArrayList and LinkedList. Lists are similar to vectors.The Map interface represents an object that maps one or more keys to their values. Maps do not contain duplicate keys, and each key maps to a single value. Implementing classes are HashMap and TreeMap. These are similar to a Hashtable.Sorted collections are provided through the SortedSet and SortedMap interfaces, which are sorted versions of Set and Map, respectively.

Page 360: Java Programming

Oracle10g: Java Programming 11-20

11-20 Copyright © 2004, Oracle. All rights reserved.

Collections Framework Components

Collections Framework is a set of interfaces and classes used to store and manipulate groups of data as a single unit.• Core Interfaces are the interfaces used to

manipulate collections, and to pass them from one method to another.

• Implementations are the actual data objects used to store collections, which implement the core collection interface.

• Algorithms are pieces of reusable functionality provided by the JDK.

Java Collections Framework ComponentsThe design of programs often requires handling of groups of objects. This collection framework offers a set of standard utility classes to manage the collection of these objects. The framework is made up of three main components (listed on the previous page):

• Core Interfaces: These allow collections to be manipulated, independent of theirimplementation. These interfaces describe a common set of functionality, displayed by collections, and enhance data exchange between collections. In object-oriented languages, these interfaces, generally, are contained within a hierarchy.

• Implementations: A small set of implementations exists as concrete implementations of the core interfaces, which provide a data structure that a program can use. In a sense, these are reusable data structures. The implementations come in three flavors: general-purpose, wrapper, and convienience.

• Algorithms: Methods that perform useful computations, such as searching andsorting, on objects that implement collection interfaces. These algorithms are said to be polymorphic because the same method can be used on many different implementations of the appropriate collections interface. In essence, algorithms are reusable functionality.

Page 361: Java Programming

Oracle10g: Java Programming 11-21

11-21 Copyright © 2004, Oracle. All rights reserved.

Using ArrayList and Hashtable

The ArrayList class:• Is a resizable implementation of the List interface• Allows manipulation of the array size• Has capacity that grows as elements are added to

the listThe Hashtable class:• Is a legacy class similar to Map implementations• Is used to store arbitrary objects that are indexed

by another arbitrary object• Is commonly used with String as the key to store

objects as values

ArrayListThe ArrayList is a resizable-array implementation of the List interface. It implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.

HashtableThe java.util.Hashtable class provides a table of keys, where each key is hashed to an associated value object. The key and value can be any Java object. Here is an example of using the Hashtable to store String objects on information about a book.

import java.util.Hashtable;public class HashtableDemo {

public static void main (String args[]) {Hashtable ht = new Hashtable();ht.put ("title", "Beyond Freedom and Diginity");ht.put ("author", "B.F. Skinner");ht.put ("year", "1971");System.out.println(ht);System.out.println("Year: " + ht.get("year"));

}}

Page 362: Java Programming

Oracle10g: Java Programming 11-22

11-22 Copyright © 2004, Oracle. All rights reserved.

Using Iterators

The Iterator interface, which is part of Java Collection Framework, can be used to process a series of Objects. The java.util.Iterator interface:• Implements an object-oriented approach for

accessing elements in a collection• Replaces the java.util.Enumeration approach• Contains the following methods:

– hasNext() returns true if more elements exist.– next() returns the next Object, if any.– remove() removes the last element returned.

Another Type of CollectionCollections differ from arrays in that the members of a collection are not directly accessible using indices, as you would with arrays. When using an Enumeration or an Iteratoryou can only move the current item pointer to the first or next element of a collection. The Enumeration was part of the standard Java API, and the Iterator was added with Java Collection Framework API. An Iterator supports removal of an object from the collection, whereas an Enumeration can only traverse the collection.The following example creates a Vector containing several String elements, and then calls the iterator() method to return an Iterator object. The loop uses the next() method of the Iterator is to get elements and display their string value in uppercase.When hasNext() is false the loop terminates.

import java.util.Vector;import java.util.Iterator;:Vector v = new Vector();v.addElement("Jazz");v.addElement("Classical");v.addElement("Rock 'n Roll");for (Iterator e = v.iterator(); e.hasNext(); ) {

String s = (String) e.next();System.out.println(s.toUpperCase());

}

Page 363: Java Programming

Oracle10g: Java Programming 11-23

11-23 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:• Create Java arrays of primitives• Create arrays of object references• Initialize arrays of primitives or object references• Process command-line arguments in the main()

method• Use the Vector object to implement resizable

arrays• Use ArrayList and Hashtable classes

Page 364: Java Programming

Oracle10g: Java Programming 11-24

11-24 Copyright © 2004, Oracle. All rights reserved.

Practice 11: Overview

This practice covers:• Modifying the DataMan class

– Create an array to hold the Customer, Company, and Individual objects.

– Add a method to ensure that the array is successfully created and initialized.

– Add a method to find a customer by an ID value.

Practice 11: OverviewNote: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les10 directory, load the OrderEntryWorkspaceLes10 workspace, and continue with this practice.Viewing the model: To view the course application model up to this practice, load the OrderEntryWorkspaceLes10 workspace. In the Applications – Navigator node, expand the OrderEntryWorkspaceLes10 – OrderEntryProjectLes10 -Application Sources – oe, and double- click on UML Class Diagram1entry. This diagram displays all the classes created to this point in the course.

Page 365: Java Programming

Oracle10g: Java Programming 11-25

Practice 11: Using Arrays and CollectionsGoalThe goal of this practice is to gain experience with Java array objects, and work with collection classes such as the java.util.Vector class. You also work with command-line arguments.Note: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les10 directory, load the OrderEntryWorkspaceLes10 workspace, and continue with this practice.Your AssignmentContinue to use JDeveloper to build on the application classes from the previous practices. You will enhance the DataMan class to construct an array of Customer objects, and then provide a method to find and return a Customer object for a given ID.The Order class is modified to contain a vector of order items, requiring a method to add items into the vector, and (optionally) another method to remove the items.Modify DataMan to Keep the Customer Objects in an Array

1. Modify the DataMan class to build an array of customers.a. Define a private static array of Customer objects named customers.b. Initialize the array to a null reference.

2. Create a public static void method called buildCustomers() to populate the array of customers. The array must hold six objects by using the four Customerobjects, the Company object and the Individual object that you have already created.

a. In the body of the method, first test whether the customers variable is not null, and if so, then return from the method without doing anything because a non-null reference indicates that the customers array has been initialized. If customers is null, then you must create the array object to hold the six customer objects that are already created.

b. Now move (cut and paste) the definitions of the four existing Customer objects, the Company, and the Individual into the body of this method, after creating the array object. Then, delete the static keyword and class name or type before each customer<n> variable name. Modify each variable to be the name of the array variable followed by brackets enclosing an array element number. Remember, array elements start with a zero base.For example replace:

static Customer customer1 = new Customer(…);with:

customers[0] = new Customer(…);The example here assigns the customer object to the first element in the array.Repeat this for each customer<n> object references in the code.

c. Create a static block that invokes the buildCustomers() method to create and initialize the array of customer objects, when the DataMan class is loaded. Place the block at the end of the DataMan class. (Static blocks in the class definition are sometimes called class constructors.)

static{buildCustomers();}

Page 366: Java Programming

Oracle10g: Java Programming 11-26

Practice 11: Using Arrays and Collections (continued)d. Save and compile the DataMan class. What other classes are compiled?

Explain the results. (Only fix errors that are related to the DataMan class, if any. Any errors pertaining to OrderEntry class will be fixed after doing the next set of questions).Hint: Look in the Messages and Compiler tabs of the Log Window.

Modify DataMan to Find a Customer by ID3. Create a public static method called findCustomerById(int custId),

where the argument represents the ID of the Customer object to be found. If found, then return the object reference for the matching Customer, otherwise return a null reference value.

a. Why is the customer array guaranteed to be initialized when the findCustomerById() method is called? Thus, you can write code assuming that the array is populated.

b. Write a loop to scan through the customers array, obtaining each customer object reference to compare the custId parameter value with the return value from the getId() method of each customer. If there is a match, then return the customer object reference; otherwise, return a null.

c. Save and compile your DataMan class, only fixing the syntax errors that are reported for the DataMan class.

4. You now fix the syntax errors in the OrderEntry class as a result of the changes made to DataMan. The modifications that you make to OrderEntry.java fix the syntax errors, and test the code that is added to the DataMan class.

a. In the Code Editor, locate and modify each line that directly refers to the DataMan.customer<n> variables that previously existed.Hint: You can quickly navigate to the error lines by double-clicking the error message line in the Compiler tab of the Log Window.Replace each occurrence of the DataMan.customer<n> text with a method call to: DataMan.findCustomerById(n). For example, replace:System.out.println(DataMan.customer1.toString());withSystem.out.println(DataMan.findCustomerById(1).toString());

b. Save, compile, and run the OrderEntry.java file to test your changes.Optional Extra CreditModify the Order Class to Hold a Vector of OrderItem ObjectsCurrently, the Order class has hardcoded creation of two OrderItem objects as instance variables, and the details of each OrderItem object is set in the getOrderTotal()method. This is impractical for the intended behavior of the Order class. You must now replace the two OrderItem variables with a Vector that will contain the OrderItemobjects. Therefore, you must create methods to add and remove OrderItem objects to and from the vector.

Page 367: Java Programming

Oracle10g: Java Programming 11-27

Practice 11: Using Arrays and Collections (continued)Modify the Order Class to Hold a Vector of OrderItem Objects (continued)

5. In the Order class, define a Vector of order items, and replace the OrderItem instance variables, removing code dependent on the original OrderItem instance variables.

a. Add a statement at the beginning of your class, after the package statement, toimport the java.util.Vector class.

b. Declare a new instance variable called items as a Vector object reference.Also remove, or comment out, the declarations of the two instance variablescalled item1 and item2, and the code that is using these variables.Hint: The following methods directly use the item1 and item2 variables: getOrderTotal(), showOrder().

c. In the Order no-arg constructor, add a line to create the item vector, as follows:

items = new Vector(10);

d ompile and save your changes tothe Order class

Modify OrderItem to Handle Product Information6. Before you create the method to add an OrderItem object to the items vector,

you must first modify the OrderItem class to hold information about the productbeing ordered. Each OrderItem object represents an order line item. Eachorder line item contains information about a product that is ordered, its price, andquantity that is ordered.

a. Edit the OrderItem class and add a new instance variable called product.Declare the variable as a private int, and generate or write thegetProduct() method and setProduct() methods. Modify the toString()method to add the product value between the lineNbr and quantity.

b. Create an OrderItem constructor to initialize the object by using values that are supplied from the following two arguments: int productId and double itemPrice.Initialize the item quantity variable to 1.Note: The OrderItem class will not provide a no-arg constructor.

c. Save and compile the OrderItem class.Modify Order to Add Products into the OrderItem Vector

7. In the Order class, create a new public void method called addOrderItem()that accepts one argument: an integer called product, representing an ID of the product being ordered. This method must perform the following tasks:

a. Search the items vector for an OrderItem containing the supplied product.To do this, create a loop to get each OrderItem element from the itemsvector.

Page 368: Java Programming

Oracle10g: Java Programming 11-28

Practice 11: Using Arrays and Collections (continued)Hint: Use the size() method of the Vector object to determine the number of elements in the vector. Use the getProduct() method of the OrderItemclass to compare the product value with the existing product value in the order item.If the product, with the specified ID, is found in an OrderItem elements fromthe vector, then increment the quantity by using the setQuantity() method.If the specified product does not exist in any OrderItem object in the vector,then create a new OrderItem object by using the constructor that will acceptthe product, and a price. Then add the new OrderItem object into the vector.Note: Because line item numbers are set relative to their order, set the line number for the OrderItem, by using the setLineNbr() method, after an item is added to the vector. The line number is set using the size() of the vector, because the elements are added to the end of the vector. For now, assume that all products have a price of $5.00.

b. The orderTotal value will now be calculated as each product is added to the order. Thus, you must also add the price of each product to orderTotal.Hint: Use the getUnitPrice() method from the OrderItem class. Because the orderTotal is now updated as each product is added to the order, the getOrderTotal() method can simply return the orderTotalvalue.Note: This may already be done due to previous changes to the method.

c. Modify the showOrder() method to use an Enumeration technique to loop through the items vector to display each OrderItem object by calling the toString() method.Hint: Import java.util.Enumeration, and use the Vector elements() method to create an Enumeration. See your course notes for an example, or ask your instructor for guidance.

d. Save and compile the Order class, and remove any syntax errors.e. Test your changes to the OrderItem and Order classes by modifying the

OrderEntry class to add products 101, 102 to the first order object.For example, before the call to showOrder(), enter the bold lines shown:

order.setCustomer(DataMan.findCustomerById(5));order.addOrderItem(101);order.addOrderItem(102);order.addOrderItem(101);order.showOrder();

f. Compile (eliminating syntax errors first), save and run OrderEntry.java.Confirm that your results are accurate. For example, check whether the order total is reported as $15.

Page 369: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Structuring Code by UsingAbstract Classes and Interfaces

Schedule: Timing Topic40 minutes Lecture30 minutes Practice70 minutes Total

Page 370: Java Programming

Oracle10g: Java Programming 12-2

12-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Define abstract classes• Define abstract methods• Define interfaces• Implement interfaces

Lesson AimThis lesson shows how abstract classes and abstract methods can be defined and used in Java. The lesson also introduces interfaces, and shows how they can be used to specify a set of methods that interested classes can implement if they want to. You learn how to use interfaces as an effective alternative to multiple inheritance.

Page 371: Java Programming

Oracle10g: Java Programming 12-3

12-3 Copyright © 2004, Oracle. All rights reserved.

Defining Abstract Classes

• An abstract class cannot be instantiated.• Abstract methods must be implemented by

subclasses.• Interfaces support multiple inheritance.

Abstract superclass

Concrete subclasses

InventoryItem

Movie VCR

Abstract ClassesIn Java, you can define classes that are high-level abstractions of real-world objects. Using these high-level classes gives the designer a vote in what subclasses look like and even which methods are mandatory in the subclass.An abstract class is simply a class that cannot be instantiated; only its nonabstract subclasses may be instantiated. For example, an InventoryItem does not contain sufficient detail to provide anything meaningful to the business. It must either be a movie or a VCR. An InventoryItem does, however, serve as a collection of data and behaviors that are common to all items that are available for rent.Abstract MethodsAbstract methods go a step beyond standard inheritance. An abstract method is defined only within an abstract class, and must be implemented by a subclass. The class designer can use this technique to decide exactly what behaviors a subclass must be able to perform. The designer of the abstract class cannot determine how the behaviors will be implemented, only that they will be implemented.InterfacesAn interface is the specification of a set of methods, which is similar to an abstract class. In addition to what an abstract class offers, an interface can effectively provide multiple inheritance. A class can implement an unlimited number of interfaces but can only extend one superclass.

Page 372: Java Programming

Oracle10g: Java Programming 12-4

12-4 Copyright © 2004, Oracle. All rights reserved.

Creating Abstract Classes

Use the abstract keyword to declare a class as abstract.

public abstract class InventoryItem {

private float price;

public boolean isRentable()…

}

public class Movie

extends InventoryItem {

private String title;

public int getLength()…

public class Vcr

extends InventoryItem {

private int serialNbr;

public void setTimer()…

Creating Abstract Classes Java provides the abstract keyword, which indicates that a class is abstract. For example, the InventoryItem class in the slide has been declared as abstract:

public abstract class InventoryItem {…

}

InventoryItem is declared abstract because it does not possess enough intelligence or detail to represent a complete and stand-alone object. The user must not be allowed to create InventoryItem objects, because InventoryItem is only a partial class. The InventoryItem class exists only so that it can be extended by more specialized subclasses, such as Movie and Vcr.What Happens If You Try to Instantiate an Abstract Class?If you try to create an InventoryItem object anywhere in the program, then the compiler flags an error:

InventoryItem i = new InventoryItem (…);// Compiler error

The user can only create objects of the concrete subclasses:Movie m = new Movie(…); // This is fineVcr v = new Vcr(…); // This is fine too

Page 373: Java Programming

Oracle10g: Java Programming 12-5

12-5 Copyright © 2004, Oracle. All rights reserved.

What Are Abstract Methods?

• An abstract method:– Is an implementation placeholder– Is part of an abstract class– Must be overridden by a concrete subclass

• Each concrete subclass can implement the method differently.

The Need for Abstract MethodsWhen you design an inheritance hierarchy, there will probably be some operations that all classes perform, each in its own way. For example, in a video rental business, the vendor must know whether each item is rentable or not. Each type of item, however, determines whether the item is rentable in a specific way.To represent this concept in Java, the common “is this item rentable” method is defined in the InventoryItem class. However, there is no sensible implementation for this method in InventoryItem, because each different kind of item has its own requirements. One approach may be to leave the method empty in the InventoryItem class:

public abstract class InventoryItem{

public boolean isRentable(); {

return true;

}

}

Page 374: Java Programming

Oracle10g: Java Programming 12-6

The Need for Abstract Methods (continued)This approach is not good enough because it does not force each concrete subclass to override the method. For example, in the Vcr class, if the user forgets to override the isRentable()method, then what will happen if the user calls the method on a Vcr object? The isRentable()method in InventoryItem will be called and always return true. This is not the desired outcome. The solution is to declare the method as abstract, as shown on the next page.

Page 375: Java Programming

Oracle10g: Java Programming 12-7

12-7 Copyright © 2004, Oracle. All rights reserved.

Defining Abstract Methods

• Use the abstract keyword to declare a method as abstract:– Provide the method signature only.– The class must also be abstract.

• Why is this useful?– Declare the structure of a given class without

providing complete implementation of every method.

public abstract class InventoryItem {

public abstract boolean isRentable();

Defining Abstract MethodsTo declare a method as abstract in Java, prefix the method name with the abstract keyword as follows:

public abstract class InventoryItem {

abstract boolean isRentable();

}

When you declare an abstract method, you provide only the signature for the method, which comprises its name, its argument list, and its return type. You do not provide a body for the method. Each concrete subclass must override the method and provide its own body.Now that the method is declared as abstract, a subclass must provide an implementation of that method.Abstract classes can contain methods that are not declared as abstract. Those methods can be overridden by the subclasses but it is not mandatory.

Page 376: Java Programming

Oracle10g: Java Programming 12-8

12-8 Copyright © 2004, Oracle. All rights reserved.

Defining and Using Interfaces

• An interface is like a fully abstract class:– All its methods are abstract.– All variables are public static final.

• An interface lists a set of method signatures without any code details.

• A class that implements the interface must provide code details for all the methods of the interface.

• A class can implement many interfaces but can extend only one class.

What Is an Interface?An interface is similar to an abstract class, except that it cannot have any concrete methods or instance variables. It is a collection of abstract method declarations and constants; that is, static final variables. It is like a contract that the subclass must obey.Any class that implements an interface must implement some or all of the methods that are specified in that interface. If it does not implement all of the methods, then the class is an abstract class and a subclass of the abstract class must implement the remaining abstract methods. A class can implement many interfaces but can extend only one class. Java does not support inheritance from multiple classes, but it does support implementing multiple interfaces. For example:class Movie extends InventoryItem implements Sortable, Listable {

…}

As demonstrated earlier, Movie inherits all of the attributes and behaviors of InventoryItem. In addition, it now must provide implementation details for all of the methods that are specified in the Sortable and Listable interfaces. Those methods can be used by other classes to implement specific behaviors such as a sort routine.

Page 377: Java Programming

Oracle10g: Java Programming 12-9

12-9 Copyright © 2004, Oracle. All rights reserved.

Examples of Interfaces

• Interfaces describe an aspect of behavior that different classes require.

• For example, classes that can be steered support the “steerable” interface.

• Classes can be unrelated.

SteerableNonsteerable

Examples of InterfacesInterfaces describe an aspect of behavior that many different classes require. The name of an interface is often an adjective such as Steerable, Traceable, Sortable, and so on. This is in contrast to a class name, which is usually a noun such as Movie or Customer.The Steerable interface may include such methods as turnRight(), turnLeft(), returnCenter(), and so on. Any class that needs to be steerable may implement the Steerable interface.The classes that implement an interface may be completely unrelated. The only thing that they may have in common is the need to be steered.For example, the core Java packages include a number of standard interfaces such as Runnable, Cloneable, and ActionListener. These interfaces are implemented by all types of classes that have nothing in common except the need to be Cloneable, or to implement an ActionListener.

Instructor NoteInterface is a way to bypass the multiple inheritance restriction that Java has.

Page 378: Java Programming

Oracle10g: Java Programming 12-10

12-10 Copyright © 2004, Oracle. All rights reserved.

Creating Interfaces

• Use the interface keyword:

• All methods are public abstract.• All variables are public static final.

public interface Steerable {

int MAXTURN = 45;

void turnLeft(int deg);

void turnRight(int deg);

}

Creating InterfacesYou can define an interface by using the interface keyword. All methods that are specified in an interface are implicitly public and abstract. Any variables that are specified in an interface are implicitly public, static, and final; that is, they are constants.Therefore, the interface definition that is shown in the slide is equivalent to the following definition, where the public, static, final, and abstract keywords have been specified explicitly.

public interface Steerable {public static final int MAXTURN = 45;public abstract void turnLeft(int deg);public abstract void turnRight(int deg);

}

Page 379: Java Programming

Oracle10g: Java Programming 12-11

Creating Interfaces (continued)Because interface methods are implicitly public and abstract, it is a generally accepted practice not to specify those access modifiers. The same is true for variables. Because they are implicitly public, static, and final(in other words, constants), you must not specify those modifiers.

Instructor NoteEvery field declaration in the body of an interface is implicitly public, static, and final. It is permitted, but strongly discouraged as a matter of style, to redundantly specify one or all of these modifiers for such fields.

Page 380: Java Programming

Oracle10g: Java Programming 12-12

12-12 Copyright © 2004, Oracle. All rights reserved.

Implementing Interfaces

Use the implements keyword:

public class Yacht extends Boat

implements Steerable {

public void turnLeft(int deg) {…}

public void turnRight(int deg) {…}

}

Implementing InterfacesThe slide shows an example of a Yacht class, that implements the Steerable interface. Yacht must implement some or all of the methods in any interface that it implements; in this case, Yacht may implement turnLeft() and turnRight().A class can implement more than one interface by specifying a list of interfaces separated by commas. Consider the following example:

public class Yachtextends Boatimplements Steerable, Taxable {

…}

Here, the Yacht class implements two interfaces: Steerable and Taxable. This means that the Yacht class must implement all the methods that are declared in both Steerable and Taxable.

Page 381: Java Programming

Oracle10g: Java Programming 12-13

12-13 Copyright © 2004, Oracle. All rights reserved.

Sort: A Real-World Example

• Is used by several unrelated classes• Contains a known set of methods• Is needed to sort any type of object• Uses comparison rules that are known only to the

sortable object• Supports good code reuse

SortA sort is a classic example of the use of an interface. Many completely unrelated classes must use a sort. A sort is a well-known and well-defined process that does not need to be written repeatedly.A sort routine must provide the ability to sort any object in the way that fits that particular object. The traditional programming approach dictates several subroutines and an ever-growing decision tree to manage each new object type. By using good OO programming technique and interfaces, you can eliminate all of the maintenance difficulties that are associated with the traditional approach.The Sortable interface specifies the methods that are required to make the sort work on each type of object that needs to be sorted. Each class implements the interface based on its specific sorting needs. Only the class needs to know its object comparison, or sorting rules.Implementing the sort in the OO way provides a model that supports very good code reuse. The sort code is completely isolated from the objects that implement the sort.

Instructor NoteUse the sort examples to demonstrate. Open the Demo.jws. There are two projects: Sort and ExtendedSort. Start with the Sort project and launch the SortApplication.java for a simple demonstration. Use the ExtendedSort project for a more complex demonstration. Launch the ExtendedSortApplication.java file to demonstrate a double sort application.

Page 382: Java Programming

Oracle10g: Java Programming 12-14

12-14 Copyright © 2004, Oracle. All rights reserved.

Overview of the Classes

• Created by the sort expert:

• Created by the movie expert:

public classMyApplication

public class Movieimplements Sortable

public interface Sortable

public abstract class Sort

Overview of the ClassesThe slide shows the three classes and one interface that are involved in sorting a list of videos. The classes are divided into two categories:

• Classes that are created by the sort expert, who knows all about sort algorithms but nothing about individual objects that people may want to sort

• Classes that are created by the movie expert, who knows all about movies, but nothing about sort algorithms

You see how interfaces can separate these two types of developers, enabling the separation of unrelated areas of functionality. Classes and Interfaces Used by the Example

• The Sortable interface declares one method: compare(). This method must be implemented by any class that wants to use the sort class methods.

• The Sort class is an abstract class that contains sortObjects(), which is a method to sort an array of objects. Most sort algorithms work by comparing pairs of objects. sortObjects() does this comparison by calling the compare() method on the objects in the array.

• The Movie class implements the Sortable interface. It contains a compare() method that compares two Movie objects.

• MyApplication represents any application that must sort a list of movies. It can be a form displaying a sortable list of movies.

Page 383: Java Programming

Oracle10g: Java Programming 12-15

12-15 Copyright © 2004, Oracle. All rights reserved.

How the Sort Works

MyApplication passes an array of movies to Sort.sortObjects().

sortObjects()asks a movie to

compare itself with another movie.

The movie returns the result of the comparison.

sortObjects()returns the sorted list.

1

23

4

Sort

Movie

MyApplication

How the Sort WorksThe slide shows the process of sorting a list of objects. The steps are as follows:

1. The main application passes an array of movies to Sort.sortObjects().2. sortObjects()sorts the array. Whenever sortObjects() needs to compare two

movies, it calls the compare() method of one movie, passing it with the other movie as a parameter.

3. The movie returns the results of the comparison to sortObjects().4. sortObjects() returns the sorted list.

Instructor NoteThe java.lang.Comparable interface that is used with Collections.sort(List)from the java.util package provides the developer with ready-made sort functionality. The class implementing the Comparable interface only needs to implement an int compareTo(Object o) method, that returns a –1, 0, or 1 for a less than, equal to, or greater than result, respectively.

Page 384: Java Programming

Oracle10g: Java Programming 12-16

12-16 Copyright © 2004, Oracle. All rights reserved.

The Sortable Interface

Specifies the compare() method:

public interface Sortable {

// compare(): Compare this object to another object

// Returns:

// 0 if this object is equal to obj2

// a value < 0 if this object < obj2

// a value > 0 if this object > obj2

int compare(Object obj2);

}

The Sortable InterfaceThe Sortable interface specifies all of the methods and constants that are required for a class to be sortable. In the example, the only method is compare(). Any class that implements Sortable must provide a compare() method that accepts an Object argument and returns an int.The result of the compare() method is as follows:

Note: It is entirely up to the implementer of compare() to determine the meaning of “greater than,” “less than,” and “equal to.”

Value Meaning

Positive integer This object is greater than the argument. Negative integer This object is less than the argument. Zero This object is equal to the argument.

Page 385: Java Programming

Oracle10g: Java Programming 12-17

12-17 Copyright © 2004, Oracle. All rights reserved.

The Sort Class

Holds sortObjects():

public abstract class Sort {

public static void sortObjects(Sortable[] items) {

// Step through the array comparing and swapping;

// do this length-1 times

for (int i = 1; i < items.length; i++) {

for (int j = 0; j < items.length - 1; j++) {

if (items[j].compare(items[j+1]) > 0) {

Sortable tempitem = items[j+1];

items[j+1] = items[j];

items[j] = tempitem; } } } } }

The Sort ClassThe Sort class contains the sortObjects() method that sorts an array of Sortableobjects. sortObjects() accepts an array of Sortable as its argument. It is legal syntax to specify an interface type for a method’s argument; in this case, it ensures that the method will be asked to sort only objects that implement the Sortable interface. In the example, sortObjects() executes a simple sort that steps through the array several times, and compares each item with the next one and swaps them if necessary. When sortObjects() needs to compare two items in the array, it calls compare() on one of the items, passing the other item as the argument. Note that sortObjects() knows nothing about the type of object that it is sorting. It knows only that they are Sortable objects, and therefore it knows that it can call a compare()method on any of the objects, and it knows how to interpret the results.Interface as a ContractYou can think of an interface as a contract between the object that uses the interface and the object that implements the interface. In this case, the contract is as follows:

• The Movie class (the implementer) agrees to implement a method called compare(), with parameters and return value specified by the interface.

• The Sort class (the user) agrees to sort a list of objects in the correct order.

Page 386: Java Programming

Oracle10g: Java Programming 12-18

12-18 Copyright © 2004, Oracle. All rights reserved.

The Movie Class

Implements Sortable:

public class Movie extends InventoryItemimplements Sortable {

String title; public int compare(Object movie2) {String title1 = this.title;String title2 = ((Movie)movie2).getTitle();return(title1.compareTo(title2));

}}

The Movie classThe Movie class implements the Sortable interface. To call Sort.sortObjects(), it must implement the Sortable interface, and if it implements the Sortable interface, then it must implement the compare() method; this is the contract. The compare() method takes an Object as an argument and compares it with the object on which it was called. In this case, you use the String compareTo() method to compare the two title strings. compareTo() returns a positive integer, a negative integer, or zero depending on the relative order of the two objects. When implementing compare(), you can compare the two objects in any way you like, as long as you return an integer that indicates their relative sort order.Note: In the example, movie2 is an Object. So, it must be cast to Movie before you can call getTitle() to get its title.

Page 387: Java Programming

Oracle10g: Java Programming 12-19

12-19 Copyright © 2004, Oracle. All rights reserved.

Using the Sort

Call Sort.sortObjects(Sortable []) with an array of Movie as the argument:

class myApplication {

Movie[] movielist;

… // build the array of Movie

Sort.sortObjects(movielist);

}

Using the SortTo use the sort, you call Sort.sortObjects(Sortable []) from your application, passing the array of objects that you want sorted. Each object that you want to sort must implement the Sortable interface and provide the required compare() method. Only the class implementing Sortable knows exactly how its objects are sorted.You can make other types of objects in your application sortable. For example, you can make the Rental and Member classes implement the Sortable interface and add a compare()method to each class. Then, you can sort an array of Rental or Member by calling Sort.sortObjects(). The compare() method in each of the classes can be radically different or fundamentally the same. The only requirement is that the compare() methods return an integer to indicate the relative sort order of the objects.

Page 388: Java Programming

Oracle10g: Java Programming 12-20

12-20 Copyright © 2004, Oracle. All rights reserved.

Using instanceof with Interfaces

• Use the instanceof operator to determine whether an object implements an interface.

• Use downcasting to call methods that are defined in the interface:

public void aMethod(Object obj) {

if (obj instanceof Sortable)

((Sortable)obj).compare(obj2);

}

Using instanceof with InterfacesIn the lesson about inheritance, you learned how to use the instanceof operator to test whether the run-time type of an object matched a certain type.You can also use instanceof with interfaces, as shown by the method in the slide. The method takes an argument whose compile-time type is Object. At run time, the argument can be any kind of object inherited from Object. The instanceof operator tests the object to see whether it is an instanceof Sortable. In other words, does the object support the Sortable interface?This means that you do not care what kind of object you are dealing with. Your concern is whether the object is capable of having the compare() method called on it.If the object does implement the Sortable interface, then you cast the object reference into Sortable so that the compiler lets you call the compare() method.

Page 389: Java Programming

Oracle10g: Java Programming 12-21

12-21 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:• An abstract class cannot be instantiated.• An abstract method has a signature but no code.• An interface is a collection of abstract methods to

be implemented elsewhere.• A class can implement many interfaces.• Implementing more than one interface is

comparable to multiple inheritance.

Page 390: Java Programming

Oracle10g: Java Programming 12-22

12-22 Copyright © 2004, Oracle. All rights reserved.

Practice 12: Overview

This practice covers:• Making an interface and abstract class• Implementing the java.lang.Comparable

interface to sort objects• Testing the abstract and interface classes

Practice 12: OverviewNote: To complete this practice, you must load a new workspace and use its contents. Before starting this practice, open the \labs\les12start directory, load the OrderEntryWorkspaceLes12Start workspace, to continue with this practice.Viewing the model: To view the course application model up to this practice, load the OrderEntryWorkspaceLes11 workspace. In the Applications – Navigator node, expand the OrderEntryWorkspaceLes11 – OrderEntryProjectLes11 -Application Sources – oe, and double-click the UML Class Diagram1 entry. This diagram displays all the classes created to this point in the course.

Page 391: Java Programming

Oracle10g: Java Programming 12-23

Practice 12: Structuring Code by Using Abstract Classes and InterfacesGoalThe goal of this practice is to learn how to create and use an abstract class, and how to create and use an interface.Note: To complete this practice, you must load a new workspace and use its contents. Before starting this practice, open the \labs\les12start directory, load the OrderEntryWorkspaceLes12Start workspace, to continue with this practice. The solution for this practice is found in the \labs\les12 directory, by loading the OrderEntryWorkspaceLes12 workspace.Your AssignmentThe OrderItem class currently only tracks a product as an integer. This is insufficient for the business, which must know the name, description, and retail price of each product. To meet this requirement, you create an abstract class called Product, and define three concrete subclasses called Software, Hardware, and Manual.To support the business requirement of computing a sales tax on the hardware products, you create an interface called Taxable that is implemented by the Hardware subclass.To test your changes, you must modify DataMan to build a list of Product objects, and provide a method to find a product by its ID.

• Modify OrderItem to hold an object reference for a Product, and not an integer for ID of product, and also change Order to find a Product by its ID value.

• Compile and run OrderEntry class to test the changes.Create an Abstract Class and Three Supporting Subclasses

1. Add a public abstract class called Product to the OrderEntryProject.a. Declare the following attributes and their getXXX() and setXXX() methods.

Hint: Use the JDeveloper Class Editor to rapidly build this class.Note: Remember to add the abstract keyword before the class keyword in the Source code after the Product.java file is created.private static int nextProductId = 2000;private int id;private String name;private String description;private double retailPrice;

b. Define a public no-arg constructor that assigns the nextProductId to the ID of a new product object, before incrementing nextProductId.

c. Add a public String toString() method to return the ID, name, and retailPrice. Prefix with the class name by using getClassName(this) from the Util class lso format retailPricewith Util.toMoney()

d. Compile and save the Product class.e. Use JDeveloper and its Class Editor to create three concrete subclasses of the

Product class, each with attributes and initial values that are listed in the table on the next page (generate or add the appropriate get and set methods):

Page 392: Java Programming

Oracle10g: Java Programming 12-24

Practice 12: Structuring Code by Using Abstract Classes and Interfaces (continued)1.e. (continued)

Subclass AttributesSoftware String license = "30 Day Trial";Hardware int warrantyPeriod = 6;Manual String publisher = "Oradev Press";

f. Modify the no-arg constructor for Software, Hardware, and Manual subclasses to accept three arguments for the product name, description, and price. Use this code example for the Software class as an example:public Software(String name,String desc,double price){

setName(name);setDescription(desc);setRetailPrice(price);

}g. Compile and save all your new subclasses.

Modify DataMan to Provide a List of Products and a Finder MethodUse the new class definitions in the DataMan class to build an inventory of products.

2. In DataMan, create an object to hold a collection of products.a. Create a private static inner class called ProductMap that extends

HashMap.Note: Remember to import java.util.HashMap.

b. In the ProductMap inner class, create the following method to add product objectsto the collection. The ID is the key, and object reference is the value:public void add(Product p) {

String key = Integer.toString(p.getId());put(key, p); // use inherited put() method

}c. Declare a private static ProductMap variable called products. For example:

private static ProductMap products = null;d. Compile and save your DataMan class.

3. Create a method to populate the ProductMap variable with product objects.a. Create the method called buildProducts() in the DataMan class as follows:

public static void buildProducts() {if (products != null) return;products = new ProductMap();products.add(new Product());

}b. Save and compile your code. Explain the compilation error that is listed for the line

adding the Product to the products map.

Page 393: Java Programming

Oracle10g: Java Programming 12-25

Practice 12: Structuring Code by Using Abstract Classes and Interfaces (continued)c. Fix the compilation error by adding concrete subclasses of the Product class.

Replace the line of code products.add(new Product()) with the following text:Note: Either copy the following code, or to save time, cut and paste the lines of code from a file called \labs\les12.txt:products.add(

new Hardware("SDRAM - 128 MB", null, 299.0));products.add(new Hardware("GP 800x600", null, 48.0));products.add(

new Software("Spreadsheet-SSP/V2.0", null, 45.0));products.add(new Software("Word Processing-SWP/V4.5",null,65.0));

products.add(new Manual("Manual-Vision OS/2x +", null, 125.0));

d. Compile the DataMan code and save your changes. Your compilation shouldwork this time.

e. At the end of the file, in the static block of DataMan, add a call to the buildProducts() method.

f. Add the following method called findProductById() to return a Productobject matching a supplied ID.public static Product findProductById(int id) {

String key = Integer.toString(id);return (Product) products.get(key);

}Note: Because products is a HashMap, you simply find the product object byusing its key; that is, the ID of the product.

g. Compile and save the changes to the DataMan class.h. Test the DataMan code, and additional classes, by printing the product that is found

by its ID. Add the following line to OrderEntry class at the end of main():System.out.println("Product is: " +

DataMan.findProductById(2001));i. Compile, save, and run the OrderEntry application to test the code.

Page 394: Java Programming

Oracle10g: Java Programming 12-26

Practice 12: Structuring Code by Using Abstract Classes and Interfaces (continued)Optional Extra CreditModify OrderItem to Hold Product Objects

4. Replace usages of the product variable as an int type with the Product class.a. In OrderItem.java, change the type declaration for the product instance

variable to be Product instead of int.b. Replace the two argument constructors with a single argument called newProduct

whose type is Product; that is, remove productId and itemPrice arguments.c. Change the body of the constructor to store the newProduct in the product

variable, and set the unitPrice to be the value that is returned by calling the getRetailPrice() method of the product object.

d. Modify getProduct() method to return Product instead of an int, and change setProduct() method to accept a Product instead of an int.

e. Alter the toString() method to display the item total instead of the unitPrice.Hint: Use the getItemTotal() method.

f. Compile and save your code changes. Only eliminate syntax errors from the OrderItem class. Errors that are reported for the Order class are corrected in the next step of this lab.

Modify Order to Add Product Objects into OrderItemAlter the Order.java class to use the Product objects instead of an int value.

5. Make the following changes to the addOrderItem() method:a. Rename the argument to be productId, and in the for loop replace:

productFound = (item.getProduct() == product);

withproductFound =

(item.getProduct().getId() == productId);b. In the else section of the if statement, call findProductById() from

DataMan by using the productId value. If a product object is found, then create the OrderItem by using with the product object; otherwise, do nothing. For example:

item = new OrderItem(product, 5.0);items.addElement(item);

becomes:Product p = DataMan.findProductById(productId);if (p != null) {

item = new OrderItem(p);items.addElement(item);

}

Page 395: Java Programming

Oracle10g: Java Programming 12-27

Practice 12: Structuring Code by Using Abstract Classes and Interfaces (continued)6. Test changes that are made to your code supporting the Product class and its subclasses,

by modifying OrderEntry class to use the new product ID values.a. Because the ID of Product objects (or its subclasses) start at 2000, edit the file

OrderEntry.java, replacing parameter values in all the calls to the order.addOrderItem() method, as shown by the following table:eplace With

101 2001102 2002

b. Save, compile, and run the OrderEntryProject project, and check the changes to the printed items. Check whether the price calculations are still correct.

Create and Implement the Taxable Interface7. Create an interface called Taxable.

a. Right-click the OrderEntryProject.jpr file in the Navigator, and select New … from the pop-up menu. Enter Taxable in the class name and ensure that you clear Generate Default Constructor.Then, click the OK button.

b. In the Code Editor, replace the keyword class with the keyword interface.c. Add the following variable and method definitions to the interface:

double TAX_RATE = 0.10;double getTax(double amount);

Note: Remember that all variables are implicitly public static final, and that methods are all implicitly public.The implementer of the interface must multiply the amount, such as a price, by the TAX_RATE and return the result as a double.

d. Compile and save the interface.8. Edit the Hardware class to implement the Taxable interface.

a. Add the bold text to the class definition to implement the interface, as shown:public class Hardware extends Product

implements Taxable {b ompile the Hardware class and explain

the errorc dd the following method to completethe implementation of the interface

public double getTax(double amount) {return amount * TAX_RATE;

}Note: To perform the two steps above, select the Tools > Implement Interface menu item, and select oe.Taxable from the tree in the Implement Interface window, then click OK. JDeveloper generates all the code except for the return value calculation. You can modify the generated body to return the desired result, as shown above. Alternatively, you can also type the code manually in the Source.

d. Compile and save the Hardware class.

Page 396: Java Programming

Oracle10g: Java Programming 12-28

Practice 12: Structuring Code by Using Abstract Classes and Interfaces (continued)9. Change the OrderItem class to obtain the tax for each item.

a. Add a public double getTax() method to determine whether the Productin the item is taxable. If the product is taxable, then return the tax amount for the item total (use getItemTotal() method); otherwise, return 0.0. For example:

double itemTax = 0.0;if (product instanceof Taxable){

itemTax =((Taxable) product).getTax(getItemTotal());}

b. Modify the toString() method to display the tax amount for the item, if and only if the product is taxable. Use the getTax() method that you created, and format the value with Util.toMoney().

c. To view changes, compile OrderItem.java, and run OrderEntry.10. Modify the Order class to display the tax, and order total to include the tax.

a. In the showOrder() method, add a local double variable called taxTotalinitialized to 0.0 that accumulates the total tax for the order.

b. Modify the for loop by using the Enumeration to call the getTax() method for each item, and add the value to taxTotal.Hint: To do this, you must cast the return value of e.nextElement() to OrderItem

c dd three System.out.println() statementsafter the loop one to print the taxTotalthe second to print the orderTotalincluding taxTotaland the last without a parameter toprint a blank line se the Util.toMoney()method to format the totals

d o view results compile and saveOrder.java and then run OrderEntry

Page 397: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Throwing and Catching Exceptions

Schedule: Timing Topic45 minutes Lecture25 minutes Practice70 minutes Total

Page 398: Java Programming

Oracle10g: Java Programming 13-2

13-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Explain the basic concepts of exception handling• Write code to catch and handle exceptions• Write code to throw exceptions• Create your own exceptions

Lesson AimMany Java methods in the Java Development Kit (JDK) class library throw an exception when they encounter a serious problem that they do not know how to handle. This lesson explains how exceptions work in Java, and shows you how to handle such exceptions in your applications.

Page 399: Java Programming

Oracle10g: Java Programming 13-3

13-3 Copyright © 2004, Oracle. All rights reserved.

What Is an Exception?

An exception is an unexpected event.

What Is an Exception?An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. For example, trying to access an element outside the bounds of an array, trying to divide a number by zero, and trying to access a URL with an invalid protocol are all exceptions.

What Is an Error?An error in Java is an unrecoverable abnormal condition. For example, an error condition exists if there is some internal error in Java Virtual Machine (JVM) or if JVM runs out of memory.

What Is the Difference?Your code can handle an exception and move on; if an error occurs, then your program must exit.

Instructor NoteThere are some instances when errors can be caught and handled. For example, under some circumstances your code can catch the error java.lang.ThreadDeath. See the javadoc for details.

Page 400: Java Programming

Oracle10g: Java Programming 13-4

13-4 Copyright © 2004, Oracle. All rights reserved.

How Does Java Handle Exceptions?

• A method throws an exception.• A handler catches the exception.

Yes No

Handlerfor this

exception?

Exception object

Exception Handling in JavaWhen an exception occurs within a Java method, the method creates an Exception object and hands it off to the run-time system. This process is called throwing an exception. The Exception object contains information about the exception, including its type and the state of the program when the error occurred. When a Java method throws an exception, the run-time system searches all the methods in the call stack in sequence to find one that can handle this type of exception. In Java terminology, this method catches the exception.If the run-time system does not find an appropriate exception handler, then the whole program terminates.The following slides discuss some of the advantages of Java’s exception handling over traditional error handling in other languages.

Page 401: Java Programming

Oracle10g: Java Programming 13-5

13-5 Copyright © 2004, Oracle. All rights reserved.

Advantages of Java Exceptions: Separating Error Handling Code

• In traditional programming, error handling often makes code more confusing to read.

• Java separates the details of handling unexpected errors from the main work of the program.

• The resulting code is clearer to read and, therefore, less prone to bugs.

Advantage 1: Separating Error Handling Code from Other CodeIn traditional programming, error handling often makes code more confusing to read. For example, if you want to write a function that reads the first line of a file, then the pseudocode for the function may be:

readFirstLine {open the file; // the open could failread the first line; // the read could failclose the file; // the close could fail

}

The traditional way of checking for the potential errors in this function is to test each possible error and set an error code. The table on the next page compares the traditional method with Java’s exception handling; the original three statements are in bold.

Page 402: Java Programming

Oracle10g: Java Programming 13-6

Advantage 1: Separating Error Handling Code from Other Code (continued)

Java separates the details of handling unexpected errors from the main work of the program, making the code clearer to read (which, in turn, makes it less prone to bugs).

Instructor NoteThe term try means that the code is trying something that may throw an exception; catchmeans that the code is handling the exception.

Traditional Error Handling Java Exception Handling readFirstLine { int errcode = 0; open the file; if (openError) { errcode = OPEN_ERR; } else { read the first line; if (readError) { errcode = READ_ERR; } close the file; if (closeError) { errcode = errcode and CLOSE_ERR; } } return errcode; }

readFirstLine { try { open the file; read the first line; close the file; } catch (openError) { handle error; } catch (readError) { handle error; } catch (closeError) { handle error; } }

Page 403: Java Programming

Oracle10g: Java Programming 13-7

13-7 Copyright © 2004, Oracle. All rights reserved.

Advantages of Java Exceptions:Passing Errors Up the Call Stack

method4

method3

method2

method1 //handle error

Error code

Error code

Error code

method4

method3

method2

Method1//handle ex

Exceptionex

Each method checks for errors and returns an error code to its calling method.

method4 throws an exception; eventually method1 catches it.

Traditional error handling

Java exceptions

Advantage 2: Passing Errors Up the Call StackA Java exception is sent immediately to the appropriate exception handler; there is no need to have if statements at each level to pass the error up the call stack. For example, a series of nested methods can handle errors as follows:

method1 handles all errorsmethod1 calls method2method2 calls method3method3 calls method4

The following table shows the steps that are taken by traditional error handling and Java exception handling if an error occurs in method4. Exception handling requires fewer steps.Traditional Error Handling Java Exception Handling

1. method4 returns an error code to method3.

2. method3 checks for errors, and passes the error code to method2.

3. method2 checks for errors, and passes the error code to method1.

4. method1 handles the error.

1. method4 throws an exception and it is propagated to method3.

2. method3 receives a return from method 4 and propagates it to method2.

3. method2 receives a return from method3 and propagates it to method1.

4. method1 catches and handles the exception.

Page 404: Java Programming

Oracle10g: Java Programming 13-8

13-8 Copyright © 2004, Oracle. All rights reserved.

method3

Advantages of Java Exceptions: Exceptions Cannot Be Ignored

If method3 ignores the error, then it will never be handled.

method4

method2

method1 //handle error

Error code

The exception must be caught and handled somewhere.

Traditional error handling

Java exceptions

method4

method3

method2

method1//handle ex

Exceptionex

Advantage 3: Exceptions Cannot Be IgnoredAfter a method has thrown an exception, it cannot be ignored; it must be caught and handled somewhere. In the example in the slide, the programmer writing method3, method2, or method1 can choose to ignore the error code that is returned by method4, in which case the error code will be lost.

Instructor NoteThe following slide describes the two types of exceptions. The compiler requires that checked exceptions be caught and handled somewhere. The compiler does not make this requirement for run-time exceptions, but an uncaught run-time exception causes the program to terminate. The details of the slide are true only for checked exceptions, but it is true that no exception can be ignored. You may want to make this point here, or you may want to leave it until the two types of exceptions have been covered.The Java exceptions diagram uses dotted arrows to show the exception propagating, by returning from method4 to method3, and then from method3 to method2. It uses a solid arrow to show a return from method2 to method1. In this case, the dotted lines indicate that the exception has just been propagated, and the solid line indicates that the exception has been picked up and caught by the caller.

Page 405: Java Programming

Oracle10g: Java Programming 13-9

13-9 Copyright © 2004, Oracle. All rights reserved.

Checked Exceptions, Unchecked Exceptions, and Errors

All errors and exceptions extend the Throwable class.

Throwable

Error Exception

Unrecoverable errors

Checkedexceptions

Unchecked (run-time) exceptions

RuntimeException

Standard Error and Exception ClassesAll the standard errors and exceptions in Java extend the Throwable class. ErrorsErrors are extensions of the Error class. If an error is generated, then it normally indicates a problem that will be fatal to the program. Examples of this type of error are: running out of memory or being unable to load a class. Do not catch Errors in your Java code.Unchecked ExceptionsUnchecked (or run-time) exceptions are extensions of the RuntimeException class. All the standard run-time exceptions (for example, dividing by zero or attempting to access an array beyond its last element) are extensions of RuntimeException. You can choose what to do with run-time exceptions; you can check for them and handle them, or you can ignore them. If a run-time exception occurs and your code does not handle it, JVM terminates your program and prints the name of the exception and a stack trace.

Page 406: Java Programming

Oracle10g: Java Programming 13-10

Standard Error and Exception Classes (continued)Checked ExceptionsChecked exceptions are extensions of the Exception class. Checked exceptions must be caught and handled somewhere in your application; this rule is enforced by the compiler. Exceptions that you create yourself must extend the Exception class. Note: Run-time exceptions do not need to be caught, but they cannot be ignored. If they are not caught, then the program terminates with an error.

Instructor NoteAsk the students: Why must you extend the Exception class?If you subclass the Exception class to create a “Checked” exception (that is, if the error is significant enough), then the developers who use your Exception class are forced to explicitly handle the exception when it is thrown. This forces a more robust code to be written.Subclass a RuntimeException if the developer does not want to force the developers to catch the exception. In the case of subclassing a RuntimeException, the type of errors must be of a less critical type, which does not cause the code to terminate or function badly if it is not handled.In general, to promote a robust code, subclass the Exception class to force the developer to manage the exception before the code is compiled.

Page 407: Java Programming

Oracle10g: Java Programming 13-11

13-11 Copyright © 2004, Oracle. All rights reserved.

What to Do with an Exception

• Catch the exception and handle it.• Allow the exception to pass to the calling method.• Catch the exception and throw a different

exception.

Handling ExceptionsIf you call a method that may throw a checked exception, then you have three choices:

• Catch the exception and handle it.• Allow the exception to pass through your method; another handler somewhere else

must handle it.• Catch the exception and throw a different exception; the new exception must be

handled by another handler somewhere else.Run-Time ExceptionsYour code does not need to handle run-time exceptions; these are handled by JVM. JVM handles run-time exceptions by terminating your program; if you do not want a run-time exception to have this effect, then you must handle it.

Page 408: Java Programming

Oracle10g: Java Programming 13-12

13-12 Copyright © 2004, Oracle. All rights reserved.

Catching and Handling Exceptions

• Enclose the method call in a try block.

• Handle each exception in a catchblock.

• Perform any final processing in a finally block.

try {

// call the method

}

catch (exception1) {

// handle exception1

}

catch (exception2) {

// handle exception2

}…

finally {

// any final processing

}

Catching and Handling ExceptionsIf a block of code calls one or more methods that may throw exceptions, then enclose the code in a try block, with one or more catch blocks immediately after it. Each catchblock handles a particular exception.You can add a finally block after all the catch blocks. A finally block may be executed, depending on what happens before the block (for example, System.exit).How Do You Know Whether a Particular Java Method Throws an Exception?All the standard Java classes are documented in the JDK documentation; part of the specification for each method is a list of exceptions that the method may throw. Whenever you call a Java method, you must know what exceptions may arise as a consequence. For example, the following are declarations that are taken from the JDK documentation for java.io.FileInputStream:

public FileInputStream(String name)throws FileNotFoundException …

public int read() throws IOExceptioneneral uidelines for try-catch-blocktructures

try block must have at least one catchblock or a finally block

- catch block is required for checkedexceptions unless it ispropagated

try block can have more than one catchblock

Page 409: Java Programming

Oracle10g: Java Programming 13-13

13-13 Copyright © 2004, Oracle. All rights reserved.

Catching a Single Exception

int qty;

String s = getQtyFromForm();

try {

// Might throw NumberFormatException

qty = Integer.parseInt(s);

}

catch ( NumberFormatException e ) {

// Handle the exception

}

// If no exceptions were thrown, we end up here

Catching a Single ExceptionThe example in the slide uses Integer.parseInt() to process the value that an end user has entered on a form. parseInt() throws a NumberFormatException if the string is not an integer value. The catch block can handle this exception by prompting the user to enter the value again.

Instructor NoteYou can show the JDK documentation for Integer.parseInt(String s), or ask students to look it up themselves to find out exactly what it does.Because NumberFormatException is a run-time exception, your code does not have to catch it, although in this case, it is a good idea.

Page 410: Java Programming

Oracle10g: Java Programming 13-14

13-14 Copyright © 2004, Oracle. All rights reserved.

Catching Multiple Exceptions

try {

// Might throw MalformedURLException

URL u = new URL(str);

// Might throw IOException

URLConnection c = u.openConnection();

}

catch (MalformedURLException e) {

System.err.println("Could not open URL: " + e);

}

catch (IOException e) {

System.err.println("Could not connect: " + e);

}

Catching Multiple ExceptionsThe example constructs a URL and then connects to it. The example uses two catchblocks, because there are two possible exceptions that can occur. If an exception occurs in the try block, then JVM checks each catch handler in sequence until it finds one that deals with that type of exception; the rest of the try block is not executed.A catch statement catches the exception that is specified as well as any of its subclasses. For example, the javadoc for MalformedURLException shows that it extends IOException; thus, you can replace the two catch blocks with one:catch (IOException e) {

System.err.println("Operation failed: " + e);}

You will use a single catch block if you wanted your code to behave in the same way for either exception. Order of catch StatementsNote that you get a compiler error if you specify a catch handler for a superclass first, followed by a catch handler for a subclass. This is because the superclass catch handler hides the subclass catch handler, which will therefore never see any exceptions. For example, reversing the two catch blocks in the example causes a compiler error.

Page 411: Java Programming

Oracle10g: Java Programming 13-15

13-15 Copyright © 2004, Oracle. All rights reserved.

Cleaning Up with a finally Block

FileInputStream f = null;

try {

f = new FileInputStream(filePath);

while (f.read() != -1)

charcount++;

}

catch(IOException e) {

System.out.println("Error accessing file " + e);

}

finally {

// This block is always executed

f.close();

}

Cleaning Up with a finally BlockThe example opens a file and counts the characters in the file. The file is then closed, even if the read operation causes an exception. A finally block is useful when you want to release system resources, such as open files. A finally block is executed regardless of how the try block exits:

• Normal termination, by falling through the end brace• Because of return or break statement• Because an exception was thrown

Note: f.close() can throw an IOException and, therefore, must be enclosed in its own try…catch block inside the finally block.

Instructor NoteThe FileInputStream constructor throws the FileNotFoundException, and read() throws the IOException. However, FileNotFoundException is a subclass of IOException, so the catch block works in either case.Note that you can have a finally block without any intervening catch blocks:

try { … }

finally { … }

You cannot, however, have a finally block on its own, without a try block preceding it.

Page 412: Java Programming

Oracle10g: Java Programming 13-16

13-16 Copyright © 2004, Oracle. All rights reserved.

Catching and Handling Exceptions:Guided Practice

void makeConnection(String url) {

try {

URL u = new URL(url);

}

catch (MalformedURLException e) {

System.out.println("Invalid URL: " + url);

return;

}

finally {

System.out.println("Finally block");

}

System.out.println("Exiting makeConnection");

}

Catching and Handling ExceptionsExamine the code that is shown in the slide, and describe what it is doing. Note that the urlargument is a string such as http://www.oracle.com.

1. What will be printed to standard output if the URL constructor executes without throwing an exception?

2. What will be printed to standard output if the URL constructor throws a MalformedURLException?

Instructor Note1. Finally block

Exiting makeConnection2. Invalid URL: <url>

Finally block

Page 413: Java Programming

Oracle10g: Java Programming 13-17

13-17 Copyright © 2004, Oracle. All rights reserved.

Catching and Handling Exceptions: Guided Practice

void myMethod () {

try {

getSomething();

} catch (IndexOutOfBoundsException e1) {

System.out.println("Caught IOBException ");

} catch (Exception e2) {

System.out.println("Caught Exception ");

} finally {

System.out.println("No more exceptions ");

}

System.out.println("Goodbye");

}

Catching and Handling Exceptions (continued)1. What will be printed to standard output if getSomething() throws an

IllegalArgumentException? 2. Would anything change if the order of the two catch blocks was reversed? That is:

…try …catch (Exception e) {…}catch (IndexOutOfBoundsException e) {…}…

Instructor Note1. Caught Exception

No more exceptionsGoodbye

2. The code will not compile because the second catch block can never be reached.The relevant subclassing information is:public class RuntimeException extends Exceptionpublic class IndexOutOfBoundsException extends RuntimeExceptionpublic class IllegalArgumentException extends RuntimeException

Page 414: Java Programming

Oracle10g: Java Programming 13-18

13-18 Copyright © 2004, Oracle. All rights reserved.

Allowing an Exception to Pass to the Calling Method

• Use throws in the method declaration.• The exception propagates to the calling method.

public int myMethod() throws exception1 {

// code that might throw exception1

}

public URL changeURL(URL oldURL)

throws MalformedURLException {

return new URL("http://www.oracle.com");

}

Allowing an Exception to Pass to the Calling MethodIf you cannot meaningfully handle an exception locally, or you choose not to, then it can be passed back to the code that called your method.In the example in the slide, the URL constructor can throw a MalformedURLException, but the method does not catch this exception locally. Instead, the exception passes automatically to the method that called changeURL().If you want an exception to propagate to the calling method, then you must declare the exception in your method declaration:public URL changeURL(URL oldURL) throws MalformedURLException {

}

The method that calls changeURL() can catch MalformedURLException, or it can also let the exception pass through. If the calling method allows the exception to pass through, then it must also contain throws MalformedURLException in its declaration.

Page 415: Java Programming

Oracle10g: Java Programming 13-19

13-19 Copyright © 2004, Oracle. All rights reserved.

Throwing Exceptions

• Throw exceptions by using the throw keyword.• Use throws in the method declaration.

public String getValue(int index) throws

IndexOutOfBoundsException {

if (index < 0 || index >= values.length) {

throw new IndexOutOfBoundsException();

}

}

throw new Exception1();

Throwing ExceptionsYou can throw exceptions in your own code to indicate some abnormal situation. The exceptions that you throw can be standard system exceptions, or you can create your own.If you do decide to throw exceptions, remember that what you are really doing is creating an object and passing it to a higher-level method. Therefore, you must create this exception object by using the new operator, as shown in the slide.A method can throw multiple exceptions, in which case the exception names are separated by commas.Four types of exception are System, Application, Run-time and Custom. The java.lang.IndexOutOfBoundsException is a run-time Exception.

Page 416: Java Programming

Oracle10g: Java Programming 13-20

13-20 Copyright © 2004, Oracle. All rights reserved.

Creating Exceptions

Extend the Exception class.

public class UserFileException extends Exception {

public UserFileException (String message) {

super(message);

}

}

public class MyException extends Exception { … }

Creating ExceptionsYou can create your own exceptions by extending the Exception class. You must not extend the RuntimeException class because this is for common exceptions that need not be checked.The example creates an exception called UserFileException with one constructor that just calls the constructor of the superclass.You can create multiple exceptions for different circumstances in your code. For example, if your code accesses different files, then you can throw a different exception for each file. This approach is useful for several reasons:

• You can handle each exception differently.• If your exception handlers print out the exception, then this gives you or your users

more information about where the exception occurred.• You can customize your exception. For example, you can add a

UserFileException constructor that sets an attribute for the line number of the file and a method that prints out the line number.

Page 417: Java Programming

Oracle10g: Java Programming 13-21

13-21 Copyright © 2004, Oracle. All rights reserved.

Catching an Exception and Throwing aDifferent Exception

catch (exception1 e) {

throw new exception2(…);

}

void readUserFile() throws UserFileException {

try {

// code to open and read userfile

}

catch(IOException e) {

throw new UserFileException(e.toString());

}

}

Catching an Exception and Throwing a Different ExceptionThe example catches IOException and handles it by throwing UserFileException. You do this if you want this method to throw a different exception from other methods. The method uses the throws keyword in its declaration to indicate that it throws a UserFileException.

Page 418: Java Programming

Oracle10g: Java Programming 13-22

13-22 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to do the following:• Use Java exceptions for robust error handling• Handle exceptions by using try, catch, and

finally• Use the throw keyword to throw an exception• Use a method to declare an exception in its

signature to pass it up the call stack

Page 419: Java Programming

Oracle10g: Java Programming 13-23

13-23 Copyright © 2004, Oracle. All rights reserved.

Practice 13: Overview

This practice covers:• Creating a custom exception• Changing DataMan finder methods to throw

exceptions• Handling the exceptions when calling the DataMan

finder methods• Testing the changes to the code

Practice 13: OverviewNote: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les12 directory, load the OrderEntryWorkspaceLes12 workspace, and continue with this practice.Viewing the model: To view the course application model up to this practice, load the OrderEntryWorkspaceLes12 workspace. In the Applications – Navigator node, expand the OrderEntryWorkspaceLes12 – OrderEntryProjectLes12 -Application Sources – oe, and double-click the UML Class Diagram1 entry. This diagram displays all the classes created to this point in the course.

Page 420: Java Programming

Oracle10g: Java Programming 13-24

Practice 13: Throwing and Catching ExceptionsGoalThe goal of this practice is to learn how to create your own exception classes, throw an exception object by using your own class, and handle the exceptions.Note: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les12 directory, load the OrderEntryWorkspaceLes12 workspace, and continue with this practice.Your AssignmentThe application does not appropriately handle situations when an invalid customer ID is supplied to the DataMan.findCustomerById() method, or an invalid product ID is given to the DataMan.findProductById() method. In both cases, a null value is returned. Your tasks are to:

• Create a user-defined (checked) exception called oe.NotFoundException.• Modify DataMan.findCustomerById() to throw the exception when an

invalid customer ID is provided.• Modify the DataMan.findProductById()method in the DataMan class to

throw the exception if the given product ID is not valid (that is, not found).Create the NotFoundException Class

1. In the OrderEntryProject, create a new class called NotFoundException.a. Right-click the project name in the Navigator, and select New … from the pop-

up menu. From the New gallery window, ensure that the Category selected is General and the Item selected is Java Class. Enter the class name NotFoundException, and make it a subclass of java.lang.Exception.

b. Modify the default no-arg constructor to accept a message String argument, and pass the string to the superclass constructor. For example:

public NotFoundException(String message) {super(message);

}c. Compile and save the NotFoundException class.

Throw Exceptions in DataMan Find Methods and Handle Them in OrderEntry2. Edit DataMan.java, and modify the findCustomerById() method to throw

the NotFoundException when the given customer ID is not found in the array.a. At the end of the for loop, if the local customer object reference is null (that

is, the customer is not found), then throw an exception object, using the following error message structure in the constructor argument:"Customer with id " + custId + " does not exist“

b. Compile the DataMan class. Explain the error.c. Fix the error by modifying the method declaration to propagate the exception.d. Compile DataMan again. What errors do you get this time? Explain the errors.

Page 421: Java Programming

Oracle10g: Java Programming 13-25

Practice 13: Throwing and Catching Exceptions (continued)e. Fix the compilation errors by handling the exceptions with a try-catch block

in the OrderEntry class. For simplicity, use one try-catch block to handle all the calls to the DataMan.findCustomerById() methods. Alternatively, if desired, then handle each call in its own try-catch block.try { // calls to findCustomerById() here …}catch (NotFoundException e) {

// handle the error here …}

In the catch block, you can use the exception’s inherited methods to display error information. Use the following two methods to display error information:

- e.printStackTrace() to display the exception, message, and stack trace

- e.getMessage() to return the error message text as a String.f. Compile, save, and run OrderEntry.java. Test your code with the errors.

3. Now modify the findProductById() to throw NotFoundException when the supplied product ID is not found in the product map.

a. The findProductById() method calls get(key) to find a product from the HashMap. If get(key) returns a null, then throw a NotFoundException by using the following error message; otherwise, return product object found. You must also add the product declaration line and modify the current return statement. "Product with id " + id + " is not found"

b. Modify the findProductById() declaration to propagate the exception.c. Compile and save DataMan, and explain the compile time error reported.d. In the Order class, modify the addOrderItem() to propagate the exception.e. Compile the Order class, and explain why it compiles successfully.f. In OrderEntry.java, use a value of 9999 as the product ID in the first call

to order.addOrderItem(2001) ompile and runOrderEntry

xplain why the applicationterminates immediately afteradding product 9999

g n Order.java remove throws NotFoundExceptionfrom the end of the addOrderItem() methoddeclaration rite a try-catch block to

handle the exception in thismethodint ou must return from the methodin the catch block to ensure theitemTotal is not affected

h. Compile Order and run OrderEntry.java, and explain the difference in output results.

i. In OrderEntry, replace the 9999 product ID with 2001. Compile, save, and run.

Page 422: Java Programming
Page 423: Java Programming

Copyright © 2004, Oracle. All rights reserved.

User Interface Design: Swing BasicsPlanning the Application Layout

Schedule: Timing Topic55 minutes Lecture35 minutes Practice90 minutes Total

Page 424: Java Programming

Oracle10g: Java Programming 14-2

14-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Explain Abstract Window Toolkit (AWT), Swing,

and Java Foundation Classes (JFC)• Detail the Swing UI containment hierarchy• Describe how to use layout managers• Add UI containers to an application to group

components• Embed UI components into UI containers• Use the Swing pluggable look and feel

Lesson AimThis lesson shows you how to provide a Java applet or application with a graphical user interface based on Swing components, such as buttons and text fields. Participants learn how to embed Swing components into Swing containers and how to use layout managers to provide an interface that is usable across platforms.

Page 425: Java Programming

Oracle10g: Java Programming 14-3

14-3 Copyright © 2004, Oracle. All rights reserved.

Running Java UI Applications

Running Java UI ApplicationsJava applications and applets are not limited to run on any one platform. You can run them on any platform that supports a Java Virtual Machine (JVM) because each of the platforms has its own specific display methods and characteristics.Java provides layout managers that help to optimize the look and feel of your application for the platform on which it is running. This is performed dynamically without any need for code modification. This behavior is one of the aspects of the Java “write once, run anywhere” (WORA) concept.The screenshot on the slide uses different layout managers to produce the desired effect. It uses Border, Grid, and GridBag layouts. By combining different layout managers, you can obtain the layout that you want and deploy the program on multiple platforms.

Page 426: Java Programming

Oracle10g: Java Programming 14-4

14-4 Copyright © 2004, Oracle. All rights reserved.

AWT, Swing, and JFC

• AWT, or Abstract Window Toolkit (java.awt):– A graphical user interface library– The predecessor to Swing components and the

foundation for Swing and JFC• Swing (javax.swing):

– A more powerful graphical user interface library– Built on top of the AWT class hierarchy

• Java Foundation Classes (JFC):– A collection of APIs including: AWT, Swing,

Accessibility API, Pluggable Look and Feel– Java 2D API, Drag and Drop support (since JDK 1.2)

Abstract Window Toolkit (java.awt)The AWT was Java’s original toolkit or set of visual components for the development of graphical user interface applications. AWT is the foundation upon which Swing and the rest of the JFC are constructed. AWT was not designed for high-powered UI development, which can be appreciated when you understand that it has a smaller set of components. AWT classes are found in the java.awt package and its subpackages.

Swing (javax.swing)Swing provides lightweight components built on top of the AWT library. It provides many more components that are intended for high-powered user interface, which are more efficient than their AWT counterparts. Swing components adhere to the AWT event handling model that was introduced in JDK 1.1. Swing classes are found in the javax.swing package and its subpackages.

Page 427: Java Programming

Oracle10g: Java Programming 14-5

Java Foundation Classes (JFC)The Java Foundation Classes is a set of classes and APIs that was first released with JDK 1.1. The version of JFC that is included in JDK 1.2 contains:

• AWT and the Swing GUI components• Accessibility API for people with disabilities• Pluggable look and feel, to adapt the UI to an operating system look and feel• Java 2D API for two-dimensional graphics and imaging• Drag and drop support

Because Swing is the major component of JFC, the terms Swing and JFC are often used interchangeably. Oracle JDeveloper 10g supports JDK 1.4.2, so Swing is fully supported.Note: You can create Java client applications that rely on standard Swing components in your application. The Java client application in JDeveloper is known as a JClient application. When a JClient form has been deployed to a client machine, users can use it to display and manipulate data in the form. This course is not intended to teach you about JClient, only to show you how to develop Java applications using JDeveloper.

Page 428: Java Programming

Oracle10g: Java Programming 14-6

14-6 Copyright © 2004, Oracle. All rights reserved.

JButton JSlider JTree

JComboBox JTextField JProgressBar

InventoryItem

Swing Features

A set of visual components that have been available since JDK 1.1, but part of core JDK since version 1.2:• Lightweight components compared to AWT• Pluggable look and feel API• Many more components than AWT

The Swing PackageThe Swing components are all part of the javax.swing package, which was added in JDK 1.2. Swing transformed the Java UI development by providing lightweight components that could adapt to the look and feel of the operating system in which the application executed. Swing provides many more types of UI components for user interaction than found in AWT.Lightweight Versus Heavyweight ComponentsSwing components are considered lightweight, meaning that they are rendered (visually constructed) in their container window; that is, they are created within the Java environment. The container window is usually a native (operating system) window. However, AWT components are heavyweight, meaning that each component is rendered in its own native window. This makes Swing components smaller and more efficient than their AWT counterparts.

Page 429: Java Programming

Oracle10g: Java Programming 14-7

The Swing Package (continued)Pluggable Look and FeelDevelopers can use the pluggable look and feel feature of Swing to specify the look and feel of applications that are developed with Swing components. The default is to use the Java look and feel (called the Metal look and feel). By using the pluggable look and feel API, you can develop your application to use the native look and feel of whatever platform the application happens to be running on, or you can develop your own look and feel.

Instructor NoteThe javax.swing.UIManager class controls the look and feel of an application. Some simple code examples at the end of this lesson are provided to show how to change the look and feel for Swing applications.

Page 430: Java Programming

Oracle10g: Java Programming 14-8

14-8 Copyright © 2004, Oracle. All rights reserved.

Lightweight or Heavyweight Components?

Lightweight components• No dependence on native

peer code• Can have transparent

backgrounds• Most Swing components

are lightweight• When displayed, they can

appear nonrectangular• Must be displayed in

heavyweight container

Heavyweight components• Strong dependency on

native peer code• Each rendered in its own

opaque window• Early AWT components

were mostly heavyweight

• Include some Swingtop-level components (JFrame, JApplet, JDialog)

Using Lightweight and Heavyweight ComponentsHeavyweight components were developed in early releases of the AWT. Each heavyweight component is tightly associated with a native peer component in the client environment. When rendered, each heavyweight component relies on the creation of its own native opaque window. All top-level containers are heavyweight and provide the context for lightweight containers and components.Lightweight components must ultimately be displayed in heavyweight top-level containers, such as JFrame, JApplet, or JDialog. However, lightweight components are visually more flexible because they can be transparent, and appear nonrectangular. These features allow lightweight components to be easily adapted to a different look and feel. Lightweight components do not have a native peer, as they are rendered directly by the Java code. Therefore, lightweight components are more portable.Note: As a general rule, avoid mixing heavyweight and lightweight low-level components, such as buttons, text fields, and so on. In other words, avoid using AWT and Swing components in the same visual container or application.

Page 431: Java Programming

Oracle10g: Java Programming 14-9

14-9 Copyright © 2004, Oracle. All rights reserved.

Planning the UI Layout

Building a UI application involves planning, even more so when building Swing applications. Planning requires understanding the following concepts and their relationship:• UI containment hierarchy (a root component that

comprises nested containers and components)• Container levels and types (such as top-level or

intermediate containers)• Layout managers and their types (used by each

container)• Components that can be added into containers

Planning the UI LayoutBuilding a Java UI application, whether it is stand-alone or embedded in a browser such as an applet, requires some basic understanding of:

• The Java UI containment hierarchy that provides a layer of containers nested within containers, and components within containers

• The types of Java containers and their relationship in the containment hierarchy• The concept of layout managers and their types• Components that can be added into containers

Most graphical applications have a main display area, usually a main window, or the applet display area in a Web browser. In Java, the main window, or applet display area, is called a top-level container. A top-level container is considered the root of the containment hierarchy for that window or area.Note: An application can comprise many top-level windows.A main window can be divided into regions or sections, which are represented by intermediate containers, and ultimately into components that contain the user data or accept user input. These components will be positioned within the top-level or intermediate containers. Together, the top-level and intermediate containers with their components form a containment hierarchy.Each container makes use of a layout manager to control the size and placement of components within a container.

Page 432: Java Programming

Oracle10g: Java Programming 14-10

14-10 Copyright © 2004, Oracle. All rights reserved.

The Containment Hierarchy

• Top-level containers– Frame– Dialog– Applet

• Intermediate containers– Panel– Scroll Pane

• Atomic components– Label– Text items– Buttons

Frame

PanelAtomic

components

Swing Containment HierarchyThe slide lists the three levels of containers for Swing components that are commonly used in applications: top-level containers, intermediate-level containers, and atomic components.Top-level containers provide a place for other Swing components to display or paint themselves, such as a main application window. Top-level containers cannot be placed within another top-level container, and usually contain an intermediate container called a content pane. Commonly used top-level containers are JFrame, JDialog, and JApplet.Intermediate containers simplify the way you organize visual items within a top-level container, and can contain other intermediate containers, and lower-level atomic components. For example, a panel (sometimes called a pane) can be nested within another panel. Common intermediate containers are: JPanel, JScrollPane, JSplitPane, and JToolBar.

Page 433: Java Programming

Oracle10g: Java Programming 14-11

Swing Containment Hierarchy (continued)Atomic components are self-sufficient entities (or widgets) that are used to present information to, or receive data from, the user. Common atomic components are JButton, JLabel, and JTextField (as shown on the slide). Many atomic components exist for text, combination boxes, check boxes, tables, and lists, to name a few.Note: The slide shows the following containment hierarchy:

Frame (top-level container contains a …)Panel (intermediate container, which contains …)

a Labela TextFielda Button

Page 434: Java Programming

Oracle10g: Java Programming 14-12

14-12 Copyright © 2004, Oracle. All rights reserved.

Top-Level Containers

• Swing provides JFrame, JDialog, or JApplet,with changeable properties such as:– A content pane for holding intermediate containers

or components, by using the getContentPane() or setContentPane() methods

– A border, by using a setBorder() method– A title, by using a setTitle() method– Window decorations such as buttons for closing

and minimizing (excludes applets)• AWT provides Frame, Dialog, or Applet

– These do not provide properties such as a content pane or borders.

Top-Level ContainersEach Swing application has at least one top-level container or frame. The top-level container can be an instance of JFrame, JDialog, or JApplet. It is easy to customize the top-level content pane to add a border or set the layout manager. However, using the top-level content pane methods is tricky. The methods of the top-level containers return a Container object, not a JComponent object. This means that you must typecast the return value of the methods in order to use them.An easier way to achieve the same results is to create your own content pane, typically by using a JPanel object. You then call the JFrame setContentPane() method to set the top-level content pane to be your customized JPanel. You now have complete control of the content pane without the restrictions of the top-level or root container.

Page 435: Java Programming

Oracle10g: Java Programming 14-13

Top-Level Containers (continued)The following example creates a top-level container by using a JFrame object, and an intermediate container as a JPanel. After customizing the panel by changing its layout manager and applying a border, the top-level container’s content pane is modified to use the panel by calling the setContentPane() method:

JFrame topLevelContainer = new JFrame();JPanel myContentPane = new JPanel();myContentPane.setLayout(new BorderLayout());myContentPane.setBorder(new LineBorder(Color.lightGray,0));topLevelContainer.setContentPane(myContentPane); // ortopLevelContainer.getContentPane().add(myContentPane);

Page 436: Java Programming

Oracle10g: Java Programming 14-14

14-14 Copyright © 2004, Oracle. All rights reserved.

Intermediate Containers

• Designed to contain components (or containers): Can be nested within other containers

• Types of intermediate containers:– Panels for grouping containers or components– Scroll Panes to add scroll bars around components

that can grow, such as a list or a text area– Split Panes to display two components in a fixed

area, which is adjustable by the user– Tabbed Panes for containing multiple components,

showing only one at a time, based on user selection– Tool Bars for grouping components, such as

buttons– Internal Frames for nested windows

Intermediate ContainersThe next level of containers in Swing is designed for the sole purpose of containing other components. These containers may hold any other Swing component including other containers. By nesting intermediate containers within other containers, you can control the layout of your application. This technique is described later in this lesson.The intermediate containers are the following:

• Panels: These are the most frequently used intermediate containers. They are implemented with the JPanel class. They are generally used to group components for logical presentation to the user. A JPanel can use any layout manager; by default it uses the FlowLayout, and you can set its border to any border.

• Scroll pane: These provide scroll bars around any large component or one that may grow. They are implemented with JScrollPane.

• Split pane: This container is used to present two components in a fixed amount of space while letting the user adjust the space that is devoted to each item. Split Pane is implemented with JSplitPane.

• Tabbed pane: This container possesses multiple components but the user can see only one at a time. The user can switch between the components by clicking on the visible tabs. Tabs are implemented with JTabbedPane.

• Toolbar: In addition to holding multiple components, instances of JToolBar can be repositioned by the user.

• Internal frame: Top-level containers can support internal windows or frames, which are implemented by JInternalFrame and best used with a JDesktopPane.

Page 437: Java Programming

Oracle10g: Java Programming 14-15

14-15 Copyright © 2004, Oracle. All rights reserved.

Atomic Components

• Buttons• Check boxes• Combo boxes• Text• Lists• Labels

Atomic ComponentsAtomic components exist solely to present or accept information. They do not serve as containers for other components. Atomic components inherit from JComponent and thus support standard component features such as borders and tool tips.

Page 438: Java Programming

Oracle10g: Java Programming 14-16

14-16 Copyright © 2004, Oracle. All rights reserved.

Layout Management Overview

Layout Management OverviewYou can use layout managers to control the process of placing components onto a container at run time. Each container has a layout manager by default. The layout manager ultimately controls the layout and position of components within the container. However, each component can provide hints about itself to assist the layout manager, such as its preferred size and position.Java provides many layout managers. The following five are commonly used:• java.awt.BorderLayout, which is the default for JFrame containers, arranges

the container into five areas that are called North, South, East, West, and Center.• java.awt.FlowLayout, which is the default for Jpanel organi es

items from left to right and then fromtop to bottom The rows can be centered (default), right justified, or left justified.

• java.awt.GridLayout arranges items in a grid in rows and columns with cells of the same size.

• java.awt.GridBagLayout arranges items in a grid of rows and columns with different cell sizes. This is the most flexible and complex of all the layout managers, and it allows components to span multiple rows and column cells.

• javax.swing.BoxLayout arranges items in a stack horizontally or vertically.

Page 439: Java Programming

Oracle10g: Java Programming 14-17

Layout Management Overview (continued)You can set a container layout property to null forcing the container not to use any layout manager with the rules described. In this case, absolute positioning, specific position, and size in pixels control the UI component. Absolute positioning is inflexible to changes in the shape of the top-level container at run time. However, it can be useful in design stages to provide precise control over the placement and size of each component.

Page 440: Java Programming

Oracle10g: Java Programming 14-18

14-18 Copyright © 2004, Oracle. All rights reserved.

Border Layout

• Has five areas: North, South, West, East, and Center

• Has center area that expands to fill the available space

• Displays only one component in each area• Makes each area useful for holding intermediate

panels

Border LayoutBorder layout provides five areas for components: north, south, east, west, and center. If the user enlarges the window, then the center area expands to use as much of the space as possible. The other areas expand only as much as necessary to fill the available space. For example, if the user makes the frame wider, then the center will expand horizontally, but the east and west areas will not; however, the south area will expand to fill the new window size.Each area will display only one component. To overcome this restriction and make Border a useful layout manager, add containers to the areas instead of atomic components. Most panels that use Border use only one or two of the areas, such as center and south. South may be used for a toolbar or navigation, whereas center may contain a panel that will hold all the atomic data components. This technique is useful in creating a resizable frame.

Page 441: Java Programming

Oracle10g: Java Programming 14-19

14-19 Copyright © 2004, Oracle. All rights reserved.

GridBag Layout

• Is based on a grid• Allows components to span multiple rows and

columns• Allows rows and columns to differ in size• Uses the component’s preferred size to control

cell size

GridBag LayoutGridBag layout is the most flexible and the most complex of the layout managers. The flexibility comes from its ability to allow components to span multiple rows and columns. In addition to spanning multiple columns and rows, the components can provide hints or suggestions about how the component would like to appear. For instance, a component can specify how much space to automatically set around the component, both inside and outside of the component’s cell. You can also specify minimum, maximum, and preferred size for each component.Components can span multiple cells in both directions, row and column. The row and column sizes are determined by the size of the components that occupy the row or column.

Page 442: Java Programming

Oracle10g: Java Programming 14-20

14-20 Copyright © 2004, Oracle. All rights reserved.

GridBag Constraints

Cell position

Cell span

Expansionweighting

Fill rules

Anchoring

Componentpadding

External insets

GridBag ConstraintsEach component in a GridBagLayout container has properties that you can set to control the layout behavior for the component. You edit the constraints by selecting the component and clicking constraints in the Properties Inspector window. Alternatively, you can right-click the component and select constraints from the context menu.Layout Constraints

• Cell position: The X and Y properties specify the grid cell for the upper left corner of the component. The values are integers and represent the cell number in a row and column.

• Cell Span: These properties specify how many columns (Width) and rows (Height) the component occupies.

• External Insets: These values specify the amount of space between the component and the edge of its display area. You can specify a value for the top, bottom, left, and right.

• Component padding: These values specify the amount of space around a component within a cell. The width of the component is calculated as the minimum width plus the width property. The height is calculated as the minimum height plus the height property.

Page 443: Java Programming

Oracle10g: Java Programming 14-21

GridBag Constraints (continued)Layout Constraints (continued)

• Expansion weighting: This specifies how extra space is distributed vertically (X) and horizontally (Y). The range of values is 0 through 1.0. Weight determines what share of the extra space is allocated to each component.

• Fill rules: These values specify what to do if the display area is larger than the component.

• Anchoring: This indicates where to anchor the component if the component is smaller than the display area.

Page 444: Java Programming

Oracle10g: Java Programming 14-22

14-22 Copyright © 2004, Oracle. All rights reserved.

Using Layout Managers

• Layout managers are designed to manage multiple components simultaneously.

• Using a layout manager with containers requires:– Creating a container and a layout manager object– Setting the layout property of the container– Adding items (components or other containers) into

the regions that are defined by the layout manager• Different layout managers require different

arguments to control component placement.

Using Layout ManagersThese layout managers are designed to manage multiple components at once. The basic steps to use a layout manager are shown on the slide. The examples on the slide show creating a frame by using the javax.swing.JFrame class, to which you apply a java.awt.BorderLayout manager.First you create the layout manager object, then call the frames setLayout() method, and start adding components or other containers into the regions that are provided by the layout manager.Create container and manager

JFrame myFrame = new JFrame();BorderLayout layoutMgr = new BorderLayout();

Set propertiesmyFrame.setLayout(layoutMgr);

Add itemsmyFrame.add(new JButton(), BorderLayout.NORTH);myFrame.add(new JTextField(), BorderLayout.SOUTH); myFrame.add(new JPanel(), BorderLayout.CENTER);

Page 445: Java Programming

Oracle10g: Java Programming 14-23

Using Layout Managers (continued)Adding Components to ContainersWhen adding a component to a container, you must always consider the layout manager that is used by the container. Each type of layout manager may require different arguments to control the placements and/or size of component that is added. For example, when adding a component to a container by using the BorderLayout manager, you are required to specify the border area in which you want the component placed, such as North, South, and so on. FlowLayout does not require a placement parameter, and just appends components in the order that they are added to the container.For most Swing code, such as the examples shown on the slide, you should import classes from the following packages: javax.swing, java.awt, and java.awt.event.Note: If you are using an IDE tool like JDeveloper, then you can set the layout property of a container to null to force the absolute position to be used. This makes it very convenient for you when designing and prototyping a user interface. Later, you can switch the layout property to a suitable Java layout manager class for the application.

Page 446: Java Programming

Oracle10g: Java Programming 14-24

14-24 Copyright © 2004, Oracle. All rights reserved.

Combining Layout Managers

VerticalFlow

Grid

GridBag

null

Border

Combining Layout ManagersDifferent layout managers are good at different tasks. Because you can place multiple panels in a frame and each one may have a different layout manager, you have a lot of control over the ultimate layout.Nesting panels and layout managers is a common practice. In the example on the slide, you use the Border, null, VerticalFlow, GridBag, and Grid layout managers. The top-level frame uses Border, which allows you to specify what nested panels go in the north, south, east, and west areas. The top panel uses null, which allows you to place the components where you want them to be displayed.The RentalID panel uses VerticalFlow, which displays the items that are stacked vertically. You use GridBag in the Rental panel (east) so that you can align components of differing sizes. Lastly, you use Grid in the bottom panel, which contains only one component.Using a combination of these layout managers offers very fine control over the layout of your application. You can create a form that is resizable without losing its general look and feel.

Instructor NoteDue to differences in the way various platforms calculate x, y coordinates, the null layout works well in Windows NT, but does not translate well to other platforms. To ensure that your layout is neatly laid out on other displays, do not leave any containers in null layout in your final design.

Page 447: Java Programming

Oracle10g: Java Programming 14-25

14-25 Copyright © 2004, Oracle. All rights reserved.

Using Frames or Dialogs

A Java frame is equivalent to an application window.• Use the JFrame for a main window

– It has properties for icons, title, window decorations for minimize, maximize, and close buttons.

– It uses BorderLayout by default.– It provides a default content pane that occupies the

center region of the layout.– You can set the frame size with the setSize()

method, and make it visible by using the setVisible() method.

• Use JDialog for a modal window– You must dismiss a modal window before the

application that invokes it can become active.

Using Java Frame ClassesThe Java frame is analogous to a top-level application window. These windows contain all the frills and dressings that are provided by the operating system to manage the window, such as a bar containing title string, an icon, and the minimize, maximize, and close buttons. These windows are also resizable unless you programmatically disable this feature.When you create a Java JFrame object, you automatically get a content pane that provides the container for the window objects or components. As stated in a previous slide, you typically replace the content pane with an intermediate component like a JPanel, to simplify management of the visual contents of the container.The JFrame uses a BorderLayout manager by default, where default content pane is located in the center region. You can alter the frame to have a menu and/or a toolbar, to be commonly placed in the north region, and a status bar that would typically be placed in the south.JDialog classes can be modal, or nonmodal. They tend to be modal in nature. It is more common to create dialogs by using the JOptionPane class methods, such as the showMessageDialog() among others therwise youcan use the JDialog class to create custom

dialog boxesNote: On the next page, there is an example of a simple frame application, with a default content pane, but no intermediate containers or components.

Page 448: Java Programming

Oracle10g: Java Programming 14-26

Creating a Simple Frame ApplicationThis example shows how to build a Java GUI application by using the JFrame class. The code example illustrates the points that are discussed on the slide of the previous page.import java.awt.Color;import javax.swing.JFrame;public class MyFrame extends JFrame{

public MyFrame(){

setDefaultCloseOperation(EXIT_ON_CLOSE);getContentPane().setBackground(Color.blue);setTitle("Default Frame Title");setLocation(50, 50);setSize(600, 400);

}

public static void main(String[] args){

JFrame f = new MyFrame();f.setResizable(true);f.setVisible(true);

}}

Note• By default the JFrame default operation on a close event is to hide the window. The

call to setDefaultCloseOperation(EXIT_ON_CLOSE) changes the default operation that is performed by the JVM when the window is closed. The EXIT_ON_CLOSE constant is defined in javax.swing.WindowConstants, which is an interface implemented by JFrame.

• The getContentPane() method is used to access the frame’s default container and change the background color to blue.

• The setLocation() determines the top left x and y coordinates (in pixels) of the window relative to the top left corner of the screen.

• The setSize() method sets the width and height of the window (in pixels).• The setLocation() and setSize() can be done in one step by calling

setBounds(x, y, width, height)• The example shows how you can set properties of the frame in the constructor, or by

using a reference to the frame (as shown in the main() method).

Page 449: Java Programming

Oracle10g: Java Programming 14-27

14-27 Copyright © 2004, Oracle. All rights reserved.

Using JPanel Containers

JPanel is a general purpose container.• Can use any layout manager

(uses Flowlayout by default)• Can use any border• Can have added components

or other panels/containers by using the add() method

JPanel myPanel = new JPanel(new BorderLayout());

JTextArea jTextArea1 = new JTextArea();

myPanel.setBorder(BorderFactory.createRaisedBevelBorder());

myPanel.add(jTextArea1, BorderLayout.SOUTH);

Using JPanel ContainersJPanel is a general purpose container that is designed to hold other components. You can use JPanel containers to group components within an area of an application. You may add a border to the panel to help visually separate the components from other components in the application.Setting the Layout ManagerThe default layout manager for JPanel is FlowLayout, which places all the components within the container in a row. You can make the panel use another layout manager by calling the setLayout() method or by specifying the layout manager when you create the panel. For example:

JPanel myPanel = new JPanel();myPanel.setLayout(new BorderLayout()); orJPanel myPanel = new JPanel(new BorderLayout());

Page 450: Java Programming

Oracle10g: Java Programming 14-28

Using JPanel Containers (continued)Adding ComponentsYou can add components to the panel by using the add() method. The arguments that are provided to the add() method depend on which layout manager is used by the panel. Forexample, FlowLayout, GridLayout, and GridBagLayout typically accept one argument. If the layout manager is BorderLayout, then additional arguments are used to specify the position of the contained components.For example:myPanel.add(button); // if FlowLayoutmyPanel.add(button, BorderLayout.NORTH); // if BorderLayoutmyFrame.getContentPane().add(myPanel); // add to a frame

Page 451: Java Programming

Oracle10g: Java Programming 14-29

14-29 Copyright © 2004, Oracle. All rights reserved.

Adding Borders to Components

• Borders are Swing objects.– Defined in javax.swing.borders

• Use setBorder() to assign a border to a component.

• Create borders with the class called javax.swing.BorderFactory.

• Create borders separately to use with many components.

jPanel1.setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED,Color.lightGray,Color.darkGray));

Border etchedBorder = BorderFactory.createEtchedBorder();//pre-create border

jPanel2.setBorder(etchedBorder); // use border`

Adding Borders to ComponentsAny JComponent object or subclass may have one or more borders. To place a border around a component, use its setBorder() method.Because borders are objects, they must be created. You create a border by using the BorderFactory class. You can include the border object creation in the call to setBorder(), or you can create the border object with a separate line of code. If you use the same border style for multiple components, then it would be easier and more consistent to create one border object for each style needed. The following code illustrates the technique for creating reusable Border objects:import javax.swing.BorderFactory;import javax.swing.border.*;

Border etchedBorder = BorderFactory.createEtchedBorder();Border raisedBorder = BorderFactory.createRaisedBevelBorder();jPanel1.setBorder(raisedBorder);jPanel2.setBorder(etchedBorder);

Page 452: Java Programming

Oracle10g: Java Programming 14-30

14-30 Copyright © 2004, Oracle. All rights reserved.

Using Internal Frames

An internal frame is the equivalent of a document window that is contained within an application window for multiple-document interface (MDI) window applications.• Use JInternalFrame for an internal window:

– Similar to JFrame, it can contain intermediate containers and components and use a layout manager.

– By default it is not “closable,” “iconifiable,”“maximizable,” or visible.

• Use a JDesktopPane as the content pane in which the internal frames are added:– Controls the size and placement of internal frames– Uses a null layout manager by default

Using Java Internal FramesThe Swing API also provides an internal frame, which is implemented by the JInternalFrame class. An internal frame creates a window within another window that you can use to build an application that conforms to the popular multiple document interface (MDI) model of the Windows platform.When using a JInternalFrame, the JDesktopPane class is provided as a container to manage the size and placement of the internal frames within the containing window. Therefore, you would normally create a JDesktopPane object to replace the existing frame’s default content pane. The internal frames are then added to the desktop pane.Like a JFrame, the JInternalFrame has a window title bar, with a title, icon, and window decorations such as maximize, “iconify,” and close buttons, which by default are disabled. The internal frames can be dragged over each other, and an internal frame provides methods to control whether it is on top and selected, and so on. For example:

setResizable(boolean), setIconifiable(boolean)setMaximizable(boolean), setVisible(boolean)toFront(), toBack()

The desktop pane provides methods to obtain an array of internal frame objects that have been added to its container; for example:getAllFrames() returns an array of JInternalFrame objects.getSelecedFrame() returns the currently selected JInternalFrame.

Note: Most getXXX() methods have a corresponding setXXX() method.

Page 453: Java Programming

Oracle10g: Java Programming 14-31

Creating a Multiple Document Interface (MDI) ApplicationThis code example uses a JFrame as the main MDI application window, whose default content pane is replaced with a JDesktopPane object. Two JInternalFrame objects are then added to the main application window desktop pane.import java.awt.Color;import javax.swing.JFrame;import javax.swing.JInternalFrame;import javax.swing.JDesktopPane;

public class MdiFrame extends JFrame {public MdiFrame() {

setDefaultCloseOperation(EXIT_ON_CLOSE);setTitle("MDI Frame Example");

setBounds(50, 50, 600, 400);}public static void main(String[] args) {

JFrame f = new MdiFrame();JDesktopPane desktop = new JDesktopPane();JInternalFrame iFrame1 =

new MyInternalFrame("Internal 1", Color.red);JInternalFrame iFrame2 =

new MyInternalFrame("Internal 2", Color.green);f.setResizable(true);f.setVisible(true);f.setContentPane(desktop);iFrame1.setBounds(10, 20, 350, 200);iFrame2.setBounds(60, 70, 350, 200);desktop.add(iFrame1);desktop.add(iFrame2);iFrame2.toFront(); //only after frames are added

}} class MyInternalFrame extends JInternalFrame {public MyInternalFrame(String name, Color c) {

super(name); setBackground(c);setResizable(true); setMaximizable(true);setIconifiable(true); setClosable(true);setVisible(true);

}}

NoteThe text in boldface highlights some of the important parts of the code, such as:

• Creation of the desktop pane (line 14), and internal frame objects (from line 16 through 18)

• Replacing MdiFrame default content pane with the desktop pane (line 21)• Adding the internal frames into the desktop frame (lines 24 and 25)• Making the second internal frame the front/top internal frame (line 26)• Making the internal frames visible (line 34)

Page 454: Java Programming

Oracle10g: Java Programming 14-32

14-32 Copyright © 2004, Oracle. All rights reserved.

Swing Text Controls

Swing Text ControlsSwing provides five text components (along with supporting classes and interfaces) that meet even the most complex text requirements. All of Swing’s text components inherit from JTextComponent.Text FieldsAlso known as text controls, text fields can display and edit only one line of text and are action-based, like buttons. Use them to get a small amount of textual information from the user and take some action after all the text has been entered. The text fields are JTextField and JPasswordField.Plain Text AreasJTextArea can display and edit multiple lines of text. This field is useful when you want the user to enter text of any length or to display large amounts of unformatted text. JTextArea can display text in any font; however, all of the text displayed must be in the same font.Styled Text AreasStyled text components can display and edit text using more than one font. These components can display text that is stored in different formats such as HTML and Rich Text Format (RTF). They also support images and some support buttons and other controls. The styled text components are JEditorPane and JTextPane.

Page 455: Java Programming

Oracle10g: Java Programming 14-33

14-33 Copyright © 2004, Oracle. All rights reserved.

Adding Componentswith Oracle JDeveloper 10g

• Use the wizard to create a JFrame.• Select a layout manager.• Add components from the Component Palette.• Fine-tune component properties.

Adding Components with JDeveloperAdding components to an application is a straightforward process with Oracle JDeveloper. You can use the Frame Wizard to create an empty frame and then add the components that you want. The components can be Swing containers or Swing atomic components, such as text fields, buttons, check boxes, and so on. After you add the components, you can fine-tune the components by using the Properties Inspector or by adding or changing the code in the Code Editor window.

Page 456: Java Programming

Oracle10g: Java Programming 14-34

14-34 Copyright © 2004, Oracle. All rights reserved.

Creating a Frame

Frame

Creating a FrameTo create a new JFrame, select File > New from the JDeveloper menu. Expand the Client Tier, then select the SWING/AWT node. Look for the Frame item in the Items list. In the Frame Builder Wizard, change the name of the class and the frame title to something meaningful. Select javax.swing.JFrame as the base class. You can ask the wizard to create a menu bar, status bar, toolbar, and about box. These are all optional attributes.You can use the wizard to specify the preferred superclass for the new frame. JDeveloper will generate a class with the required import statements and the code that is necessary to create a usable frame. Now you can use the JDeveloper UI Editor to construct the application UI structure visually.

Page 457: Java Programming

Oracle10g: Java Programming 14-35

14-35 Copyright © 2004, Oracle. All rights reserved.

Adding Components

Use the Component Palette to add Swing items to the Frame

Adding ComponentsThe JFrame that is created by the Frame Builder Wizard includes the frame and an intermediate JPanel container. The wizard does not set the layout manager for the generated JPanel. It uses the default layout manager for its type of container (FlowLayout).Because it is a default layout manager, JDeveloper cannot provide the ability to alter the properties of the layout manager. It is best to change the layout manager so that you can manipulate the layout properties.After setting the layout manager, you can then add components by selecting them from the Swing component toolbar and dragging an area onto the JPanel in the Design window. Alternatively, you can click the component and then click JPanel in the Component pane of the structure window. If you choose the latter, then JDeveloper uses default sizes for components. In either case, the layout manager affects the final location of the component.

Page 458: Java Programming

Oracle10g: Java Programming 14-36

Adding Components (continued)To invoke the UI Editor, in the navigator select a class, right-click, and choose UI Editor.In general, add components to the structure window instead of directly to the panel. This approach is best if you want to avoid adding a component to the wrong panel by accident. For instance, adding components to a JTabbedPane inside a panel can be done in an easier manner by using the structure pane.When visually adding a component into a frame/panel with JDeveloper, it generates code to:

• Declare and instantiate the selected component object• Set minimal properties for the default state• Add the component into the chosen container

Page 459: Java Programming

Oracle10g: Java Programming 14-37

14-37 Copyright © 2004, Oracle. All rights reserved.

Setting Pluggable Look and Feel

Swing applications provide support for a different look and feel to adapt to the visual environment of the operating system. The look and feel:• Is application-specific:

– Can be initialized when the application starts– Can change dynamically

• Affects lightweight Swing components• Supports Win, Mac, Java (Metal) and Motif • Uses javax.swing.UIManager class

– Provides the setLookAndFeel() method, which accepts a look and feel class name string.

Pluggable Look and Feel (plaf)Java provides a set of classes in the javax.swing.plaf package and subpackages that assist to render components in a platform-specific manner. The default Java look and feel is known by its code name “Metal,” which is the name of the project that was assigned to a team at Sun Microsystems, Inc., to create a unique and distinctive look and feel for Swing 1.0 (JFC 1.1).

Setting UI Look and FeelUse the javax.swing.UIManager class to initialize, or dynamically change the look and feel of your application. For example, in the main() method of your frame application, you can add the following code:

try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

} catch (Exception e) { }

Page 460: Java Programming

Oracle10g: Java Programming 14-38

Setting UI Look and Feel (continued)

he value that is returned bygetSystemLookAndFeelClassName() is a string

representing a fully qualified classname that implements the look and feelof the current platform he class namestring is provided as the parameter toUIManager.setLookAndFeel(). Some possible values for the class names of different platforms are:

javax.swing.plaf.metal.MetalLookAndFeelcom.sun.java.swing.plaf.windows.WindowsLookAndFeelcom.sun.java.swing.plaf.motif.MotifLookAndFeel

Note: If you want to change the look and feel dynamically, then you can call the SwingUtilities.updateComponentTreeUI(getContent Pane())method.This method will make the existing components reflect the new look and feel.

Page 461: Java Programming

Oracle10g: Java Programming 14-39

14-39 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:• Frames are top-level containers.• Panels are intermediate containers that can be

nested.• Each container can have its own layout manager.• Layout managers control component placement.• You can combine layout managers within an

application.• You can control the application’s look and feel.

Page 462: Java Programming

Oracle10g: Java Programming 14-40

14-40 Copyright © 2004, Oracle. All rights reserved.

Practice 14: Overview

This practice covers:• Creating a class based on JFrame for the main

window of the OrderEntry application.– Add a default menu and status bar.– Add a JDesktopPane and set it as the content pane.

• Creating a class based on JInternalFrame to manage order creation and data entry.– Create the container layout hierarchical structure

for the order-entry frame components.– Add some of the components to this frame.

• Setting layout managers for each container

Practice 14: OverviewNote: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you would like to move on to this practice, then change to the les13 directory, load up the OrderEntryWorkspaceLes13 workspace, and continue with this practice.Viewing the model: To view the course application model up to this practice, load the OrderEntryWorkspaceLes13 workspace. In the Applications – Navigator node, expand the OrderEntryWorkspaceLes13 – OrderEntryProjectLes13 -Application Sources – oe, and double-click the UML Class Diagram1 entry. This diagram displays all the classes created to this point in the course.

Page 463: Java Programming

Oracle10g: Java Programming 14-41

Practice 14: User Interface Design: Swing Basics Planning the Application Layout

GoalThe goal of this practice is to use JDeveloper to create the main application frame as an MDI window, and the internal order frames that will be contained within the main window. These frames will serve as a way to explore Swing classes and ways of building GUI applications.Note: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you would like to move on to this practice, then change to the les13 directory, load up the OrderEntryWorkspaceLes13 workspace, and continue with this practice.Your AssignmentCreate the main window as an extension of the JFrame class. This class will contain a JDesktopPane object to manage the internal frame layout. You will also create a class based on the JInternalFrame class in which the customer and order details will be entered via atomic Swing components. The components layout will be managed through the use of panels and associated layout managers. You use the JDeveloper Frame Wizard to create a basic menu for the application, and a status bar in the main application window.Create the Main Application Window

1. In OrderEntryProject, create a new subclass of the JFrame class.a. Right-click the project name in the navigator, and select New… from the context

menu. Select the Frame item from Client tier > Swing/AWT category, and click the OK button.

b. In the Create Frame dialog box, enter the class name OrderEntryMDIFrame, and extend javax.swing.JFrame. In the Optional Attributes section, set the Title field to: Order Entry Application, and select only the Menu Bar and Status Bar check boxes. Then click the OK button.

c. Examine the code for the new class that is generated by JDeveloper by selecting the Source tab. You will notice that JDeveloper creates a jbInit() method that is called from the default no-arg constructor. The jbInit() method should contain all code to initialize the user interface structure. You should modify the code if required, to match with the one displayed.

d. In the Editor window, select the Design tab, and examine the visual container hierarchy and presentation of the frame. The container hierarchy is visible in the JDeveloper Structure pane (located under the Navigator pane).

e. Return to the Code Editor for the class by selecting the Source tab and make the following changes:Replace the JPanel panelCenter variable declaration, with:

JDesktopPane desktopPane = new JDesktopPane();Note: Remember to import javax.swing.JDesktopPane.In the jbInit() method, replace panelCenter references with desktopPane.

f. Compile and save the OrderEntryMDIFrame class.g. Modify OrderEntry.java by renaming the main() method to

test1(…)reate a new public static void main(String[] args) method which creates an instance of the OrderEntryMDIFrame and makes it visible.

Page 464: Java Programming

Oracle10g: Java Programming 14-42

Practice 14: User Interface Design: Swing Basics Planning the Application Layout (continued)

h. Compile, save, and run the OrderEntry application.Create the JInternalFrame Class for Order DataThis frame will contain the bulk of the UI code for data entry and user interaction for an order, and assigning a customer and adding items to the order.

2. Right-click the OrderEntryProject and select New… from the context menu.a. Navigate to the Client Tier > Swing/AWT node and select the Frame item. In the

New FrameWizard, enter the class name OrderEntryFrame, and extend the javax.swing.JInternalFrame. Set the title to the text Order.Then click the OK button.Note: The JInternalFrame class can be selected by clicking the Browse button.

b. The OrderEntryFrame that is generated does not have the desired layout manager or content pane. To set the layout manager, and add a panel to the content pane, open OrderEntryFrame with the UI Editor.Note: When the UI Editor is activated (UI Editor can be invoked by clicking the Design tab), the Property Inspector window is also displayed, showing the properties of the object that is selected in the UI Editor.

c. Select the internal frame object by clicking the frame title bar in the UI Editor or the node labeled this in the structure window. (You may have to expand the UI node to view objects in the containment hierarchy.) In the Inspector pane, locate the layout property and select BorderLayout from the pop-up list options.

d. Which lines of code has JDeveloper added or changed in your class? When creating a Swing UI by using the JDeveloper UI Editor, it is wise to view changes that are made to the source code as an aid to learning what you would need to write yourself if you are building the UI manually. Remove the private declaration from the BorderLayout.

e. JDeveloper provides a Component Palette in the toolbar (ask the instructor, if needed). In the palette, choose Swing Containers from the pop-up list.Click the JPanel icon, and then click the center of the frame in the UI Editor (or click the node labeled this in the UI Structure pane) to add a new panel to the center region of the border layout.If the JPanel icon is not visible, they have to expand the Component Palette window by increasing the height.Note: Confirm that the panel is in the center by selecting the JPanel object added and checking that its constraints property (in the Inspector) has the value Center. If not, then set it to Center.

3. The panel was added to the frame’s content pane, and will be used to lay out the rest of the application UI objects. The panel will be divided into two areas: a top (for order and customer data), and a bottom (for order item data). Divide the panel into two by using a GridLayout for the layout, with one column and two rows:

a. Select jPanel1, and set its layout manager property to GridLayout.b. Expand jPanel1 in the UI Structure pane, select the gridLayout1 object,

set the columns property to 1 and press the Enter key, set the rows property to 2, and then press Enter.

Page 465: Java Programming

Oracle10g: Java Programming 14-43

Practice 14: User Interface Design: Swing Basics Planning the Application Layout (continued)

Using the following picture as a visual guide to the desired results for the layout ofthese containers, add another panel to the top, and a scroll pane to the bottomof the content panel.

c. Add a second panel to the top half (or first row) of the first panel, by clicking the JPanel icon in the Swing Components palette, and then clicking the jPanel1 object in the UI Editor, or in the Structure pane.Note: Confirm that the new panel is called jPanel2, and more importantly, that it is nested inside jPanel1 in the hierarchy.

d. Add a raised-bevel border to the new panel, called jPanel2, by selecting its border property in the Inspector, and select Swing Border… from the pop-up list. In the Border dialog box, choose BevelBorder and select the RAISEDoption button, then click the OK button.Note: jPanel2 should visually occupy the top half of the jPanel1.

e. Add a scroll pane object to the bottom half (second row) of the jPanel1, by clicking the JScrollPane icon in the Swing Components palette, and click the bottom area of the jPanel1. (Alternatively, click the jPanel1 object in the Structure pane to add the JScrollPane.)

f. Use the Structure pane to check whether you have the following containment hierarchy:

g. Save your OrderEntryFrame class. Then compile the class.

Page 466: Java Programming

Oracle10g: Java Programming 14-44

Practice 14: User Interface Design: Swing Basics Planning the Application Layout (continued)

Modify OrderEntryMDIFrame Class to Contain an Internal OrderEntryFrame4. To view the visual results of your internal frame at run time modify the constructor in

OrderEntryMDIFrame to create an instance of OrderEntryFrame, and make it visible.

a. Edit OrderEntryMDIFrame.java, and at the end of the constructor add the following lines of code:OrderEntryFrame iFrame = new OrderEntryFrame();iFrame.setVisible(true);desktopPane.add(iFrame);

Note: The bounds (size and location) of the internal frame must nowbe set, otherwise it will not become visible. In addition, you must also alter thedimensions of OrderEntryMDIFrame to be larger than the initial size of theinternal frame OrderEntryFrame.

b. In the jbInit() method of the OrderEntryMDIFrame class, locate the following statement:this.setSize(new Dimension(400,300));

Then modify the dimension arguments to be 700,500.c. In the OrderEntryFrame, add the following line into the jbInit()

method:this.setBounds(0, 0, 400, 300);

d. Compile and save OrderEntryMDIFrame and OrderEntryFrame.e. Run the OrderEntry class to view the results.

5. You will notice that the internal frame cannot be maximized, “iconified” (minimized), or closed. Make changes to OrderEntryFrame to enable these features.

a. In the jbInit() method, add the following lines of code to enable the internal frame to maximized, “iconified,” and closed.this.setMaximizable(true);this.setIconifiable(true);this.setClosable(true);

b. Compile and save the changes to OrderEntryFrame.java.c. Run the OrderEntry application, and observe the changes.

Add UI Components to OrderEntryFrame6. Before adding UI components to jPanel2 in OrderEntryFrame, set its layout to

null.Note: You could also use the JDeveloper XYLayout.In either case, JDeveloper will use absolute positioning and sizing for components that are added to the panel. It is easier to use absolute positioning when building the initial UI layout. You will change the layout again in a subsequent lesson.Use the following image as a guide to the desired results:

Page 467: Java Programming

Oracle10g: Java Programming 14-45

Practice 14: User Interface Design: Swing Basics Planning the Application Layout (continued)

a. In the Design mode, select the Swing option in the Component Palette pop-up list. Then add a Jlabel to jPanel2 and set its text property to Order Id. Resize the label to see the label value, if needed. What lines of code have been added to your class?Hint: You should find at least five lines of code (some of them in the jbInit() method). Try to identify the three that make the object visible in the panel.Note: The setBounds value can be modified if required in the source to make the label clearly visible.

b. From Swing icons, select and add a JTextField component into jPanel2, to the right of the label, then delete the default value in the text property of the text field (remember to press the Enter key after deleting the text value).Note: setBounds values can be changed if required.

c. Compile and save OrderEntryFrame, and run OrderEntry to view the results.

Page 468: Java Programming
Page 469: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Adding User Interface Componentsand Event Handling

Schedule: Timing Topic50 minutes Lecture70 minutes Practice (total for both mid lesson and end of lesson)

120 minutes Total

Page 470: Java Programming

Oracle10g: Java Programming 15-2

15-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Add Swing components to an application• Get and modify the contents of the components• Provide event handlers for common types of

events• Create a menu bar

Lesson AimThis lesson shows how to provide a Java applet (or application) with a graphical user interface based on components, such as buttons and text fields. You learn how to use standard Java Swing components as well as the more sophisticated controls provided by JDeveloper. You also learn how to provide event handler methods, to deal with events such as button clicks and text changes.

Instructor NoteFurther reading: The Java tutorial has a very good section on the Swing components: http://java.sun.com/docs/books/tutorial/

Page 471: Java Programming

Oracle10g: Java Programming 15-3

15-3 Copyright © 2004, Oracle. All rights reserved.

Swing Components

• Text controls– JTextField– JPasswordField– JTextArea– JEditorPane– JTextPane

• Graphic controls– JTree– JTable– JToggleButton

Swing ComponentsSwing text components display text and can optionally allow the user to edit text. There are five different text components that support the varying complexities and requirements. They are:• JTextField: Can display and edit only one line of text at a time• JPasswordField: A subclass of JTextField (It works the same as

JTextField except that the input is hidden from the user.)• JTextArea: Can display and edit multiple lines of text (This component is used to

allow the user to enter text of any length. It can display text in any font.)• JEditorPane: Allows the use of more sophisticated text styles including multiple

fonts and embedded images (JEditorPane can read and write plain text, HTML, and RTF text.)

• JTextPane: In addition to the facilities that are provided by JEditorPane, it allows embedded components.

Page 472: Java Programming

Oracle10g: Java Programming 15-4

Swing Components (continued)Graphic components• JTree: A control that displays a set of hierarchical data as a tree diagram• JTable: A component that displays data in a two-dimensional table format• JToggleButton: Toggle buttons are similar to JCheckBox. When they are

pushed (set to true), they remain true until they are programmatically set to false.

The Swing Containers ToolbarThe Swing Containers toolbar holds components that are intended to contain other components.

Page 473: Java Programming

Oracle10g: Java Programming 15-5

15-5 Copyright © 2004, Oracle. All rights reserved.

Swing Components in JDeveloper

Use the Swing Component Palette to add items.

Swing Components in JDeveloperThe main window contains the Component Palette, which holds all the graphical and nongraphical controls that are available. The Swing Control Category contains the Swing components. Here is a brief summary:• JButton: A push button• JCheckBox: A check box that can be selected or cleared• JComboBox: A combination of text field and drop-down list• JEditorPane: A styled text area that can display text in different formats including

RTF and HTML• JLabel: A short text string or an image that cannot be selected• JList: A list of items that the user can select from• JPasswordField: A text field that displays a character such as an asterisk (*)

instead of showing what the user enters• JProgressBar: A graphic display showing how much of a task is completed• JRadioButton: One of a group of option buttons• JScrollBar: A horizontal or vertical scroll bar• JSeparator: A component that draws a straight line• JSlider: A component that the user can use to select a value by sliding a knob

Page 474: Java Programming

Oracle10g: Java Programming 15-6

Swing Components in JDeveloper (continued)• JTextArea: A multiline text field• JTextField: A single-line text field• JTextPane: A styled text area that you can use to define your own text formats• JTree: A control that displays a set of hierarchical data as a tree diagram• JTable: A component that displays data in a two-dimensional table format• JToggleButton: Toggle buttons are similar to JCheckBox. When they are pushed

(set to true), they remain true until they are programmatically set to false.

Page 475: Java Programming

Oracle10g: Java Programming 15-7

15-7 Copyright © 2004, Oracle. All rights reserved.

System Navigator

Invoking the UI Editor

Right-click and select Open from the Context menu.

Code Editor

Context menu

UI EditorYou can invoke the Context menu by right-clicking the class in the Application Navigator and selecting Open to view the class. The class will be displayed in the Code Editor. On the bottom of the pane, there will be three tabs: Source, Class, and Design. Clicking the Design tab will display the class using the UI Editor.

Page 476: Java Programming

Oracle10g: Java Programming 15-8

15-8 Copyright © 2004, Oracle. All rights reserved.

1: Open the Component Palette; select the Swing category.

2: Drag the component to the form. The class updates automatically.

How to Add a Component to a Form

Adding Components to the Structure PaneNote that you can add components to the structure window instead of directly to the panel. This approach is best if you want to avoid adding a component to the wrong panel by accident, particularly in cases when the panel regions are not perceptually visible in the UI Editor. Make sure that you drag the component to its container in the structure window. For instance, adding components to a JTabbedPane inside a panel is easily done by using the structure window.

Changes JDeveloper Makes to the Source Code when Adding ComponentsIf you examine the source code changes before, and again after you add a component, then you will notice that JDeveloper makes the following changes to the class that is being edited:

• Adds an import statement for the component’s class (if not already present)• Creates an instance variable by using the component class name as the type, and a

default instance variable name (by using default/package level access)• Adds lines to the jbInit() method in order to set the default properties for the

component, such as the initial text value of a JTextField. In addition, a code line is generated to add the component into its container.

Page 477: Java Programming

Oracle10g: Java Programming 15-9

15-9 Copyright © 2004, Oracle. All rights reserved.

Change property values in the Inspector.

Edit the Properties of a Component

Editing the Properties of a ComponentSelect a Swing component, and in the JDeveloper menu navigate to View > Property Inspector to view the component’s properties.Changes that are made to the properties of a component modify the source code to reflect the changes that are made in the Inspector window.Note: When changing a textual field that requires you to enter the value, press the Enter key to accept the change that is made.

Page 478: Java Programming

Oracle10g: Java Programming 15-10

15-10 Copyright © 2004, Oracle. All rights reserved.

Code Generated by JDeveloper

For example: Adding a JButton to a Jframe:import javax.swing.JButton;

public class JFrame1 extends JFrame {

JButton jButton1 = new JButton();

...

public void jbInit() throws Exception {

...

jbutton1.setText("jButton1");

...

this.getContentPane().add(jButton1,

new XYConstraints(21, 20, 118, 48));

}

Generated CodeWhenever you modify a UI in JDeveloper, it automatically updates the source code for that class in order to achieve the design that you have just specified. In fact, the source code is all that matters; the Designer tool is just an easy way to generate the source code that is required to achieve a certain visual appearance.Instance Variables and Their NamesEach time you add a component to the UI, JDeveloper adds a corresponding instance variable to your class. By default, the instance variable is assigned a default name based on the class name and number, for example, jButton1 (as shown on the slide). To give the variable a more meaningful name, change its name property in the Inspector, to replace all usages of the name in the class. If you change the variable name manually in the source code, then you must remember to replace all occurrences of the variable in the class.The code lines that are generated in the jbInit() method to initialize the component and add it to its container will vary based on the type of layout manager that is used by the container. On the slide, the second parameter to the add() method on the content pane uses the XYConstraints object because the container layout manager is XYLayout.

Page 479: Java Programming

Oracle10g: Java Programming 15-11

Generated Code (continued)Methods That Set PropertiesJDeveloper calls a method to set each property that you edited in the Property Inspector. In the example, you changed the button’s text to Find and changed the font of the button’s text to 16 point. The two methods that are called are setText() and setFont():jButton1.setText("Find");jButton1.setFont(new Font("Dialog", 1, 16));

Component Objects Added to the ContainerThe jbInit() method adds each component object to the container:this.getContentPane().add(jButton1,

new XYConstraints(21, 20, 118, 48));

Parameters for the XYConstraints constructor:new XYConstraints(X, Y, width, height);

where X and Y are the coordinates of the component relative to the upper left-hand corner of its container.

Page 480: Java Programming

Oracle10g: Java Programming 15-12

15-12 Copyright © 2004, Oracle. All rights reserved.

Creating a Menu

• Select “Create Menu Bar” during application creation.

• Add a JMenuBar from the Component Palette.• JDeveloper creates:

– JMenuBar for visual container for menus– JMenu, which represents a menu of items, added to

a menu bar– JMenuItems, which are placed in a JMenu

• Each JMenuItem supports events, interfaces, and handler methods in the same way as with other Swing UI components.

• A JMenuBar can be added to any top-level container, such as Frames, Dialogs, or Applets.

Creating a Menu ManuallyFollow these steps to create a menu bar manually with a single menu and single item:

1. Create a JMenuBar object.2. Create a JMenu object.3. Create a JMenuItem object.4. Add the menu item to the JMenu.5. Add the JMenu to the JMenuBar.

Adding a Menu Bar to a ContainerFinally, associate the JMenuBar with the Frame, Dialog, or Applet by calling its setJMenuBar() method. Write menu event handling code for the JMenuItem by registering the appropriate event listeners, or using the Swing Action objects.

Page 481: Java Programming

Oracle10g: Java Programming 15-13

15-13 Copyright © 2004, Oracle. All rights reserved.

Using JDeveloper Menu Editor

• In the JDeveloper Menu Editor, use the Structure pane:– Expand the Menu node.– Click the menu bar object for a visual

representation.– Right-click menu or menu items to alter

structure from the Context menu options.

Clickmenu barobject in

Structure paneto displaymenu bar

Context menu when

right-clicking a menu item

Using the Menu Editor in JDeveloperIn the UI Editor, the menu bar can be altered by adding, deleting, and moving components.To Add a Menu or Menu ItemYou can right-click a menu component to add another menu to the menu bar, as shown on the slide screenshot.If you right-click a menu item, then you can use the context menu selection to:

• Add another menu item• Add a separator• Add a submenu• Mark a menu item as a check box menu item• Disable the menu item

To Delete Menu ComponentsPress the Delete key after selecting a menu component.To Rearrange the Menu StructureYou can drag the components visually.

Page 482: Java Programming

Oracle10g: Java Programming 15-14

15-14 Copyright © 2004, Oracle. All rights reserved.

Practice 15-1: Overview

This practice covers:• Creating the OrderEntryMDIFrame menu• Adding the menu items and a separator to the

Order menu• Adding components to OrderEntryFrame to form

its visual structure

Practice 15-1: OverviewNote: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les14 directory, load the OrderEntryLes14 workspace, and continue with this practice.

Page 483: Java Programming

Oracle10g: Java Programming 15-15

15-15 Copyright © 2004, Oracle. All rights reserved.

UI for Java Application

Sample Order Entry ApplicationThe slide shows a snapshot of the final visual appearance of the application’s main window OrderEntryMDIFrame, and a sample OrderEntryFrame for an order that is created as an internal frame.Using the ApplicationThe OrderEntryMDIFrame provides the main application menu, from which the user clicks the Order > New menu option to create a new order for a customer.The new order request should create the internal OrderEntryFrame, and a new Orderobject from which the Order Id text field in the frame is set by using the ID of the new order object.The customer details are entered by entering an ID value in the Customer Id field and clicking the Find button. The Find button event validates if the customer exits (by using the DataMan.findCustomerById() method) and if so, assigns the customer to the order and displays the customer details in the fields provided; otherwise an error message is displayed.

Page 484: Java Programming

Oracle10g: Java Programming 15-16

Sample Order Entry Application (continued)Using the Application (continued)Products are added to the order by entering a value in the Product Id field and clicking the Add button. The products that are found by using the DataMan.findProductById()method, are added to the order contained in the order item objects that are added to the JList in the bottom pane of the OrderEntryFrame. Multiple products can be added to the order, but adding a product that already exists in the order increments the item quantity.Note: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you would like to move on to this practice, then change to the les14 directory, load the OrderEntryLes14 workspace, and continue with this practice.Viewing the model: If you load the OrderEntryWorkspaceLes14 workspace, and in the Applications – Navigator node, expand the OrderEntryWorkspaceLes14 –OrderEntryProjectLes14 - Application Sources – oe, and double click the UML Class Diagram1 entry. This diagram displays all the classes created to this point in the course.

Page 485: Java Programming

Oracle10g: Java Programming 15-17

Practice 15-1: Adding User Interface ComponentsGoalIn this practice, you create the menu and visual components for the user to manage order entry details. The application will include a button to find a customer that will be assigned to the order, and buttons to add and remove products as items in the order. You learn how to build a Swing-based UI application by using the JDeveloper UI Editor to construct the user interface. You also learn how to handle events for the Swing components that are added to the application.Note: Whenever you create a UI component, JDeveloper will declare it as private and you can remove that if required.Your AssignmentModify the menu of the OrderEntryMDIFrame, and add several Swing components to the OrderEntryFrame to meet the user requirements by using the following screenshotas a guide:

Create the OrderEntryMDIFrame Menu1. The menu bar structure that is added to the main window should be as follows:

Use the JDeveloper UI Editor to modify the menu to include the Order menu and its menu items, as shown above.Note: File > Exit already exists.

a. Edit the OrderEntryMDIFrame by using the UI Editor, expand the Menu item in the Structure pane, and click the menuBar entry to display the initial menu structure in the UI Editor window.

Page 486: Java Programming

Oracle10g: Java Programming 15-18

Menu item text Menu name property value New newMenuItem Open openMenuItem Save saveMenuItem Close closeMenuItem <separator> See step b. Print printMenuItem

Practice 15-1: Adding User Interface Components (continued)b. Add the Order menu after the File menu. Right-click the outlined box on the right

side of the File menu item, and select the Insert Menu option from the context menu.

c. The new menu should be selected and shown as jMenu1. With the menu selected enter the text: Order, overwriting the default menu label text, and then press the Enter key.

d. Select the new Order menu, and replace the name property value of jMenu1with: menuOrder, and press the Enter key.

e. Save your work, and compile the class ensuring that there are no compilation errors. What lines has JDeveloper added to the OrderEntryMDIFrame class?

2. Add the menu items and a separator to the Order menu.a. Create each menu item by selecting the blank outline box at the bottom of the

Order menu, and enter the menu label text in the box. You can select the menuOrder menu from the Structure so that the outline boxes are visible. After creating the menu item entry, select the menu item box and set its name property in the Inspector, according to the following table:

Hint: You may want to add all menu labels first, and then set the name properties.

b. Save and compile the class. Then run OrderEntry.java to view the menu.Add Components to OrderEntryFrame to Form its Visual Structure

3. To add UI components, open OrderEntryFrame.java by right-clicking its name in the Navigator; select the Design tab to invoke the UI Editor.

a. In the top panel, add Jlabel and JTextField components for the Customer details. (These components can be found in the Swing pulldown.) Use the sample window on the previous pages as a guide for the layout. Create label and text field items by using the following table:JLabel text property JTextField name propertyCustomer Id custIdTxtName custNameTxtAddress custAddressTxtPhone custPhoneTxt

Hint: Aligning UI components works best with XYLayout manager, in whichalignment is relative to the first component clicked. Select additional components, while holding [Shift] or [Control]. Right-click a selected component and choose an Align option from the context menu. (Null layout hints on next page).

Page 487: Java Programming

Oracle10g: Java Programming 15-19

Practice 15-1: Adding User Interface Components (continued)Hint: If you are using the null layout manager, then JDeveloper generates calls to each component setBounds() method, with a Rectangle parameter defining the components x, y location, width, and height. You can alter the parameters (x, y, width, height) in the Rectangle constructor to manually align and size components, or set the bounds property for each component in the Inspector.

b. Select the JTextField1 component next to the Order Id label. Change its name property to orderIdTxt.

c. Multiselect all customer JTextField items that you created in 3a, and delete the text property, then press the Enter key.Note: Selecting multiple components and changing a property value sets the property to the same value for all the selected items.

d. Add a JButton to the right of the customer ID text field, and set the text property to Find, and the name property to findBtn. Then save your work.

4. Add the components for the other order information, and components for addingproducts to the order.

a. Create a JLabel and set the text property to Product Id. To the right of the label add a JTextField and set its name property to prodIdTxt and delete the value in the text property (and press the Enter key).

b. Below the product ID label and text field create a JButton component, and set the name and text properties as follows:Name property Text propertyaddBtn Add

c. Add two Jlabel components at the top-right side of the top panel, for the order date. Set the first label text property to Order Date. Set the second label’s name to orderDateLbl and its text property to the empty string. Select the Swing Border option from the list and from the Border window, select the LineBorder value. Set the border thickness to 1, if its not already set.

d. Add two more Jlabel components under the order date labels, for the order total. Set the first label text property to Order Total. Set the second label’s name to orderTotalLbl and its text property to the empty string. Select the Swing Border option from the list and from the Border window, select the LineBorder value. Set the border thickness to 1, if its not already set.

e. Add a JList component into the scroll pane in the bottom panel of the OrderEntryFrame. The list component should fill the entire bottom section of the frame (just click in the lower pane, and the Jlist will expand and take up the entire pane). Set the list name property to orderItemList.

f. Save and compile the OrderEntryFrame class.g. Run the OrderEntry.java application to view the resulting UI layout in the

internal frame. Quickly make minor adjustments to the UI layout to make all items pleasantly visible.

Page 488: Java Programming

Oracle10g: Java Programming 15-20

15-20 Copyright © 2004, Oracle. All rights reserved.

Java Event Handling Model

• How it works:– Event originates from source and generates an

event object.– An event listener hears a specific event.– An event handler determines what to do.

• Setting it up:1. Create an event source object.2. Create an event listener object implementing an

interface with methods to handle the event object.3. Write an event-specific method to handle the event.4. Register the listener object with the event source

for the specified event.

Java Event Handling ModelThere are four components of the Java event handling model:

• Event source: The object or component from which the event comes. For example, a mouse-click event could originate from a button.

• Event object: The object that is generated when the event occurs. (This object is passed to an event listener.)

• Event listener: A method whose job is to listen for a specific event, and then run an event handler when the event occurs by receiving the event object from the event source

• Event handler: A method whose job is to handle a specific event and event objectThe following slides illustrate the event handling model in detail.

Page 489: Java Programming

Oracle10g: Java Programming 15-21

15-21 Copyright © 2004, Oracle. All rights reserved.

Event Handling Code Basics

• Create the event source.

• Create the event listener implementing the required event interface.

• Register the listener with the event source.

Jbutton findBtn = new Jbutton("Find");

class MyListener implements ActionListener {

public void actionPerformed(ActionEvent e) {

// handler logic

}

}

findBtn.addActionListener(new MyListener());

Java Event Handling Code BasicsThe above slide shows the key steps to create an event source object; for example, a JButton. When the button (event source) is pressed with an Enter key (if it has focus), or if you click the button with the mouse, the button creates the event object, a java.awt.eventActionEvent object. If listeners are registered with a button to listen for the ActionEvent, then their handler method will be called by the event firing mechanism of the button.The second code example in the slide shows creating the class for the event listener that implements the java.awt.event.ActionListener interface, requiring that you write a single method with the following signature:

public void actionPerformed(ActionEvent e);The actionPerformed() method receives an event object reference that is created by the event source, in this case an ActionEvent. The handler code can optionally use the event object to get information from or find out about the event source. The body of the method effectively handles the event by implementing the code to manage the event. The event handling code executes on the Java event handling thread.The third code example shows the final piece to the puzzle, where the listener object is created in the argument of the addActionListener() method, thereby registering the listener object with event source to handle the ActionEvent; that is, the button-pressed or clicked event.

Page 490: Java Programming

Oracle10g: Java Programming 15-22

15-22 Copyright © 2004, Oracle. All rights reserved.

OK

SourceEvent listener object

Handler method

Event Handling Process: Registration

MyListener actionListenerObj = new MyListener();

public void jbInit() {

button1.addActionListener(actionListenerObj);

}

Event Handling Process: RegistrationRegistering the ListenerAs already seen, the final stage in the event handling coding process is the registration of the listener with the event source. The event listener registers “interested” in a particular type of event. For example, “I am interested in button clicks.”Registering Listener ObjectsAn event listener receives events from a source only if it registers with that source as a listener for a particular type of event. For each type of event that it can generate, a source object provides a method that allows objects to register themselves as listeners for that event.

Page 491: Java Programming

Oracle10g: Java Programming 15-23

Event Handling Process: Registration (continued)Registering Listener Objects (continued)For example, consider a button. A Button object can generate ActionEvents, so theButton class provides a method called addActionListener(). The example on the slides shows how to call this method to register the listener object that was created on the previous slide. This MyListener object is added to a list of listeners that are informed when the button is clicked. This listener object contains the code to handle theevent.Note: There is a method called removeActionListener(), which allows a listener to be removed from the list of registered listeners; for example,

findBtn.removeActionListener( actionListenerObj);

The event handling model is enforced because the classes follow coding rules as follows:• The event object class is called XXXEvent• The listener implements an interface called XXXListener interface.• The event source provides an addXXXListener() method, which accepts an object

argument that implements the appropriate XXXListener interface.

Page 492: Java Programming

Oracle10g: Java Programming 15-24

15-24 Copyright © 2004, Oracle. All rights reserved.

Event Handling Process:The Event Occurs

Notified

public void jbInit() {

button1.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

// Your code to handle the ActionEvent

}

}); … }

OK

SourceEvent listener object

Handler method

Notifying the Listener of the EventWhen the event occurs, the listener is notified that the event it is interested in has occurred. An event source notifies an event listener object by invoking a method on it and passing it an event object. Events are delivered only to registered listener objects. An object never receives unsolicited events, and events that are not handled are simply ignored.

Listening for an EventWhen an event occurs, the event source notifies an event listener by calling an event-specific method on the listener; all listeners for a particular type of event must provide the appropriate method. For example, the event that occurs when a button is clicked is ActionEvent. All listeners for an ActionEvent must provide an actionPerformed() method, because this is what the event source will try to call.

Implementing the Event Listener as an Inner ClassThe example on the slide shows how to implement the event listener object and register it with the event source in one step. You can do this by implementing the event listener object as an anonymous inner class.The particular type of inner class event adapters that JDeveloper generates by default are known as anonymous adapters. This implementation of anonymous adapters avoids the creation of a separate (named) adapter class. The resulting code is compact and elegant.

Page 493: Java Programming

Oracle10g: Java Programming 15-25

15-25 Copyright © 2004, Oracle. All rights reserved.

Event Handling Process:Running the Event Handler

SourceOK

SourceEvent listener object

Handler method:save changes and quit

Running the Event HandlerThe event listener contains an event handler. After the event listener receives notification, it runs its event handler. For example, if the button is a Save button, the event handler would save the data on the form.How Is This Enforced?All listeners for an ActionEvent must implement the ActionListener interface. The various listener interfaces specify the methods that you must implement in your listener class. The ActionListener interface only stipulates one method for you to implement:

public interface ActionListener {public void actionPerformed(ActionEvent e);

}

Instructor NoteWriting event handling code can be confusing. If the students have problems understanding the implementation details, you could tell them that JDeveloper simplifies the implementation of event handling. They must understand the concepts and have an idea of the different classes; JDeveloper handles the rest. Handling errors with JDeveloper is covered later in this lesson.

Page 494: Java Programming

Oracle10g: Java Programming 15-26

15-26 Copyright © 2004, Oracle. All rights reserved.

interface MouseListener {

// Declares five methods

} class MouseAdapter implements MouseListener {

// Empty implementations of all five methods

}

public class MyListener extends MouseAdapter {

// Override only the methods you need

}

Using Adapter Classes for Listeners

Adapter classes are “convenience” classes that implement event listener interface:• They provide empty method implementations.• They are extended and the desired method

overridden.

The Adapter ClassesSome of the event listener interfaces contain more than one method. For each of these interfaces, there is a simple adapter class that provides an empty body for each method in the interfaces.For example, MouseListener contains five methods. If you implement MouseListener directly, then you must implement all five of its methods, even if you are only interested in one of them. Alternatively, you can extend the MouseAdapter class. If you do this, then you can override the methods that you need and ignore the rest.There is no adapter class for the ActionListener interface, because the interface has only one method.

Page 495: Java Programming

Oracle10g: Java Programming 15-27

15-27 Copyright © 2004, Oracle. All rights reserved.

Swing Model View Controller Architecture

• Model, View, Controller principles

• Terms explained:– Model represents the data or information.– View provides a visual representation of the data.– Controller handles events modifying the

view/model.• Always update Swing components on the event

thread queue, or use SwingUtilities methods.

Model

Controller ViewViewEventmodify

modify Notify update

Get changed data

Importance of Swing Model View Controller ArchitectureThe Model View Controller (MVC) design forms dynamic associations between the visual representation of the data object, the data, and events. The MVC design allows multiple views to the same data (model), keeping the various views synchronized as the data is modified. This forms the foundation for creating data aware components.The slide shows that when an event occurs that causes changes to a visual component, the view requests the appropriate data from the model. If the event causes a change to the model, then the model notifies the view that a change occured and the view in turn makes a request for the changed data from the model.In Swing terms, a UI component represents a view. Each component passes an event object to a “listener” object or controller to handle the event. Depending on the event, the controller modifies the view or model. If the model class is one of those provided by the Swing API that is suitable for the associated UI component, then changes to the model are automatically visible through the view.

Page 496: Java Programming

Oracle10g: Java Programming 15-28

Importance of Swing Model View Controller Architecture (continued)Using a JList with a Vector is possible, but adding elements to the Vector does not update the JList contents for two reasons:

• The Vector is not the appropriate model class for a JList.• The JList creates an internal ListModel from the vector items.

However, if you explicitly create a DefaultListModel object, and associate it with a JList, then as items are added to the DefaultListModel object, the JList will reflect the changes automatically.Note: The diagram on the slide represents classic MVC. Swing components use a modified form of MVC to support pluggable look and feel.

Page 497: Java Programming

Oracle10g: Java Programming 15-29

Importance of Swing Model View Controller Architecture (continued)Swing Components (View) and Model ClassesThe table below shows the Swing components and interfaces that can be implemented by model classes to provide MVC functionality. Each interface has been implemented by a class in the Swing API packages; the implementing classes are also shown.

Swing components, by default, implicitly create and store data in a default model that suits their requirement. You can use all components to explicitly create and use an appropriate model, usually based on those shown in the table above.

Swing components Model interface Class implementing model interface

JTextField, JPasswordField, JTextArea, JTextPane, JEditorPane

Document (found in javax.swing.text package).

PlainDocument, and DefaultStyledDocument.

JButton, JCheckBox, JCheckBoxMenuItem, JMenu, JMenuItem, JRadioButton, JRadioButtonMenuItem, JToggleButton

ButtonModel DefaultButtonModel.

JComboBox ComboBoxModel DefaultComboBoxModel. JProgessBar, JScrollBar, JSlider

BoundedRangeModel DefaultBoundedRangeModel

JList ListModel, ListSelectionModel DefaultListModel, DefaultListSelectionModel

JTable TableModel (found in javax.swing.table package) ListSelectionModel

DefaultTableModel, DefaultListSelectionModel

JTree TreeModel TreeSelectionModel (both interfaces found in javax.swing.table package)

DefaultTreeModel, DefaultTreeSelectionModel

Page 498: Java Programming

Oracle10g: Java Programming 15-30

15-30 Copyright © 2004, Oracle. All rights reserved.

Basic Text Component Methods

• Text item (JLabel, JTextField, and JButton) methods:void setText(String value)String getText()

• Additional methods in JTextArea:void append(String value)void insert(String value, int pos)

• Changes to component contents are usually done in the event handling thread.

Note: Consult the Java API documentation for details about each component’s capabilities.

Getting and Setting PropertiesThe various Swing components have different methods to populate them with values, and to retrieve the values contained in the component. In general, most text items, such as labels, text fields, and text areas, have a setText(String value) method that sets the contents to the specified string value, or a String getText() method that returns the contents as a String object.Note: You must use the setText() and getText() methods to change or get the label of a JButton object, respectively. Do not use the setLabel() and getLabel()methods that are now deprecated.JTextArea objects are multiline text items, and therefore allow you to append to the existing contents, insert at a particular position in the text, or replace text. See the Java API documentation for information about its methods.

Page 499: Java Programming

Oracle10g: Java Programming 15-31

15-31 Copyright © 2004, Oracle. All rights reserved.

Basic JList Component Methods

Subset of JList component methods include:• void setListData(Vector)

– Copies Vector to a ListModel applied with setModel

• void setModel(ListModel)– Sets model representing the data and clears

selection. Uses DefaultListModel class for the model.

• Object getSelectedValue()– Returns the selected object, or null if nothing is

selected• int getSelectedIndex()

– Returns the index of the selected item, or –1 if nothing is selected

List ComponentsThe JList and JComboBox are Swing components that handle lists of data. The slide discusses some of the methods that are provided by the JList class.

Vector vector = new Vector();Jlist list = new JList(vector);

For example, if you create a JList object with the constructor accepting a vector, then the vector elements are copied to an internally created DefaultListModel object. Thus, if you add elements to the vector, with the addElement() method, then the new elements will not be visible through the Jlist unless you call theJList.setListData() method passing the updated

vector object as an argument his isinefficient as the elements are copiedfrom the vector again and a newDefaultListModel object is created internally

t is better to create the DefaultListModel

object first and use it like you would aVector and create the JList with the

appropriate constructor for exampleDefaultListModel model = new DefaultListMode();Jlist list = new JList(model);

or call the setModel() method s elementsare added to the DefaultListModel object by

Page 500: Java Programming

Oracle10g: Java Programming 15-32

15-32 Copyright © 2004, Oracle. All rights reserved.

Events that a component can generate

Event handler methods

What Events Cana Component Generate?

Each Type of Component Generates Different EventsTo find out what events a component is capable of generating, select the component in the Designer pane and click the Events tab in the Inspector window. This shows a list of all the events that the component can generate. For each event, the Inspector also shows whether an event handler method has been installed yet. On the slide, the Inspector shows all the events for the JButton component, findButton. You have not installed any event handlers yet, so the Inspector does not have any event handler methods to advertise in the list.

Page 501: Java Programming

Oracle10g: Java Programming 15-33

15-33 Copyright © 2004, Oracle. All rights reserved.

1: Select the event that you want to handle.

2: Click the right column to fill in a method name.

3: Double-click the right column to create the method.

How to Define an Event Handlerin JDeveloper

Defining an Event Handler with JDeveloperJDeveloper makes it easy to define event handler methods in your code:

• In the UI Editor, select the component that you want to provide an event handler for.• In the Inspector, the Events tab shows a list of all the events that the component can

generate. Click the event that you want to handle.• Click the right column for that event; the Inspector suggests a name for the event

handler method that it is about to generate. In the example, the event handler method will be called findButton_actionPerformed.

• Click the ‘…’ button and it will suggest a name for the event handler method in the dialog box. JDeveloper will then generate the event handler method in your code.

Note that double-clicking the button in the UI Editor creates the listener and handler. It is an alternative to clicking the Events tab of the Inspector and double-clicking the name of the listener.The actionPerformed EventMany UI components have a special event called actionPerformed. For most components, actionPerformed is the most commonly used event. For example, a JButton generates an actionPerformed event when it is clicked, whereas a JListgenerates an actionPerformed event when it is double-clicked. Use actionPerformed when possible, rather than an event such as mouseClicked.

Page 502: Java Programming

Oracle10g: Java Programming 15-34

15-34 Copyright © 2004, Oracle. All rights reserved.

public void jbInit() throws Exception {

findButton.addActionListener(

new java.awt.event.ActionListener() {

public void actionPerformed(ActionEvent e) {

findButton_actionPerformed(e);

}

}); …

void findButton_actionPerformed(ActionEvent e) {

// Your code to handle the ActionEvent

}

Find

Default Event Handling Code Style Generated by JDeveloper

What Happens When the Event Is Fired?• When the button is clicked, it examines its list of registered listener objects and calls

the actionPerformed() method on each listener object. One of the listener objects is the new (nameless) ActionListener object, created and registered in the applet’s jbInit() method.

• The listener object’s implementation of actionPerformed() calls the handler method.

By default, JDeveloper uses anonymous inner classes in the event handling code that it generates, but you can configure JDeveloper to create a separate listener class instead, called a Standard Adapter style.The procedure for selecting this code style option is as follows:

• Tools > Preferences• Select the Code Style node and in the Event Handling section,

select either:- The Anonymous Inner Class option button, or- The Standard Adapter option button.

Page 503: Java Programming

Oracle10g: Java Programming 15-35

15-35 Copyright © 2004, Oracle. All rights reserved.

public class JFrame1 extends JFrame {

void findButton_actionPerformed(ActionEvent e){

// When the user clicks the button, display

// the list of customers in jTextArea1

String findList = (“Supplies-R-Us " + "\n" +

“Consulting Inc. " + "\n" +

“Just-In-Time Training ");

jTextArea1.setText(findList);

}

}

Completing the Event Handler Method

Completing the Event Handler MethodWhen you add an event handler method in JDeveloper, it defines a skeleton method in your program and also generates the event listener code to make sure that the method is called when the event occurs.Using Methods in the Button and Label ClassesThe event handler that is shown on the slide will be called when findButton is clicked. When that happens, the event handler method performs the following tasks:

• Constructs a string that contains a list of customers. In a real application, the string would be built by a call to a method that returns a string. That method could retrieve the data from a database, a file, or wherever.

• Calls JTextArea1.setText()to set the text property of the form’s text area to the string list of customers

Page 504: Java Programming

Oracle10g: Java Programming 15-36

15-36 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:• Add a Swing component to a visual container• Get and modify the contents of the components• Use the AWT event handling model to:

– Create an event source– Create an event listener and handler code– Register an event listener for the event to be

handled• Create a menu bar with menus and menu items• Handle events

Page 505: Java Programming

Oracle10g: Java Programming 15-37

15-37 Copyright © 2004, Oracle. All rights reserved.

Practice 15-2: Overview

This practice covers adding event handling for:• Order > New menu• Find Customer button• Add Product button

Practice 15-2: OverviewNote: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you would like to move on to this practice, then change to the les15-1 directory, load up the OrderEntryLes15-1 workspace, and continue with this practice.Viewing the model: To view the course application model up to this practice, load the OrderEntryWorkspaceLes15-1 workspace. In the Applications – Navigator node, expand the OrderEntryWorkspaceLes15-1 – OrderEntryProjectLes15-1 - Application Sources – oe, and double-click the UML Class Diagram1entry. This diagram displays all the classes created to this point in the course.Note: A Remove button has been added to the practice 15 solution workspace to demonstrate how to include the “remove” functionality. Adding the button and event code is not part of this practice, and is included only as an opportunity to see how this type of functionality works. Using this solution application should not impede your ability to successfully complete the entire application.

Page 506: Java Programming

Oracle10g: Java Programming 15-38

Practice 15-2: Adding Event HandlingGoalIn this practice, you create the order entry details. You will add event handling code for the Order > New Menu, Find Customer Button and Add Product and Remove Product Buttons. To save time, you can cut and paste code from E:\labs\les15.txt.Note: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you would like to move on to this practice, then change to the les15-1 directory, load up the OrderEntryLes15-1 workspace, and continue with this practice.Add Event Handling for Order > New Menu

1. Edit OrderEntryFrame.java in the Code Editor to create an order object and display its initial state in the appropriate components.

a. Create a new instance variable forthe order object as follows

Order order = null;

b dd the following method to createa new order object and display itscontents in the appropriatecomponents in the frameprivate void initOrder() {

order = new Order();orderIdTxt.setText(

Integer.toString(order.getId()));orderDateLbl.setText(

Util.toDateString(order.getOrderDate()));orderTotalLbl.setText(

Util.toMoney(order.getOrderTotal()));}

c all the initOrder() method at end ofthe jbInit() method

d o control the x y location of thetop left corner of the frame whenit is displayed declare thefollowing instance and classvariables

private static int x = 0;private static int y = 0;private static final int OFFSET = 20;private static final int MAX_OFFSET = 200;

and create the following method tocreate a cascading effect as neworderframes are created

Page 507: Java Programming

Oracle10g: Java Programming 15-39

Practice 15-2: Adding Event Handling (continued)Add Event Handling for Order > New Menu (continued)

d. private void setBounds() {this.setResizable(true);

this.setBounds(x, y,

this.getWidth(), this.getHeight());x = (x + OFFSET) % MAX_OFFSET;

y = (y + OFFSET) % MAX_OFFSET;}

e dd a call to your setBounds() method atthe end of the jbInit()method aftercalling initOrder()

f dd one more method to OrderEntryFrame

to make it the active window asfollows

public void setActive(boolean active) {

try {this.setSelected(active);

}

catch (Exception e) {}this.setVisible(active);

if (active) {this.toFront();

}

}

ote his method will be called fromthe Order > New menu event handler

g ompile and save the OrderEntryFrame

class2 dit OrderEntryMDIFrame.java to create the

event handler code for the new ordermenu optiona pen OrderEntryMDIFrame.java in the ditor

and expand the menu either in thevisual editor or the tructurepane and then select the New menuitem under the Order menu

b Click the Events tab of the Inspector window (second icon from the left), click in the text area to the right of the first event called actionPerformedhe text area will show a buttonwith three dots ellipses lickthis button to display theactionPerformed event generation dialog

Page 508: Java Programming

Oracle10g: Java Programming 15-40

Practice 15-2: Adding Event Handling (continued)c. ove the following lines from the

OrderEntryMDIFrame() constructor to thebody of the newMenuItem_actionPerformed()

method deleting or commenting outthe line making the frame visibleas shown

OrderEntryFrame iFrame = new OrderEntryFrame();// iFrame.setVisible(true);desktopPane.add(iFrame);

lso add the following line afteradding the frame to the desktoppane

iFrame.setActive(true);d ompile the OrderEntryMDIFrame class and

save the changes un and test theOrderEntry application by selecting

the Order > New menuote hen the application firststarts there should not be anyorder window displayed lose theinternal window by clicking itslose icon X

Add Event Handling for Find Customer ButtonIn this section of the code, you test if the customer Id text field has a non-zero length string, and convert it to an integer used in the DataMan.findCustomerById() method to return a valid customer. If the customer Id field is empty, or is not a number, then the DataMan.findCustomerById() method throws a NotFoundException.Then you display an error message using the javax.swing.JOptionPane class. If the customer is a valid customer, then associate the customer object with the order and display the customer details in the field that is provided in OrderEntryFrame.

3. Edit the OrderEntryFrame class in the UI Editor.a. Select the Find button, and click the Events tab in the Inspector, and generate the

skeleton code for the actionPerformed event.b. In the body of the generated findBtn_actionPerformed() method add

the following code:

int custId = 0;Customer customer = null;if (custIdTxt.getText().length() > 0) {

try {custId = Integer.parseInt(custIdTxt.getText());customer = DataMan.findCustomerById(custId);order.setCustomer(customer);custNameTxt.setText(customer.getName());custAddressTxt.setText(customer.getAddress());custPhoneTxt.setText(customer.getPhone());

Page 509: Java Programming

Oracle10g: Java Programming 15-41

Practice 15-2: Adding Event Handling (continued)catch (NumberFormatException err) {

JOptionPane.showMessageDialog(this,"The Customer Id: " + err.getMessage() +" is not a valid number","Error", JOptionPane.ERROR_MESSAGE);

custIdTxt.setText(""); }

catch (NotFoundException err) {JOptionPane.showMessageDialog(this,

err.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);

custIdTxt.setText("");}

}else {

JOptionPane.showMessageDialog(this,"Please enter a Customer Id", "Error",JOptionPane.ERROR_MESSAGE);

}Note: Remember to import javax.swing.JOptionPane.

c. Compile and save your changes. Run the OrderEntry application to test your code changes (customer IDs range from 1 to 6).

Optional Extra CreditAdd Event Handling for Add Product ButtonWrite code to add products to the order. The code reads the product ID that is entered and supplies it to the order.addOrderItem() method. You also update the Order Total field with the latest total after each product is added to the order. Handle errors as appropriate. The Remove button should be disabled if an item is not selected from the list.4 dit the OrderEntryFrame class in theditora. Select the Add button to generate its actionPerformed event handler containing

the following code:void addBtn_actionPerformed(ActionEvent e)

Product p = null;int prodId = 0;if (prodIdTxt.getText().length() > 0) {

try {prodId = Integer.parseInt(prodIdTxt.getText());p = DataMan.findProductById(prodId);order.addOrderItem(p.getId());orderTotalLbl.setText(

Util.toMoney(order.getOrderTotal()));}

Page 510: Java Programming

Oracle10g: Java Programming 15-42

Practice 15-2: Adding Event Handling (continued)catch (Exception err) {

String message = err.getMessage();if (err instanceof NumberFormatException) {

message = "Product id '" + message +"' is not a valid number";

}JOptionPane.showMessageDialog(this, message,

"Error", JOptionPane.ERROR_MESSAGE);prodIdTxt.setText("");

}}else {

JOptionPane.showMessageDialog(this,"Please enter a Product Id", "Error",JOptionPane.ERROR_MESSAGE);

}}

b ompile and save the code un theOrderEntry application to test the

codedd products to the order products start at 2000 id you see theproductsvisually added to the list f notexplain why id the order total getupdated

5 odify the Order class to support theby replacing the Vectortype for items to

be a javax.swing.DefaultListModel rovide amethod in the Order class to return the

reference to the modela dit the Order.java class and replacethe items declaration as shown// private Vector items = null; // replace with ...private DefaultListModel items = null;

ote ou will need to importjavax.swing.DefaultListModel

b n the rder no arg constructorcreate the DefaultListModel object toinitiali e the items variableinstead of using a Vector or example// items = new Vector(10);items = new DefaultListModel();

c dd a new method with the signatureshown to return the items reference

to the callerpublic DefaultListModel getModel() { … }

ote his method will be used as themodel for the JList causing it to

Page 511: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Using JDBC to Access the Database

Schedule: Timing Topic50 minutes Lecture30 minutes Practice80 minutes Total

Page 512: Java Programming

Oracle10g: Java Programming 16-2

16-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Describe how Java applications connect to the

database• Describe how Java database functionality is

supported by the Oracle database• Load and register a JDBC driver• Connect to an Oracle database• Follow the steps to execute a simple SELECT

statement• Map simple Oracle database types to Java types

Lesson AimThis lesson introduces you to using Java to access an Oracle database. This lesson introduces you to the basic use of JDBC to query a database from a Java class. It presents the different steps required to perform SQL statements.

Page 513: Java Programming

Oracle10g: Java Programming 16-3

16-3 Copyright © 2004, Oracle. All rights reserved.

Java, J2EE, and Oracle 10g

Oracledatabase

Web serverClient

Application server

Presentation Businesslogic

Data

OracleApplication Server 10g

J2EE Certified Environment

JDBC

Java and Oracle 10gOracle provides a complete and integrated platform called Oracle 10g, which supports all of the server-side requirements for Java applications. Oracle 10g consists of the following:Oracle DatabaseIn addition to its database management features, the Oracle database (currently Oracle 10g) provides support for a variety of Java-based structures, including Java components and Java stored procedures. These Java structures are executed in the database by its built-in Java Virtual Machine, called the Oracle Java Virtual Machine (Oracle JVM).Oracle Application Server 10gOracle Application Server 10g maintains and executes all your application logic, including Enterprise JavaBeans, through its own built-in JVM, the Enterprise Java Engine. Oracle Application Server 10g uses Apache Web server to access the OC4J where servlets and JSPsare executed.

Using J2EE with Oracle 10gJ2EE is a standard technology which provides a set of APIs and a run-time infrastructure for hosting and managing applications. It specifies roles and interfaces for applications and the run time onto which applications can be deployed. And, hence, the application developers need to focus only on the application logic and related services, while leveraging the run time for all infrastructure-related services.

Page 514: Java Programming

Oracle10g: Java Programming 16-4

16-4 Copyright © 2004, Oracle. All rights reserved.

Client application or applet

Connecting to a Database with Java

Client applications, JSPs, and servlets use JDBC.

JDBC Relational DB

How Java Connects to a DatabaseTo query an Oracle database, any Java application must have a way to connect to the database. This is performed by using JDBC.Java Database Connectivity (JDBC) is a standard application programming interface (API) that is used for connecting a Java application to relational databases. The networking protocol that is used depends on which JDBC driver you are using. For example, the OCI driver uses Oracle Net, or thin driver uses TCP/IP Running SQL from a Server-Side ApplicationJava procedures inside the database use JDBC to execute their SQL queries. This includes Java stored procedures.

Instructor NoteIf you are connecting within the server, you can use the default connection. A Java stored procedure accesses the database by using the default connection. To connect within the server, you must first connect to the server from outside, so you already have a database session. The default connection takes the same user and privileges as your existing database session. Therefore, you do not need to specify a URL, user ID, or password for the default connection. You can also use the URL, jdbc:oracle:kprb, as an alternative way to get the default connection.

Page 515: Java Programming

Oracle10g: Java Programming 16-5

16-5 Copyright © 2004, Oracle. All rights reserved.

• JDBC is a standard interface for connecting to relational databases from Java.– The JDBC API includes Core API Package in

java.sql.– JDBC 2.0 API includes Optional Package API in

javax.sql.– JDBC 3.0 API includes the Core API and Optional

Package API

• Include the Oracle JDBC driver archive file in the CLASSPATH.

• The JDBC class library is part of the Java 2, Standard Edition (J2SE).

What Is JDBC?

Java Database Connectivity (JDBC)The java.sql package contains a set of interfaces that specify the JDBC API. This package is part of Java 2, Standard Edition. Database vendors implement these interfaces in different ways, but the JDBC API itself is standard.Using JDBC, you can write code that:

• Connects to one or more data servers • Executes any SQL statement • Obtains a result set so that you can navigate through query results • Obtains metadata from the data server

Each database vendor provides one or more JDBC drivers. A JDBC driver implements the interfaces in the java.sql package, providing the code to connect to and query a specific database.

Instructor NoteJDBC 1.22 is part of JDK 1.1; JDBC 2.0 is part of Java 2.

Page 516: Java Programming

Oracle10g: Java Programming 16-6

16-6 Copyright © 2004, Oracle. All rights reserved.

// Standard packagesimport java.sql.*;

import java.math.*; // optional

// Oracle extension to JDBC packagesimport oracle.jdbc.*;

import oracle.sql.*;

Preparing the Environment

• Set the CLASSPATH:

• Import JDBC packages:

[Oracle Home]\jdbc\lib\classes12.jar

Requirements for Using Oracle JDBCThis section describes the environment variables that must be set for the JDBC OCI driver and the JDBC thin driver, focusing on the Sun Microsystems Solaris and Microsoft Windows NT platforms.You must set the CLASSPATH for your installed JDBC OCI or thin driver.Depending on whether you are using the SDK 1.2.x versions or JDK 1.1.x versions, you must set one of these values for the CLASSPATH:• [Oracle Home]/jdbc/lib/classes12.jar

(and optionally [Oracle Home]/jdbc/lib/nls_charset12.jar) for fullNLS character support)

or:• [Oracle Home]/jdbc/lib/classes111.jar

(and optionally [Oracle Home]/jdbc/lib/nls_charset11.jar) for fullNLS character support)

Ensure that there is only one classes*.zip file version and one nls_charset*.zipfile version in your CLASSPATH.

Page 517: Java Programming

Oracle10g: Java Programming 16-7

Requirements for Using Oracle JDBC (continued)JDBC OCI DriverIf you are installing the JDBC OCI driver, you must also set the following value for the library path environment variable: [Oracle Home]/libThe JDBC PackageYour Java class must import java.sql.* to be able to use the JDBC classes and include the JDBC driver classes from your database vendor in the CLASSPATH.For more information about required path and classpath settings for Oracle JDBC, refer to the Oracle 10g JDBC Developer’s Guide and Reference.

Page 518: Java Programming

Oracle10g: Java Programming 16-8

16-8 Copyright © 2004, Oracle. All rights reserved.

Steps for Using JDBC to ExecuteSQL Statements

1. Register JDBC driver.

4. Execute SQL statement.

4a. Process SELECTstatement.

4b. Process DML or DDL statement.

6. Close connections.5. Process query results.

3. Create statement object.

2. Obtain a connection.

Steps to Execute an SQL Statement with JDBCThe following are the key steps:

1. Load and register the driver. (Use the java.sql.DriverManager class.)2. Obtain a connection object. (Use java.sql.DriverManager to do this.)3. Create a statement object. (Use the Connection object.)4. Execute a query, DML, or DDL. (Use the Statement object.)5. If you obtain a ResultSet object while executing a query, then iterate through the

ResultSet to process the data for each row that satisfies the query.6. Close the ResultSet, Statement, and Connection objects, when finished.

Dealing with ExceptionsWhen using JDBC, all the methods that access the database throw SQLException if anything goes wrong. You must always deal with this exception in your JDBC code.SQLException has a number of methods that you can call to get information about the exception, including:• getMessage(): Returns a string that describes the error• getErrorCode(): Retrieves the vendor-specific exception code• getSQLState(): Retrieves the SQL state value • Class.forName(): Throws a ClassNotFoundException if the specified

class cannot be found

Page 519: Java Programming

Oracle10g: Java Programming 16-9

16-9 Copyright © 2004, Oracle. All rights reserved.

Step 1: Registering the Driver

• Register the driver in the code:– DriverManager.registerDriver (new

oracle.jdbc.OracleDriver());– Class.forName

("oracle.jdbc.OracleDriver");

• Register the driver when launching the class:– java –D jdbc.drivers =

oracle.jdbc.OracleDriver <ClassName>;

Loading the DriverJDBC drivers must register themselves with the driver manager. There are two ways to perform this:

• Use the registerDriver() method of DriverManager.• Use the forName() method of the java.lang.Class class to load the JDBC

drivers directly, as follows:try { Class.forName("oracle.jdbc.driver.OracleDriver");

}

catch (ClassNotFoundException e) {}Using the Class.forName() method calls the static initializer of the driver class. The driver class does not need to be present at compile time. However, this method is valid only for JDK-compliant Java Virtual Machines.You can register the driver at execution time. In this case, the registering statements that may exist in your Java class are ignored.Example of using the –D jdbc option in the command line:C:>java –D jdbc.drivers=oracle.jdbc.OracleDriver MyClass

Instructor Noteoracle.jdbc.OracleDriver class provides new interfaces and classes that can be used in place of the previous oracle.jdbc.driver.OracleDriver classes.

Page 520: Java Programming

Oracle10g: Java Programming 16-10

16-10 Copyright © 2004, Oracle. All rights reserved.

Using the package oracle.jdbc.driver, Oracle provides different drivers to establish a connection to the database.

JDBC callsDatabase

commandsDatabase

Connecting to the Database

OracleDriver

• Thin client • OCI• Server-based• …

About JDBC DriversA JDBC driver implements the interfaces in the java.sql package, providing the code to connect to and query a specific database. A JDBC driver can also provide a vendor’s own extensions to the standard; Oracle drivers provide extensions to support special Oracle data types.Oracle provides three drivers:

• Thin client driver• OCI-based driver• Server-based driver

The Oracle JDBC driver is located in the file classes111.zip for JDBC 1.0 or in the file classes12.zip for JDBC 2.0. These archive files contain supporting classes for both the thin and OCI JDBC drivers.Supported JDK and JDBC versionsOracle has two versions of the thin driver and the OCI driver—one that is compatible with SDK 1.2 and one that is compatible with JDK 1.1.x. The J2SE versions support standard JDBC 2.0. The JDK 1.1.x versions support most JDBC 2.0 features, but must do so through Oracle extensions because JDBC 2.0 features are not available in JDK 1.1.x versions.

Page 521: Java Programming

Oracle10g: Java Programming 16-11

16-11 Copyright © 2004, Oracle. All rights reserved.

Client

Oracle JDBC Drivers: Thin Client Driver

• Is written entirely in Java• Must be used by applets

Server

Oracle

Applet

JDBC

Thin driver

Thin Client DriverThis driver can connect to an Oracle 10g database but also to either an Oracle8i database or an Oracle9i database. You must use this driver if you are developing a client application that can connect to different versions of an Oracle database, to provide maximum portability.To communicate with the database, the thin client driver uses a lightweight version of Oracle*Net over TCP/IP that can be downloaded at run time to the client.The Oracle JDBC Thin driver is a 100% pure Java, Type IV driver. It is targeted to Oracle JDBC applets but can be used for applications as well. Because it is written entirely in Java, this driver is platform-independent. It does not require any additional Oracle software on the client side. The thin driver communicates with the server by using Two Task Common(TTC), a protocol developed by Oracle to access the Oracle Relational Database Management System (RDBMS).The JDBC Thin driver allows a direct connection to the database by providing animplementation of TCP/IP that emulates Oracle Net and TTC (the wire protocol used by OCI) on top of Java sockets. Both of these protocols are lightweight implementation versions of their counterparts on the server. The Oracle Net protocol runs over TCP/IP only.Note: When the JDBC Thin driver is used with an applet, the client browser must have the capability to support Java sockets.

Page 522: Java Programming

Oracle10g: Java Programming 16-12

16-12 Copyright © 2004, Oracle. All rights reserved.

Application

JDBC

OCI driver

Oracle JDBC Drivers: OCI Client Drivers

• Is written in C and Java• Must be installed on the client

Client Server

Oracle ocixxx.dll

OCI Client Drivers• You must choose an OCI driver if you are developing an application and need

maximum performance.• The JDBC OCI driver is a Type II driver for use with client-server Java applications.• This driver requires an Oracle client installation, and therefore is Oracle platform-

specific and not suitable for applets.• The JDBC OCI driver provides OCI connection pooling functionality, which can either

be part of the JDBC client or a JDBC stored procedure.• The OCI driver supports Oracle7, Oracle8/8i, Oracle9i and Oracle 10g with the highest

compatibility. It also supports all installed Oracle Net adapters, including IPC, named pipes, TCP/IP, and IPX/SPX.

• The OCI driver, written in a combination of Java and C, converts JDBC invocations tocalls to the Oracle Call Interface (OCI), using native methods to call C-entry points. These calls are then sent over Oracle Net to the Oracle database server. The OCI driver communicates with the server by using the Oracle-developed TTC protocol.

• The OCI driver uses the OCI libraries, C-entry points, Oracle Net, CORE libraries, andother necessary files on the client machine on which it is installed.

Instructor NoteIn Oracle, the OCI driver is a single OCI driver for use with all database versions. It replaces the distinct OCI8 and OCI7 drivers of previous releases. While the OCI8 and OCI7 drivers are deprecated for Oracle, they are still supported for backward compatibility.

Page 523: Java Programming

Oracle10g: Java Programming 16-13

16-13 Copyright © 2004, Oracle. All rights reserved.

Choosing the Right Driver

Applet

Client application

EJB, servlet(on the middle tier)

Stored procedure

OCIThin

Driver

Thin

Server side

OCI

Thin

Type of Program

Choosing the Appropriate DriverConsider the following when choosing a JDBC driver to use for your application or applet:

• If you are writing an applet, you must use the JDBC Thin driver. JDBC OCI-based driver classes will not work inside a Web browser, because they call native (C language) methods.

• If you want maximum portability and performance under Oracle 10g and earlier, then use the JDBC Thin driver. You can connect to an Oracle server from either an application or an applet by using the JDBC Thin driver.

• If you are writing a client application for an Oracle client environment and needmaximum performance, then choose the JDBC OCI driver.

• If performance is critical to your application, you want maximum scalability of the Oracle server, or you need the enhanced availability features such as Transparent Application Failover (TAF) or the enhanced proxy features such as middle-tier authentication, then choose the OCI driver.

Page 524: Java Programming

Oracle10g: Java Programming 16-14

16-14 Copyright © 2004, Oracle. All rights reserved.

Step 2: Getting a Database Connection

• In JDBC 1.0, use the DriverManager class, which provides overloaded getConnection() methods.– All connection methods require a JDBC URL to

specify the connection details.• Example:

• Vendors can provide different types of JDBC drivers.

Connection conn = DriverManager.getConnection(

"jdbc:oracle:thin:@myhost:1521:ORCL","scott","tiger");

Getting a Connection to the DatabaseUse the DriverManager class to create a connection by calling the getConnection() method.The getConnection() method is overloaded, for example:• getConnection(String url)• getConnection(String url, Properties props), where properties

must include at least a value for the following key names: user and password.• getConnection(String url, String user, String password)

In each case, you must supply a URL-like string that identifies the registered JDBC driver to use, and the database connection string and security credentials, if required.

Instructor NoteJDBC 2.0 and later versions provide other ways of obtaining a connection object such as using JNDI instead of a database URL.

Page 525: Java Programming

Oracle10g: Java Programming 16-15

16-15 Copyright © 2004, Oracle. All rights reserved.

About JDBC URLs

• JDBC uses a URL-like string. The URL identifies– The JDBC driver to use for the connection– Database connection details, which vary depending

on the driver used

• Example using Oracle Thin JDBC driver:– jdbc:oracle:thin:@myhost:1521:ORCL

jdbc:<subprotocol>:<subname>

jdbc:oracle:<driver>:@<database>

Protocol Database identification

JDBC URLsJDBC uses a URL to identify the database connection. A JDBC URL looks different from an HTTP or FTP URL. But, like any URL, it is a locator for a particular resource; in this case, a database. The structure of a JDBC URL is flexible, allowing the driver writer to specify what to include in the URL. End users need to learn what structure their vendor uses.The slide shows the general syntax for a JDBC URL and the syntax that Oracle uses for connecting with an Oracle driver. The general syntax of a JDBC URL is as follows:jdbc:<subprotocol>:<subname>• jdbc is the protocol. All URLs start with their protocol.• <subprotocol> is the name of a driver or database connectivity mechanism. Driver

developers register their subprotocols with JavaSoft to make sure that no one else uses the same subprotocol name. For all Oracle JDBC drivers, the subprotocol is oracle.

• <subname> identifies the database. The structure and contents of this string are determined by the driver developer. For Oracle JDBC drivers, the subname is <driver>:@<database>, where:

- <driver> is the driver- <database> provides database connectivity information

The following slides describe the syntax of an Oracle JDBC URL for the different JDBC drivers for client-side Java application code.

Page 526: Java Programming

Oracle10g: Java Programming 16-16

16-16 Copyright © 2004, Oracle. All rights reserved.

JDBC URLs with Oracle Drivers

• Oracle Thin driver

• Oracle OCI driver

Syntax: jdbc:oracle:thin:@<host>:<port>:<SID>

Example: "jdbc:oracle:thin:@myhost:1521:orcl"

Syntax: jdbc:oracle:oci:@<tnsname entry>

Example: "jdbc:oracle:oci:@orcl"

JDBC URLs with Oracle DriversThe basic structure of the JDBC URL for connecting to a database using one of the Oracle JDBC drivers is jdbc:<subprotocol>:<driver>:<database>.Oracle Thin driver<driver> is thin.<database> is a string of the form <host>:<port>:<sid>. That is, it is the host name, TCP/IP port, and Oracle SID of the database to which you want to connect. For example: jdbc:oracle:thin:@eduhost:1521:ORCL

Oracle OCI driver<driver> is oci, oci8 or oci7, depending on which OCI driver you are using.<database> is a TNSNAMES entry from the tnsnames.ora file. For example: jdbc:oracle:oci:@eduhost

Page 527: Java Programming

Oracle10g: Java Programming 16-17

16-17 Copyright © 2004, Oracle. All rights reserved.

Step 3: Creating a Statement

JDBC statement objects are created from the Connection instance:• Use the createStatement() method, which

provides a context for executing an SQL statement.• Example:

Connection conn = DriverManager.getConnection(

"jdbc:oracle:thin:@myhost:1521:ORCL", "scott","tiger");

Statement stmt = conn.createStatement();

Statement Objects in JDBCThe execute() method is useful for dynamically executing an unknown SQL string. JDBC provides two other statement objects:• PreparedStatement, for precompiled SQL statements• CallableStatement, for statements that execute stored procedures

Objects and Interfacesjava.sql.Statement is an interface, not an object. When you declare a Statementobject and initialize it using the createStatement() method, you are creating the implementation of the Statement interface supplied by the Oracle driver that you are using.

Page 528: Java Programming

Oracle10g: Java Programming 16-18

16-18 Copyright © 2004, Oracle. All rights reserved.

Using the Statement Interface

The Statement interface provides three methods to execute SQL statements:• Use executeQuery(String sql)for SELECT

statements.– Returns a ResultSet object for processing rows

• Use executeUpdate(String sql) for DML or DDL.– Returns an int

• Use execute(String) for any SQL statement.– Returns a boolean value

Statement Objects in JDBC (continued)Use executeQuery(String sql) for SELECT statements.

• Returns a ResultSet object for processing rowsUse executeUpdate(String sql) for DML or DDL.

• Returns an int value indicating number of rows affected by the DML; otherwise, it is 0 for DDL

Use execute(String) for any SQL statement.• Returns a boolean value of true if the statement returns a ResultSet (such as a

query); otherwise, it returns a value of false

Page 529: Java Programming

Oracle10g: Java Programming 16-19

16-19 Copyright © 2004, Oracle. All rights reserved.

Step 4a: Executing a Query

Provide a SQL query string, without semicolon, as an argument to the executeQuery() method.• Returns a ResultSet object:

Statement stmt = null;ResultSet rset = null;

stmt = conn.createStatement();rset = stmt.executeQuery

("SELECT ename FROM emp");

Execute a Query and Return a ResultSet ObjectTo query the database, use the executeQuery() method of your Statement object. This method takes a SQL statement as input and returns a JDBC ResultSet object. This statement follows standard SQL syntax.

Page 530: Java Programming

Oracle10g: Java Programming 16-20

16-20 Copyright © 2004, Oracle. All rights reserved.

The ResultSet Object

• The JDBC driver returns the results of a query in a ResultSet object.

• ResultSet:– Maintains a cursor pointing to its current row of

data– Provides methods to retrieve column values

The ResultSet ObjectThe ResultSet object is a table of data representing a database result set, which is generated by executing a statement that queries the database.A ResultSet object maintains a cursor pointing to its current row of data. Initially, the cursor is positioned before the first row.A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, it is possible to iterate through it only once, and only from the first row to the last row. New methods in the JDBC 2.0 API make it possible to produce ResultSet objects that are scrollable and updatable.

Page 531: Java Programming

Oracle10g: Java Programming 16-21

16-21 Copyright © 2004, Oracle. All rights reserved.

Step 4b: Submitting DML Statements

1. Create an empty statement object:

2. Use executeUpdate to execute the statement:

Example:

Statement stmt = conn.createStatement();

int count = stmt.executeUpdate(SQLDMLstatement);

Statement stmt = conn.createStatement();

int rowcount = stmt.executeUpdate

("DELETE FROM order_items

WHERE order_id = 2354");

How to Update a Table in the DatabaseThe slide shows the syntax for the methods that execute a database update using a DML statement. Whereas executeQuery returns a ResultSet object containing the results of the query sent to the DBMS, the return value for executeUpdate is an int that indicates how many rows of a table were updated. When the method executeUpdate is used to execute a DDL statement, such as in creating a table, it returns the int 0. When the return value for executeUpdate is 0, it can mean: (1) the statement executed was an update statement that affected zero rows, or (2) the statement executed was a DDL statement.Example: Using the executeUpdate() method, the PICTURES table is populated with the region_id from the regions table.

System.out.println("Table Insert");stmt.executeUpdate ("INSERT INTO pictures (id)SELECT region_id FROM regions");

Page 532: Java Programming

Oracle10g: Java Programming 16-22

16-22 Copyright © 2004, Oracle. All rights reserved.

1. Create an empty statement object:

2. Use executeUpdate to execute the statement:

Example:

Statement stmt = conn.createStatement();

int rowcount = stmt.executeUpdate

("CREATE TABLE temp (col1 NUMBER(5,2),

col2 VARCHAR2(30)");

Step 4b: Submitting DDL Statements

Statement stmt = conn.createStatement();

int count = stmt.executeUpdate(SQLDDLstatement);

How to Create DDL StatementsThe slide shows the syntax for the methods that execute a DDL statement.executeUpdate() returns an int containing 0, for a statement with no return value, such as a SQL DDL statement.

Page 533: Java Programming

Oracle10g: Java Programming 16-23

16-23 Copyright © 2004, Oracle. All rights reserved.

Step 5: Processing the Query Results

The executeQuery() method returns a ResultSet.• Use the next() method in loop to iterate through

rows.• Use getXXX() methods to obtain column values

by column position in query, or column name.stmt = conn.createStatement();rset = stmt.executeQuery(

"SELECT ename FROM emp");while (rset.next()) {

System.out.println (rset.getString("ename"));}

The getXXX() MethodsThe ResultSet class has several methods that retrieve column values for the current row. Each of these getXXX() methods attempts to convert the column value to the specified Java type and return a suitable Java value. For example, getInt() gets the column value as an integer, getString() gets the column value as a string, and getDate() returns the column value as a date.

• The next() method returns true if a row was found; otherwise, it returns false. Use it to check whether a row is available, and to step through subsequent rows.

• There are many getXXX() methods to get the column values, where XXX is a Java data type. For example,getString(pos) returns column in pos as a String,getInt(idx) returns column in pos as an int,and so on.

• There is a potential problem of database null values and trying to use getInt, and so on, because Java primitives do not support null values. Usually, it is recommended that you use getBigDecimal if numeric values have nulls.

Page 534: Java Programming

Oracle10g: Java Programming 16-24

16-24 Copyright © 2004, Oracle. All rights reserved.

Step 6: Closing Connections

Explicitly close a Connection, Statement, and ResultSet object to release resources that are no longer needed.• Call their respective close() methods:Connection conn = ...; Statement stmt = ...;ResultSet rset = stmt.executeQuery(

"SELECT ename FROM emp");...// clean uprset.close(); stmt.close(); conn.close();...

Closing the ResultSet, Statement, and Connection ObjectsYou must explicitly close all ResultSet and Statement objects after you finish using them. The close() methods clean up memory and release database cursors, so if you do not explicitly close your ResultSet and Statement objects, serious memory leaks may occur, and you may run out of cursors in the database. You then need to close the connection.The server-side driver runs within a default session. You are already connected, and you cannot close the default connection made by the driver. Calling close() on the connection does nothing.

Page 535: Java Programming

Oracle10g: Java Programming 16-25

16-25 Copyright © 2004, Oracle. All rights reserved.

A Basic Query Example

import java.sql.*;class TestJdbc {public static void main (String args [ ]) throws SQLException {DriverManager.registerDriver (new oracle.jdbc.OracleDriver());Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@myHost:1521:ORCL","scott", "tiger");Statement stmt = conn.createStatement ();ResultSet rset = stmt.executeQuery

("SELECT ename FROM emp");while (rset.next ())

System.out.println (rset.getString ("ename"));rset.close();stmt.close();conn.close();}

}

Page 536: Java Programming

Oracle10g: Java Programming 16-26

16-26 Copyright © 2004, Oracle. All rights reserved.

ResultSet rset = stmt.executeQuery("SELECT empno, hiredate, jobFROM emp");

while (rset.next()){int id = rset.getInt(1);Date hiredate = rset.getDate(2); String job = rset.getString(3);

Column Name

empno

hiredate

job

Type

NUMBER

DATE

VARCHAR2

Mapping Database Types to Java Types

ResultSet maps database types to Java types:

Method

getInt()

getDate()

getString()

Mapping Database Types to Java TypesIn many cases, you can get all of the columns in your result set by using the getObject()or getString() methods of ResultSet. For performance reasons, or because you want to perform complex calculations, it is sometimes important to have your data in a type that exactly matches the database column. The JDBC section of the Java tutorial contains a matrix that maps ResultSet.getXXXmethods to ANSI SQL types. For each SQL type, the matrix shows:

• Which getXXX methods can be used to retrieve the SQL type• Which getXXX method is recommended to retrieve the SQL type

Page 537: Java Programming

Oracle10g: Java Programming 16-27

ANSI SQL Type Java Type ResultSet MethodCHAR, VARCHAR2 java.lang.String getString()LONGVARCHAR java.io.InputStream getAsciiStream()NUMERIC,DECIMAL java.math.BigDecimal getBigDecimal()BIT boolean getBoolean()TINYINT byte getByte()SMALLINT short getShort()INTEGER int getInt()BIGINT long getLong()REAL float getFloat()DOUBLE,FLOAT double getDouble()BINARY,VARBINARY byte[] getBytes()LONGVARBINARY java.io.InputStream getBinaryStream()DATE java.sql.Date getDate()TIME java.sql.Time getTime()TIMESTAMP java.sql.Timestamp getTimestamp()

ORACLE SQL Type Oracle Type Type Extension NUMBER Oracle.Types.NUMBER oracle.sql.NUMBER CHAR Oracle.Types.CHAR oracle.sql.CHAR RAW Oracle.Types.RAW oracle.sql.RAW DATE Oracle.Types.DATE oracle.sql.DATE ROWID Oracle.Types.ROWID oracle.sql.ROWID BLOB Oracle.Types.BLOB oracle.sql.BLOB CLOB Oracle.Types.CLOB oracle.sql.CLOB BFILE n/a oracle.sql.BFILE Structured object Oracle.Types.STRUCT oracle.sql.STRUCT Object reference Oracle.Types.REF oracle.sql.REF Collection(array) Oracle.Types.ARRAY oracle.sql.ARRAY

Mapping Database Types to Java Types (continued)Table of ANSI SQL Types and Java TypesThe following table lists the ANSI SQL types, the corresponding data type to use in Java, and the name of the method to call in ResultSet to obtain that type of column value:

Table of Oracle SQL Types

Page 538: Java Programming

Oracle10g: Java Programming 16-28

16-28 Copyright © 2004, Oracle. All rights reserved.

1. Create an empty statement object:

2. Use execute to execute the statement:

3. Process the statement accordingly:

boolean isQuery = stmt.execute(SQLstatement);

if (isQuery) { // was a query - process resultsResultSet r = stmt.getResultSet(); ...

}else { // was an update or DDL - process resultint count = stmt.getUpdateCount(); ...

}

Handling an Unknown SQL Statement

Statement stmt = conn.createStatement();

Dynamically Executing an Unknown SQL StatementAn application may not know whether a given statement returns a result set until the statement has been executed. In addition, some stored procedures may return several different result sets and update counts.JDBC provides a mechanism so that an application can execute a statement and then process an arbitrary collection of result sets and update counts. The mechanism is based on the use of a general execute() method and then calls to three other methods: getResultSet, getUpdateCount, and getMoreResults. These methods enable an application to explore the statement results one at a time and determine whether a given result is a result set or an update count.execute() returns true if the result of the statement is a result set; it returns false if the result of the statement is an update count. You can then call either getResultSet()or getUpdateCount() on the statement.The following example uses execute() to dynamically execute an unknown statement:

public void executeStmt (String statement) throws SQLException {Statement stmt = conn.createStatement(); // Execute the statementboolean isQuery = stmt.execute(statement);

if (isQuery ) { <statement was a query; process the results>... }

else { <statement was an update or DDL>int updateCount = stmt.getUpdateCount(); // Process the results

... }

Page 539: Java Programming

Oracle10g: Java Programming 16-29

16-29 Copyright © 2004, Oracle. All rights reserved.

• SQL statements can throw a java.sql.SQLException.

• Use standard Java error handling methods.

Handling Exceptions

try {rset = stmt.executeQuery("SELECT empno, ename FROM emp");} catch (java.sql.SQLException e) { ... /* handle SQL errors */ }

...finally { // clean uptry { if (rset != null) rset.close(); }

catch (Exception e) { ... /* handle closing errors */ }

...

Handling ExceptionsYou can use the try-catch-finally block structure for closing resources.Code ExampleConnection conn = null; Statement stmt = null;ResultSet rset = null; // initializestmt = conn.createStatement();try {rset = stmt.executeQuery("SELECT empno, ename FROM emp");

} catch (java.sql.SQLException e)

{ ... /* handle errors */ }...// Clean up resourcesfinally {try { if (rset != null) rset.close(); } catch (Exception e) {}try { if (stmt != null) stmt.close(); } catch (Exception e) {}try { if (conn != null) conn.close(); } catch (Exception e) {}

}

Page 540: Java Programming

Oracle10g: Java Programming 16-30

16-30 Copyright © 2004, Oracle. All rights reserved.

Managing Transactions

• By default, connections are in autocommit mode.• Use conn.setAutoCommit(false)to turn

autocommit off.• To control transactions when you are not in

autocommit mode, use:– conn.commit(): Commit a transaction– conn.rollback(): Roll back a transaction

• Closing a connection commits the transaction even with the autocommit off option.

Transactions with JDBCAfter you perform an UPDATE or INSERT operation in a result set, you propagate the changes to the database in a separate step that you can skip if you want to cancel the changes.With JDBC, database transactions are managed by the Connection object. When you create a Connection object, it is in autocommit mode (which means that each statement is committed after it is executed).You can change the connection’s autocommit mode at any time by calling setAutoCommit(). The following is a full description of autocommit mode:

• If a connection is in autocommit mode, all its SQL statements are executed and committed as individual transactions.

• If a statement returns a result set, the statement finishes when the last row of the result set has been retrieved or the result set has been closed.

• If autocommit mode has been disabled, its SQL statements are grouped into transactions, which must be terminated by calling either commit() or rollback(). The commit() method makes permanent all changes because the previous commit or rollback releases any database locks held by the connection.

• rollback() drops all changes because the previous commit or rollback releases any database locks. commit() and rollback() must be called only when you are not in autocommit mode.

Note: The server-side driver does not support autocommit mode. You must control transactions explicitly.

Page 541: Java Programming

Oracle10g: Java Programming 16-31

16-31 Copyright © 2004, Oracle. All rights reserved.

The PreparedStatement Object

• A PreparedStatement prevents reparsing of SQL statements.

• Use this object for statements that you want to execute more than once.

• A PreparedStatement can contain variables that you supply each time you execute the statement.

PreparedStatement

PreparedStatement is inherited from Statement; the difference is that PreparedStatement holds precompiled SQL statements.If you execute a Statement object many times, its SQL statement is compiled each time. PreparedStatement is more efficient because its SQL statement is compiled only once, when you first prepare PreparedStatement. After that, each time you execute the SQL statement in PreparedStatement, the SQL statement does not have to be recompiled.Therefore, if you need to execute the same SQL statement several times in an application, it is more efficient to use PreparedStatement than Statement.PreparedStatement ParametersPreparedStatement does not have to execute exactly the same query each time. You can specify parameters in the PreparedStatement SQL string and supply the actual values for these parameters when the statement is executed.The next slide shows how to supply parameters and execute a prepared statement.

Page 542: Java Programming

Oracle10g: Java Programming 16-32

16-32 Copyright © 2004, Oracle. All rights reserved.

PreparedStatement pstmt =conn.prepareStatement

("UPDATE emp SET ename = ? WHERE empno = ?");

PreparedStatement pstmt =conn.prepareStatement

("SELECT ename FROM emp WHERE empno = ?");

How to Create a PreparedStatement

1. Register the driver and create the database connection.

2. Create the PreparedStatement, identifying variables with a question mark (?):

Creating a PreparedStatementTo write changes to the database, such as for INSERT or UPDATE operations, you typically create a PreparedStatement object. You can use the PreparedStatement object to execute a statement with varying sets of input parameters. The prepareStatement()method of your JDBC Connection object allows you to define a statement that takes bind variable parameters, and returns a JDBC PreparedStatement object with your statement definition.

Page 543: Java Programming

Oracle10g: Java Programming 16-33

16-33 Copyright © 2004, Oracle. All rights reserved.

1. Supply values for the variables:

2. Execute the statement:pstmt.setXXX(index, value);

pstmt.executeQuery();

pstmt.executeUpdate();

int empNo = 3521;PreparedStatement pstmt =conn.prepareStatement("UPDATE empSET ename = ? WHERE empno = ? ");

pstmt.setString(1, "DURAND");pstmt.setInt(2, empNo);pstmt.executeUpdate();

How to Execute a PreparedStatement

Specifying Values for the Bind VariablesYou use the PreparedStatement.setXXX() methods to supply values for the variables in a prepared statement. There is one setXXX() method for each Java type: setString(), setInt(), and so on. You must use the setXXX() method that is compatible with the SQL type of the variable. In the example in the slide, the first variable is updating a VARCHAR column, and so you must use setString() to supply a value for the variable. You can use setObject()with any variable type. Each variable has an index. The index of the first variable in the prepared statement is 1, the index of the second variable is 2, and so on. If there is only one variable, its index is 1. The index of a variable is passed to the setXXX() method.Closing a PreparedStatementA PreparedStatement is not cached. If you close it, you will have to start again.

Page 544: Java Programming

Oracle10g: Java Programming 16-34

16-34 Copyright © 2004, Oracle. All rights reserved.

Maximize Database Access

• Use connection pooling to minimize the operation costs of creating and closing sessions.

• Use explicit data source declaration for physical reference to the database.

• Use the getConnection() method to obtain a logical connection instance.

Connection Pooling PresentationA connection pool is a cache of database connections. It is maintained in memory, which enables the connections to be reused. This technique is important for increasing performance, especially when the JDBC API is used in a middle-tier environment.Connection pooling does not affect application code. The application simply accesses a JDBC data source and uses it in the standard way. The data source implements connection pooling transparently to the application by using the PooledConnection and ConnectionPoolDataSource facilities provided by the JDBC 2.0 driver.

Page 545: Java Programming

Oracle10g: Java Programming 16-35

16-35 Copyright © 2004, Oracle. All rights reserved.

Database

Database commands

Data source

ConnectionPoolDataSource

Java servlet

Middle-tier server code

Middle tier

Connection Pooling

JDBCdriver

Connection Pooling Presentation (continued)When using pooled connections, you must perform the following two steps:

• Use a DataSource object rather than the DriverManager class to get a connection. The DataSource object is implemented and deployed so that it will create pooled connections.

• Use a finally statement to close a pooled connection. The following finallystatement appears after the try and catch blocks that apply to the code in which the pooled connection is used:try { Connection con = ds.getConnection("Login","Password");// ... code to use the pooled connection con}

catch (Exception ex { // . . . code to handle exceptions

}

finally {if(con != null) con.close();}

Note: Connection pooling is supported in both JDK1.1 and JDK 1.2 OCI and thin drivers. Connection pooling is not supported for the server driver because the server driver can have only one connection, which is to the logged-in session in which it is running.

Page 546: Java Programming

Oracle10g: Java Programming 16-36

Connection Pooling Presentation (continued)A Simple Pooled Connection Sampleimport java.sql.*;

import javax.sql.*;

import oracle.jdbc.*;

import oracle.jdbc.pool.*;

class PooledConnection1

{

public static void main (String args [])

throws SQLException

{

// Create a OracleConnectionPoolDataSource instance

OracleConnectionPoolDataSource ocpds =

new OracleConnectionPoolDataSource();

String url = "jdbc:oracle:oci8:@";

try {

String url1 = System.getProperty("JDBC_URL");

if (url1 != null)

url = url1;

} catch (Exception e) {

// If there is any security exception,

// ignore it and use the default

}

Page 547: Java Programming

Oracle10g: Java Programming 16-37

Connection Pooling Presentation (continued)A Simple Pooled Connection Sample (continued)

// Set connection parameters

ocpds.setURL(url);

ocpds.setUser("scott");

ocpds.setPassword("tiger");

// Create a pooled connection

PooledConnection pc = ocpds.getPooledConnection();

// Get a Logical connection

Connection conn = pc.getConnection();

// Create a Statement

Statement stmt = conn.createStatement ();

// Select the ENAME column from the EMP table

ResultSet rset = stmt.executeQuery ("select ENAME from EMP");

// Iterate through the result and print the employee names

while (rset.next ())

System.out.println (rset.getString (1));

// Close the ResultSet

rset.close();

rset = null;

// Close the Statement, logical connection, and pooled connection

stmt.close();

stmt = null;

conn.close();

conn = null;

pc.close();

pc = null;

}

}

Page 548: Java Programming

Oracle10g: Java Programming 16-38

16-38 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned the following:• JDBC provides database connectivity for various

Java constructs, including servlets and client applications.

• JDBC is a standard Java interface and part of the J2SE.

• The steps for using SQL statements in Java are Register, Connect, Submit, and Close.

• SQL statements can throw exceptions.• You can control default transactions behavior.

Page 549: Java Programming

Oracle10g: Java Programming 16-39

16-39 Copyright © 2004, Oracle. All rights reserved.

Practice 16: Overview

This practice covers:• Setting up the Java environment for JDBC• Adding JDBC components to query the database• Populating the OrderEntryFrame with Customers

from the database

Practice 16: OverviewNote: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les15 directory, load the OrderEntryWorkspaceLes15 workspace, and continue with this practice.Viewing the model: To view the course application model up to this practice, load the OrderEntryWorkspaceLes15 workspace. In the Applications – Navigator node, expand the OrderEntryWorkspaceLes15 – OrderEntryProjectLes15 -Application Sources – oe, and double-click the UML Class Diagram1 entry. This diagram displays all the classes created to this point in the course.

Instructor NoteIn the previous practices, the phone number was defined as a String. However, in the database it is stored as a complex object type. A utility, named JPublisher, can be used to convert an object type to a string, so that it can be used in your application. This process is much more detailed than can be covered in this course. So in the JDBC practice, the phone number item will not be populated with any values. For more information about converting object types, please attend the Oracle9i: Access the Database with JDBC and Stored Procedures course.

Page 550: Java Programming

Oracle10g: Java Programming 16-40

Practice 16: Using JDBC to Access the DatabaseGoalThe goal of this practice is to use the course application to interact with the Oracle database. During this practice, you perform query statements to access a database and integrate them into the application.Note: If you have successfully completed the previous practice, then continue using the same directory and files. If the compilation from the previous practice was unsuccessful and you want to move on to this practice, then change to the les15 directory, load the OrderEntryWorkspaceLes15 workspace, and continue with this practice.Your AssignmentIn the DataMan class, you specify the code to connect to the database, to query a single column from a table. Then you modify the OrderEntryFrame class and integrate the rows returned from the database into the GUI interface.Set the Environment to Use JDBC

1. Update the project to include necessary JDBC classes.a. Double-click the OrderEntryProjectLes16, and select the Libraries node.b. In the Available Libraries pane, find and move the Oracle JDBC

library to the Selected Libraries pane. Click OK.Add JDBC Components to Query the Database

2. Modify the DataMan class and provide the connection information.Note: Place the database related code in the try block.

a. Specify the packages to import.import java.sql.*;

b. Find the code section where the ProductMap class variables are being declared. Add a static variable to hold the connection information.private static Connection conn = null;

c. Add the try { in the code block shown here because the exception portion is shown. Also, finish the syntax for the exception section and add the missing start brace. So, the corrected code block would look like:“try{

// Register the Oracle JDBC driverDriverManager.registerDriver(new

oracle.jdbc.OracleDriver()); // Define the connection url (include db conn)String url = "jdbc:oracle:thin:@myhost:1521:SID";// Provide db connection information

conn = DriverManager.getConnection (url, “ora<n>”,”oracle”);//Include an Exception in the catch block}catch (Exception e){

}d. Save and compile the DataMan.java file. Correct any errors.

Page 551: Java Programming

Oracle10g: Java Programming 16-41

Practice 16: Using JDBC to Access the Database (continued)3. Create a method to execute the select statement based on a customer number, and

return the result to a customer object. Remember the method name for later. In this practice, you populate only three of the items from the database. In the previous practices, the phone number was defined as a String. However, in the database, it is stored as a complex object type. A utility, named JPublisher, can be used to convert an object type to a string, so that it can be used in your application. This process is much more detailed than can be covered in this course. So in your JDBC practice, the phone number item will not be populated with any values. For more information about converting object types, please attend the Oracle9i: Access the Database with JDBC and Stored Procedures course.

a. Following the code to connect to the database, create the method to issue the query based on a customer ID.public static Customer selectCustomerById(int id) throws Exception{

Customer customer = null;

Statement stmt = conn.createStatement ();System.out.println("Table Customers query for customer with id: " + id);ResultSet rset = stmt.executeQuery ("SELECT

cust_last_name, nls_territory" + "FROM customers WHERE customer_id = " + id);

b. If a record is returned, populate the customer object.if (rset.next ()){customer = new Customer();customer.setId(id);customer.setName(rset.getString(1));

//holds first columncustomer.setAddress(rset.getString(2));

//holds second columnSystem.out.println("Customer found: " + customer);

// prints all three columns to the command window}

Page 552: Java Programming

Oracle10g: Java Programming 16-42

Practice 16: Using JDBC to Access the Database (continued)c. Otherwise, throw an exception that the customer is not found, close the

statement, and return the customer.else{

throw new NotFoundException("Customer with id " + id + " not found");}rset.close();stmt.close();return customer;

}d. Save and compile the DataMan.java file. Correct any errors."

Populate the OrderEntryFrame with Database Customers4. Modify the OrderEntryFrame to populate the customer with those coming from

the database.a. Open the OrderEntryFrame.java class in the Code Editor, and search for

the findBtn_actionPerformed() method. In this method, locate the line of code where the customer object is being set:customer=DataMan.findCustomerById(custId);

Remove this comment line from this line and add a line to populate the customer object from the database method you created in DataMan.java (that is, selectCustomerById()):customer=DataMan.selectCustomerById(custId);

b. In the following catch block, remove the Notfound part of the exception. You want to catch the exception from DataMan if no customer is found.catch (NotFoundException err)

changes tocatch (Exception err)

c. Compile and test the application. Try retrieving records from customer 101, 103, 308, 203, 341, and 999. Did they all return a customer? If not, did you see the exception raised?

Page 553: Java Programming

Copyright © 2004, Oracle. All rights reserved.

Deploying Applications by UsingJava Web Start

Schedule: Timing Topic20 minutes Lecture30 minutes Practice50 minutes Total

Page 554: Java Programming

Oracle10g: Java Programming 17-2

17-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Define the architecture of Java Web Start• Describe the benefits of using Java Web Start• Deploy an application by using Web Start

Lesson AimThis lesson describes how to deploy a Java application by using WebStart. The lesson covers the sequence of steps necessary to create a deployment profile and an application archive. After the application archive has been created and deployed, the lesson describes the role of the Java Network Launching Protocol (JNLP) file and how to create it.

Page 555: Java Programming

Oracle10g: Java Programming 17-3

17-3 Copyright © 2004, Oracle. All rights reserved.

What Is Java Web Start?

• It is an application deployment technology based on the Java 2 platform.

• It launches full-featured applications via any browser on any platform, from anywhere on the Web.

What Is Java Web Start?Java Web Start is a new application deployment technology created by Sun Microsystems, Inc. You can use Java Web Start to launch full-featured applications via any browser on any platform, from anywhere on the Web. After your application is launched and is running, the browser can be closed and your application will continue to run. Because Java Web Start applications are not tied to the Web browser, one benefit is that you can keep your old applications and not have to trade them for a version based on an HTML interface that runs in a Web browser.JDeveloper supports the creation of the XML-based JNLP definition on which the Java Web Start technology is based. By using Java Web Start and the JClient Java Web Start Wizard in JDeveloper, you can set up JClient applications to be maintained on the Web server. However, they are downloaded and run on the client machines.

Instructor NoteRemind the students about JClient from the lesson titled “User Interface Design: Swing Basics Planning the Application Layout.” You can create Java client applications that relys on standard Swing components in your application. The Java client application in JDeveloper is known as a JClient application. When a JClient form has been deployed to a client machine, users can use it to display and manipulate data in the form. This course is not intended to teach about JClient, only to show how to develop Java Applications by using JDeveloper.

Page 556: Java Programming

Oracle10g: Java Programming 17-4

17-4 Copyright © 2004, Oracle. All rights reserved.

Running a Web Start Application

1. Request the application.

2. Launch Web Start on the local machine.

3. Download the application.

4. Launch the application (Draw).

HTTP

HTTP

1 2

3

4

Java Web Start Architecture: OverviewThe Java Web Start software must be installed on your machine before you can launch an application.

1. When you click a download link, the link instructs the browser to invoke Java Web Start. A JNLP file runs the application.

2. Java Web Start technology queries the Web to determine whether all the resources that are needed for the application are already loaded. If they are, and if the most recent version of the application is present, then the application will be launched.

3. The application is launched.If the application is not present on your computer, then Java Web Start automatically downloads all the necessary files from the Web server where the application libraries reside. These files are cached on the client machine so that the application is always ready to be relaunched any time either from an icon on your desktop or from the browser link. The most current version of the application is always presented to you because Java Web Start performs updates as needed.

Page 557: Java Programming

Oracle10g: Java Programming 17-5

17-5 Copyright © 2004, Oracle. All rights reserved.

Advantages of Web Start

• Renders a very responsive and rich user interface• Launches applications from the Start menu on the

desktop• Does not require browser to be running• Allows applications to work offline• Automatically updates applications when invoked

Advantages of Web StartJava Web Start FeaturesWeb Start is as easy to deploy as HTML with the richness of full-featured GUI applications. Applications can be launched using a browser, on any type of platform, from anywhere on an intranet or the Internet. A small, one-time download of the application is required on initial launching. Subsequent access is provided from the local cache and the application launches more quickly. It works like a browser plug-in, similar to RealAudio.Java 2 Platform Supports

• Multiple JREs• Sandboxing• Secure code-signing• Incremental versions• Interaction with the desktop• Offline operation

Page 558: Java Programming

Oracle10g: Java Programming 17-6

17-6 Copyright © 2004, Oracle. All rights reserved.

Examining the JNLP File

The JNLP files defines:• The location of the application resources• Information that appears while the application loads• What the application resources are

Using the JNLP FileJava Web Start technology enables Web deployment by using existing Internet protocols: Applications are launched when a client accesses (typically, by clicking a link in an HTML page) a special launch file with a .jnlp file name extension.The Web Start technology is built on the JNLP API. The JNLP API provides services that enable applications to obtain information not normally available using the Java 2, Standard Edition (J2SE) platform API. These services include accessing the system clipboard, controlling resource caching, importing files from a local disk, and so on.The task of packaging for deployment is where the JNLP comes into play. In addition to a JAR file for the application classes, JNLP requires that you create a descriptor file on how to start up the application.JNLP also requires that you provide the location of the application resources, what information must be displayed in the window that appears while the application loads, and what the application resources are.

Page 559: Java Programming

Oracle10g: Java Programming 17-7

17-7 Copyright © 2004, Oracle. All rights reserved.

Deploying Applications with JDeveloper

The JDeveloper Deployment Profile Wizard:• Detects interclass dependencies• Creates .ear, .war, .jar, or .zip files• Enables you to have control over other files added

to the deployed archive• Enables you to save deployment profile settings in

project files:– To simplify redeployment when code changes– That can be automatically updated with new classes

as they are added to the project

Deploying Applications with JDeveloperOracle JDeveloper provides a deployment wizard that helps with most of the tedious tasks associated with deploying your application.The wizard detects classes that are used in your application and proposes them to be included in the archive file it will create for you. It also allows you to specify rules for the inclusion of files into the archive. These rules provide an easy way to control which file types are automatically selected for inclusion.The wizard also provides a dialog box for you to add other files that were not detected by the wizard. The wizard can detect dependencies only between classes recognized at compile time. It does not recognize required resource files, such as image and sound files, or dynamically loaded classes. These files are proposed by the wizard only if they are included in the project.Any settings you choose or set with the deployment wizard are maintained in profiles and are accessible any time you run the wizard.It is a good idea to rebuild the project before deploying your application.

Page 560: Java Programming

Oracle10g: Java Programming 17-8

17-8 Copyright © 2004, Oracle. All rights reserved.

Creating the Deployment Profile File

Select File > New

Running the Deployment WizardYou run a deployment wizard by selecting a project, then File > New, and thenselecting the Deployment Profiles category. To create a deployment profile for your application from the Items list, select either one of the following:

• JAR File: Simple Archive• WAR File: J2EE Web Module

If JDeveloper generated an existing profile during the creation of the application HTML file, then the above actions are not required. The deployment profile generated during the application HTML file is a WAR file profile.Other Types of Deployment

• JAR File: Deploys applications and JavaBeans. • Stored Procedures to Oracle: Deploys stored procedures to an Oracle database • J2EE: Deploys an Enterprise JavaBean to an Oracle database • J2EE: Client Module: Creates a deployment profile containing Java application in a JAR

file XML descriptor file• Business Components: Creates an EJB, Common Object Request Broker Architecture

(CORBA), or Archive profile

Page 561: Java Programming

Oracle10g: Java Programming 17-9

17-9 Copyright © 2004, Oracle. All rights reserved.

Saving the Deployment Profile

Select a destination and name for the deployment profile.

Deployment Profile Wizard: Staging AreaOn the Save Deployment Profile page of the Deployment Profile Wizard, you define the destination on your local machine for staging the development file and the name of the deployment profile file. When you invoke a deployment profile, the first window displayed contains the following:

• Location: For selecting the directory used as the destination for deployment. Enter a path on your local machine for staging all the files associated with your project.

• File name: For saving the deployment profile settingsClick the Save button to save the settings selected in your project.

Page 562: Java Programming

Oracle10g: Java Programming 17-10

17-10 Copyright © 2004, Oracle. All rights reserved.

Selecting Files to Deploy

Select the file types to include. Other settings differ for other deployment profile types.

Project Files to DeployYou can include any file from your project in the archive, though the .html file you use to run an application must be deployed in the parent directory of the archive file.As a default, the deployment wizard selects all files in your current project for deployment. You can cancel the selection of the files that must not be included by clearing its check box. Select the type of files you want to deploy:

• Compiled output only• Source files only• Both compiled output and source files.

For more control over deployment, click the other pages. The JAR Options page handles additional parameters for the JAR and manifest file. The Dependency Analyzer displays libraries included in your project’s current active configuration. If the Automatically Include Files Added to Project check box is selected, the profile will be updated automatically to include new files as they are added to the project. If you clear this setting, you must manually select the files to be included by editing the profile file.Note: The slide shows the profile settings for creating a JAR File - Simple Archive deployment profile. The number and choices of settings will be different for other types of deployment profiles—for example, WAR File - J2EE Archive requires a Web server context root name.

Page 563: Java Programming

Oracle10g: Java Programming 17-11

17-11 Copyright © 2004, Oracle. All rights reserved.

Making an Executable .jar File

Set the Main Class field to the class name containing a main() method, in JAR Options.

Creating an Executable .jar FileIn settings, click the JAR Options node in the navigation list, and select the Include Manifest File check box. In the Main Class field, enter the fully qualified name, without the .classextension, of the class containing the main() method you invoke when using the java –jarcommand-line option.For exampleIf the generated JAR archive file is called OrderEntry.jar , execute the main application class as follows:java -jar OrderEntry.jar

If you do not enter a name in the Main Class field for the JAR archive, you can still execute any class with a main() method contained in the JAR file from the command line as follows:1. Set the CLASSPATH to include the Java Archive file name java

package.ClassNameOr use the -classpath command-line option as follows:java -classpath {archivefilename}.jar package.ClassName

Page 564: Java Programming

Oracle10g: Java Programming 17-12

17-12 Copyright © 2004, Oracle. All rights reserved.

Creating and Deploying the Archive File

• Right-click the Deployment Profile file.• Select the Deploy to menu option.• The .jar file is created in the directory listed in

the deployment properties.

Deploying the .jar File1. In the System Navigator pane, select Deployment Profile and right-click. 2. Select the Deploy to JAR file menu option to deploy the archive.3. The Java Archive will be placed in the directory listed in the JAR Options, JAR File

properties of the archive.Editing the Profile FileTo edit the simple archive profile setting, select the archive profile, right-click, and select Settings, or double-click the Deployment Profile filename in the Navigator.Deploying an Application or WAR file to Oracle Application ServerIf you need to deploy the application to an application server, such as Oracle AS, you must use the Oracle Connection Manager to form a connection with the application server. The instructor and practices provide you with the instructions on how to accomplish this task.To deploy to the target platform, after the connection name has been created, you right-click the Deployment Profile file and select the menu entry as follows:Deploy To Java Archive (JAR) File

Page 565: Java Programming

Oracle10g: Java Programming 17-13

17-13 Copyright © 2004, Oracle. All rights reserved.

Using JDeveloper to Deploy an Applicationto Java Web Start

Step 1: Generate deployment profiles and archive the application. Step 2: Start OC4J and create a connection.Step 3: Use Web Start Wizard to create JNLP file.Step 4: Archive and deploy your application to OC4J server.

How to Deploy a Java Web Application to Java Web StartYou can use JDeveloper’s simple J2EE Web deployment process to set up the Web server before downloading and running the application by using Java Web Start. The process of deploying is similar whether you intend to deploy to the JDeveloper-embedded OC4J server or a production OC4J Web server.First, you create a deployment archive of your Java application by using a deployment wizard. The result is the creation of a .jar file that contains all your application files.Second, you must install and start the application server that is used to deliver the application. If you use the OC4J server that comes with JDeveloper, this task is done from the command line.Third, use the wizard in JDeveloper to create JNLP. You may want to store all the deployment files (HTML, JNLP, XML) in a different JDeveloper project. Finally, create a J2EE Web deployment file containing deployment-specific information and the appropriate deployment descriptor.

Page 566: Java Programming

Oracle10g: Java Programming 17-14

17-14 Copyright © 2004, Oracle. All rights reserved.

Step 1: Generate Deployment Profiles and Archive Application

Package all the Java application files into a simple .jar archive.

Step 1: Generate Deployment Profiles and Archive ApplicationJDeveloper has various deployment modes for different applications. However, you may want to quickly and simply deploy your application as a JAR or ZIP file to your file system.A J2EE Client module is packaged as a client JAR file, which contains one or more Java application components and a client deployment descriptor file named application-client.xml. You can make your simple archive or J2EE Client module into an executable JAR file that you can launch with the java -jar OrderEntry.jar command.After you have created the deployment profile containing the Java application components and the deployment descriptor file, and have packaged them into a standard J2EE archive, you can proceed to deploy the client JAR to the application server.

Page 567: Java Programming

Oracle10g: Java Programming 17-15

17-15 Copyright © 2004, Oracle. All rights reserved.

Step 2a: Start OC4J

Use the command line to start the server.

Step 2a: Start OC4JOracle JDeveloper is packaged with OC4J Release 9.0.5.1 and is the default application server when running, debugging, profiling, and Code Coaching application code directly in JDeveloper’s embedded OC4J server.You can also use the OC4J server outside of JDeveloper, as a stand-alone application server for delivering your Java application.Before you can use OC4J, it must be installed. Installation and running the stand-alone OC4J server is accomplished outside of JDeveloper, from the command-line interface.

Page 568: Java Programming

Oracle10g: Java Programming 17-16

17-16 Copyright © 2004, Oracle. All rights reserved.

Step 2b: Creating a Connection

Use the Connection Wizard to create a connection to the application server. You must specify:• The type of connection (OC4J)• The username and password for authentication• Local URL, target Web site, and local directory for

OC4J

Using the Connection WizardThe Connection Wizard guides you through the process of specifying all the appropriate information to create and test a connection. Select a connection type. The type you select determines the fields displayed on the subsequent Connection Wizard pages. Select Standalone OC4J to create a connection to a stand-alone OC4J instance (Oracle AS Containers for J2EE) that is not running within an Oracle AS machine.Use this Connection page to configure the stand-alone Oracle AS Containers for Java 2 Enterprise Edition (OC4J) connection. You will be prompted to enter the URL for the OC4J transport protocol, also known as Orion Remote Method Invocation (ORMI). ORMI is a custom wire protocol for Java Remote Method Invocation (RMI) and is used transparently by RMI.Remote Method Invocation (RMI) enables a programmer to create distributed Java to Java applications, in which the methods of remote Java objects can be invoked from other Java Virtual Machines, even on different hosts. A client can call a remote object in a server, and that server can also be a client of other remote objects. RMI uses object serialization to monitor and control parameters and supports true object-oriented polymorphism.

Page 569: Java Programming

Oracle10g: Java Programming 17-17

17-17 Copyright © 2004, Oracle. All rights reserved.

Step 3: Use Web Start Wizard to Create a JNLP File

• Specify the Web Start name, application archive (.jar), and main application class.

• Include information to be displayed to the user while downloading (for example, application title, vendor, and brief description)

Step 3: Use Web Start Wizard to Create a JNLP fileYou use the Java Web Start Wizard to create an XML-based JNLP definition, which the Java Web Start software uses to download and run the application on the client machine.This wizard creates the complete JNLP file and an optional HTML file to launch your Web Start application.

Page 570: Java Programming

Oracle10g: Java Programming 17-18

17-18 Copyright © 2004, Oracle. All rights reserved.

Step 4: Archive and Deploy the Application to the OC4J Server

• Specify properties of the Web components and deployment description.

• Deploy to the OC4J connection created in step 2.• Run the generated HTML file.

Step 4: Archive and Deploy the Application to the OC4J ServerA J2EE Web module is packaged as a Web Archive (WAR) file which contains one or more Web components (servlets, JSPs) as well as the standard J2EE Web deployment descriptor, web.xml, and the OC4J-specific deployment descriptor, webapp.xml.After you have created the deployment profile containing the Web components and the appropriate deployment descriptor files, you can deploy it as a WAR or a standard J2EE Enterprise Archive (EAR) file. JDeveloper takes the resulting EAR and deploys it to the target application server.

Page 571: Java Programming

Oracle10g: Java Programming 17-19

17-19 Copyright © 2004, Oracle. All rights reserved.

Summary

In this module, you should have learned how to:• Describe how a Java Web Start application runs• Describe the benefits of using Java Web Start• Use JDeveloper to deploy an application by using

Web Start

Page 572: Java Programming

Oracle10g: Java Programming 17-20

17-20 Copyright © 2004, Oracle. All rights reserved.

Practice 17: Overview

This practice covers the following topics:• Archiving your Java application• Creating a new project to hold the Web Start files

and setting the OC4J server preference• Installing and starting the stand-alone OC4J

application server• Creating an application server connection in

JDeveloper• Archiving and deploying the application files to

OC4J, and testing the application

Practice 17: OverviewNote: To complete this practice, you must navigate to the OrderEntryWS directory and load the OrderEntryWorkspaceWS workspace. Do not continue with the workspace you were using for the previous practice. Viewing the model: To view the course application model up to this practice, load the OrderEntryWorkspaceLes16 workspace. In the Applications – Navigator node, expand the OrderEntryWorkspaceLes16 – OrderEntryProjectLes16 -Application Sources – oe, and double-click the UML Class Diagram1 entry. This diagram displays all the classes created to this point in the course.

Instructor NoteThis practice uses the Java application solution from the lesson titled “Adding User Interface Components and Event Handling.” Make sure the students switch over the OrderEntryWSworkspace. The reason for using this workspace is that this application does not include JDBC and is much simpler and more likely to deploy successfully. There are a few extra required steps to deploy an application that uses JDBC, which require more detail than needed in this course.

Page 573: Java Programming

Oracle10g: Java Programming 17-21

Practice 17: Deploying an Application to Java Web StartGoalIn this practice, you learn to deploy your Java application to OC4J server, using Java Web Start.Note: To complete this practice, you must navigate to the OrderEntryWS directory and load up the E:\labs\OrderEntryWS\OrderEntryWorkspaceWS.jws workspace. Do not continue with the workspace you were using for the practice for lesson 16 on JDBC.Your AssignmentThe company has standardized to deploy Java applications so that they may be run from a browser or as a stand-alone application from the desktop. In this practice, you will:

• Archive your Java application and create a new project to hold the Web Start files• Install and start the stand-alone OC4J application server and create an application server

connection in JDeveloper• Create the JNLP Web Start file• Archive and deploy the Web Start and application files to OC4J• Run the application from a browser and the desktop

Archive Your Java Application1. Use the JDeveloper deployment wizard to create a simple JAR archive for

deployment. With the OrderEntryProjectWS project selected, invoke the gallery and navigate to the General - Deployment Profiles node.

a. Select JAR file and click OK. Accept the default filename (archive1) and click OK.b. In the Jar Deployment Profile Properties pane, expand the File Groups, Projects

Output, Filters node and ensure all the files are selected, press OK.c. In the Navigator pane a new deployment profile object will be listed within your

project, named archive1.deploy. Select the file, right-click and select Deploy to JAR File. Make sure there are no errors and the deployment is successful.

Create a New Project to Hold the Web Start Files and Set the OC4J Server Preference2. To keep deployment files separate from application files, create a second project in

the workspace to hold your Web Start deployment files.a. With the OrderEntryProjectWS workspace selected, invoke the gallery and

navigate to the General node. Select Empty Project and click OK. Accept the default values and click OK. Double-click the project, and ensure J2EE is available in the Selected Libraries.

b. In the Tools menu select the Embedded OC4J Server Preferences option nder the lobal

tartup node in the middle of thewindow select the pecific ost Name radio buttonand enter localhost in the field

c lick

Page 574: Java Programming

Oracle10g: Java Programming 17-22

Practice 17: Deploying an Application to Java Web Start (continued)Install and Start the Stand-Alone OC4J Application Server

3. To run the application outside JDeveloper, you must install and start the external OC4J server.

a. Open a DOS window and change the directory to the OC4J home. This isin the E:\jdev9051\j2ee\home subdirectory relative to the JDeveloper home (ask your instructor for the specific details).

b. Start the stand-alone OC4J application server by entering the following command in the DOS window:

java –jar oc4j.jar

(The command depends on the DOS Path environment variable being set to use the Java JDK and run-time environment. The Path environment must include something like D:\jdev\jdk\jre\bin).Note: If this command prompts you for an administrator password as follows:Enter an admin password to use:Click Enter to accept and use the default. The default password is welcome. Remember the password; you will need it while creating a Connection.Important: When OC4J starts, text similar to the following should be displayed:Oracle Application Server Containers for J2EE 10g(9.0.4.0.0) initialized.Do not close the DOS window. Later, you start another DOS window andenter a command to gracefully shut down the OC4J server.

Create an Application Server Connection in JDeveloper4. To deploy the application to the OC4J server, you must create a connection in

JDeveloper.a. In the Navigator, select the Connections tab, then right-click the Application Server

node, and select the New Application Server Connection option.b. Click Next in the Welcome page of the Connection Wizard. In Step 1 of 4: Type

page, enter the connection name OC4J, leaving the Connection Type at its default (Standalone OC4J). Click Next.

c. In the Step 2 of 4: Authentication page, enter welcome in the Password field, leaving the Username at its default (admin). Do not select the Deploy Password check box. Click Next.

d. In the Step 3 of 4: Connection page, accept the default values and click Next.e. In the Step 4 of 4: Test page, click the Test Connection button, and verify whether

you can successfully connect to the running OC4J application server. Correct any problems, asking the instructor for help, if necessary.Note: If you were successful in making a connection, the area below the Test Connection button should display the text: Success!

f. Click Finish, to complete this step.

Page 575: Java Programming

Oracle10g: Java Programming 17-23

Practice 17: Deploying an Application to Java Web Start (continued)Create the JNLP Web Start File

5. To run an application using Web Start, you need a JNLP file.a. First, be sure that your new project (Project1.jpr) is currently selected in

Applications Navigator.b. Then, invoke the New gallery (Select File > New). Expand the Client Tier node and

select Swing/AWT. In the Items list, select the Java Web Start (JNLP) File and click OK.

c. In the first page of the wizard, set the properties to the following values and then click Next.

Name: The name of the JNLP file (OrderEntryWS)JAR File: Click the Browse button to locate the .jar file that you created in Step 1 of this practice (..\deploy\archive1.jar).Main Class: The Java class used to start the application (oe.OrderEntry)Create Homepage: SelectedAllow Offline Usage: SelectedAllow All Permissions: Not selected

d. In the second page of the wizard, populate the properties with appropriate values of your choosing. These are displayed while the application is being downloaded by Web Start. After these properties are populated, click Finish.

e. Three files are created using this wizard: A .html file to launch the application, a .jnlp file containing all the Web Start information, and a web.xml file.

f. Double-click the the newly created JNLP file and change the URL in the second line to http://localhost:8888. This is the location where the OC4J server is running and the JNLP must be modified appropriately.

g. Ensure that the J2SE version is set to 1.4:<j2se version="1.4+"/>.

h. Save all the files.Deploy the Application to the OC4J Connection

6. Create the deployment profile for your WebStart project and deploy it.a. First, be sure that your new project (Project1.jpr) is currently selected in

JDeveloper.b. Then, invoke the New gallery (Select File > New). Expand the General node and

select the Deployment Profiles node.c. Select the WAR File item and click OK. Accept the file location and name

(webapp1), and click OK.d. The WAR Deployment Profile Settings pane appears. The default settings are

appropriate for the purposes of this practice. Click OK to continue.e. In the Navigator, select the newly created deployment file (that is,

webapp1.deploy) and right-click. Select the “Deploy to” option and choose the connection you created earlier (OC4J).

Page 576: Java Programming

Oracle10g: Java Programming 17-24

Practice 17: Deploying an Application to Java Web Start (continued)Test the application

7. Run the application in the browser and from the desktop.a. In the Deployment window, copy the test URL that is displayed. Open an instance of

Internet Explorer and paste the URL in the address field. Following the last character in the URL, add the name of the HTML page and run it. It should look like the following (ensure that the Workspace – Project and HTML file names match yours):

http://machine-name:8888/OrderEntryWorkspaceLesWS-Project1-context-root/OrderEntryWS.html

b. In the browser, click the “Click here to start your Web Start Application” link.c. A message pane with your application title asks you if you want an icon placed on

your desktop. Select Yes, and test the application.d. Find Customer where Customer Id is equal to 2 and then 4.e. Close the application and run the application from the desktop.