312
Sun Educational Services Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language SL-110

SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

  • Upload
    lekhanh

  • View
    229

  • Download
    2

Embed Size (px)

Citation preview

Page 1: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language

Fundamentals of the Java™Programming Language

SL-110

Page 2: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Copyright 2002 Sun Microsystems, Inc., 901 San Antonio Road, Palo Alto, California 94303, U.S.A. All rights reserved.

This product or document is protected by copyright and distributed under licenses restricting its use, copying, distribution, and decompilation. No part of this product or document maybe reproduced in any form by any means without prior written authorization of Sun and its licensors, if any.

Third-party software, including font technology, is copyrighted and licensed from Sun suppliers.

Sun, Sun Microsystems, the Sun Logo, Java, Java 2 Platform, Standard Edition, and J2SE are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.

All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. in the U.S. and other countries. Products bearing SPARCtrademarks are based upon an architecture developed by Sun Microsystems, Inc.

U.S. Government approval might be required when exporting the product.

RESTRICTED RIGHTS: Use, duplication, or disclosure by the U.S. Government is subject to restrictions of FAR 52.227-14(g)(2)(6/87) and FAR 52.227-19(6/87), or DFAR 252.227-7015(b)(6/95) and DFAR 227.7202-3(a).

DOCUMENTATION IS PROVIDED “AS IS” AND ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS, AND WARRANTIES, INCLUDING ANY IMPLIED WARRANTYOF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE DISCLAIMED, EXCEPT TO THE EXTENT THAT SUCH DISCLAIMERS AREHELD TO BE LEGALLY INVALID.

.THIS MANUAL IS DESIGNED TO SUPPORT AN INSTRUCTOR-LED TRAINING (ILT) COURSE AND ISINTENDED TO BE USED FOR REFERENCE PURPOSES IN CONJUNCTION WITH THE ILT COURSE. THEMANUAL IS NOT A STANDALONE TRAINING TOOL. USE OF THE MANUAL FOR SELF-STUDY WITHOUTCLASS ATTENDANCE IS NOT RECOMMENDED.

Page 3: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Copyright 2002 Sun Microsystems Inc., 901 San Antonio Road, Palo Alto, California 94303, Etats-Unis. Tous droits réservés.

Ce produit ou document est protégé par un copyright et distribué avec des licences qui en restreignent l’utilisation, la copie, la distribution, et la décompilation. Aucune partie de ceproduit ou document ne peut être reproduite sous aucune forme, par quelque moyen que ce soit, sans l’autorisation préalable et écrite de Sun et de ses bailleurs de licence, s’il y en a.

Le logiciel détenu par des tiers, et qui comprend la technologie relative aux polices de caractères, est protégé par un copyright et licencié par des fournisseurs de Sun.

Sun, Sun Microsystems, le logo Sun, Java 2 Platform, Standard Edition, et J2SE sont des marques de fabrique ou des marques déposées de Sun Microsystems, Inc. aux Etats-Unis et dansd’autres pays.

Toutes les marques SPARC sont utilisées sous licence sont des marques de fabrique ou des marques déposées de SPARC International, Inc. aux Etats-Unis et dans d’autres pays. Lesproduits portant les marques SPARC sont basés sur une architecture développée par Sun Microsystems, Inc.

L’accord du gouvernement américain est requis avant l’exportation du produit.

LA DOCUMENTATION EST FOURNIE “EN L’ETAT” ET TOUTES AUTRES CONDITIONS, DECLARATIONS ET GARANTIES EXPRESSES OU TACITES SONT FORMELLEMENTEXCLUES, DANS LA MESURE AUTORISEE PAR LA LOI APPLICABLE, Y COMPRIS NOTAMMENT TOUTE GARANTIE IMPLICITE RELATIVE A LA QUALITE MARCHANDE, AL’APTITUDE A UNE UTILISATION PARTICULIERE OU A L’ABSENCE DE CONTREFAÇON.

CE MANUEL DE RÉFÉRENCE DOIT ÊTRE UTILISÉ DANS LE CADRE D’UN COURS DE FORMATION DIRIGÉ PARUN INSTRUCTEUR (ILT). IL NE S’AGIT PAS D’UN OUTIL DE FORMATION INDÉPENDANT. NOUS VOUSDÉCONSEILLONS DE L’UTILISER DANS LE CADRE D’UNE AUTO-FORMATION.

Page 4: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language

About This Course

Page 5: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language About This Course, v of xivCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Course Goals

Upon completion of this course, you should be able to:

• Demonstrate knowledge of Java™ technology, the Javaprogramming language, and the product life cycle

• Use various Java programming language constructs tocreate several Java technology applications

• Use decision and looping constructs, and methods, todictate program flow

• Implement intermediate Java technologyprogramming and object-oriented (OO) concepts inJava technology programs

Page 6: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language About This Course, vi of xivCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Course Map

Introducing Java Technology Programming

Explaining Java Technology Programming Fundamentals

Declaring,

Using Operators Using Loop

Dictating Program Flow

Describing Intermediate Java Technology and OO Concepts

Implementing Implementing

Creating and

and

Creating and UsingEncapsulation and

Developing andTesting a Java

Developing and

Constructors

Analyzing a Problemand Designing

a Solution Technology Program

Initializing, andUsing Variables Using Objects

Decision Constructs Constructs Using Methods

Arrays Inheritance

Explaining Java™Technology

Page 7: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language About This Course, vii of xivCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Topics Not Covered

• Advanced Java technology programming – Covered inSL-275: Java™ Programming Language

• Advanced OO analysis and design – Covered inOO-226: Object-Oriented Application Analysis and Designfor Java™ Technology (UML)

• Applet programming or Web page design

Page 8: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language About This Course, viii of xivCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

How Prepared Are You?

To be sure you are prepared to take this course, can youanswer yes to the following questions?

• Can you create programs using a procedural languagesuch as C or a scripting language such as Perl?

• Can you create and edit text files using a text editor?

• Can you use a World Wide Web (WWW) browser?

• Can you solve logic problems?

Page 9: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language About This Course, ix of xivCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Introductions

• Name

• Company affiliation

• Title, function, and job responsibility

• Experience related to topics presented in this course

• Reasons for enrolling in this course

• Expectations for this course

Page 10: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language About This Course, x of xivCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

How to Use the Icons

Demonstration

Discussion

Note

Caution - Electrical

Caution - Heat

?!

Page 11: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language About This Course, xi of xivCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Case Study

Self-Check✓✓

Page 12: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language About This Course, xii of xivCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Typographical Conventions

• Courier is used for the names of commands, files,directories, programming code, programmingconstructs, and on-screen computer output.

• Courier bold is used for characters and numbersthat you type, and for each line of programming codethat is referenced in a textual description.

• Courier italics is used for variables andcommand-line placeholders that are replaced with areal name or value.

• Courier italics bold is used to representvariables whose values are to be entered by the studentas part of an activity.

Page 13: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language About This Course, xiii of xivCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Typographical Conventions

• Palatino italics is used for book titles, new words orterms, or words that are emphasized.

Page 14: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language About This Course, xiv of xivCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Additional Conventions

Java programming language examples use the followingadditional conventions:

• Courier is used for the class names, methods, andkeywords.

• Methods are not followed by parentheses unless aformal or actual parameter list is shown.

• Line breaks occur where there are separations,conjunctions, or white space in the code.

• If a command on the Solaris™ Operating Environment(Solaris OE) is different from the Microsoft Windowsplatform, both commands are shown.

Page 15: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language

Module 1

Explaining Java™ Technology

Page 16: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 2 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Overview

• Objectives:

• Describe key concepts of the Java programminglanguage

• List the three Java technology product groups

• Summarize each of the seven stages in the productlife cycle

• Relevance

Page 17: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 3 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Key Concepts of the Java ProgrammingLanguage

• Object-oriented

• Distributed

• Simple

• Multithreaded

• Secure

• Platform-independent

Page 18: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 4 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Object-Oriented

Step 5

Step 4

Step 3

Step 2

Step 11

2

3

4

5

Page 19: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 5 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Object-Oriented

Object

Object

Object

Object

Object

Object

Page 20: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 6 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Distributed

AppletApplet

Executing

Page 21: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 7 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Simple

• References are used instead of pointers.

• A boolean data type can have a value of either true orfalse.

Page 22: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 8 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Multithreaded

Database

Java Technology Program

Printer Graphical User

Interface

Thread Thread Thread

Page 23: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 9 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Secure

XAppletApplet

Page 24: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 10 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Platform-Dependent Programs

C

Code

Microsoft

Windows

Binary

0101001

Linux

Binary

0001010

Solaris

OE

Binary

0001010Solaris OE

C Compiler

Linux

C Compiler

Microsoft Windows

C Compiler

Page 25: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 11 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Platform-Dependent Programs

Solaris

OE

ExecutableSolaris OE

Linker

Linux

Linker

MicrosoftWindows

Linker

Project

Libraries

Project

Libraries

Project

Libraries

Linux

Microsoft

Windows

Executable

Executable

Microsoft

Windows

Binary

0101001

Linux

Binary

0001010

Solaris

OE

Binary

0001010

Page 26: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 12 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Platform-Dependent Programs

Solaris OE

Workstation

Linux

Workstation

Microsoft Windows

Workstation

Solaris

Linux

Microsoft

Windows

Executable

OE

Executable

Executable

Page 27: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 13 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Platform-Independent Programs

Java

Code

(.javafile)

Java Compiler

Java

Bytecode

(.classfile)

Page 28: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 14 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Platform-Independent

Java

Bytecode

(.classfile)

Linux Workstation

Solaris OE Workstation

Windows Workstation

JRE

JRE

JRE

Page 29: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 15 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Identifying Java Technology ProductGroups

TM

J2EE J2ME

J a v a T e c h n o l o g y P r o d u c t G r o u p s

Enterprise Solutions Desktop Solutions Consumer Solutions

eCommerce

eBusiness

Standalone applications

Applets

Cell phones

PDAs

TV set-top boxes

Car navigation systems

J2SE

Page 30: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 16 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Using the Java™ 2 Platform, StandardEdition SDK Components

• Java runtime environment:

• A Java virtual machine for the platform you choose

• Java class libraries for the platform you choose

• A Java technology compiler

• Java class library (API) documentation (as a separatedownload)

• Additional utilities, such as utilities for creating Javaarchive files (JAR files) and for debugging Javatechnology programs

• Examples of Java technology programs

Page 31: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 17 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The Product Life Cycle (PLC) Stages

1. Analysis

2. Design

3. Development

4. Testing

5. Implementation

6. Maintenance

7. End-of-life (EOL)

Page 32: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 18 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The Analysis Stage

!Major componentsIdea or problem

Page 33: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 19 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The Design Stage

Blueprint

Major Components

Master Blueprint

Component Blueprints

Page 34: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 20 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The Development Stage

Component Blueprints Components

Page 35: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 21 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The Testing Stage

Components

Testing

Page 36: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 22 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The Implementation Stage

Product

Page 37: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 23 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The Maintenance Stage

Improved product

Page 38: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 1, slide 24 of 24Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The EOL Stage

New product

Page 39: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language

Module 2

Analyzing a Problem and Designing aSolution

Page 40: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 2 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Overview

• Objectives:

• Analyze a problem using object-oriented analysis

• Design classes from which objects will be created

• Relevance

Page 41: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 3 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Analyzing a Problem Using Object-OrientedAnalysis

DirectCloth

ing, Inc.

"TheShirt

Company"

Name:

Address:

Phone #:

Email:

Date:

Credit Card #

Expiration

Payment: CheckCredit C

ard

Shirt ID# Size

Color Code

Price

Total Price

Page 42: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 4 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Identifying a Problem Domain

• A problem domain is the scope of the problem you willsolve.

• For example, “Create a system allowing order entrypeople to enter and accept payment for an order.”

Page 43: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 5 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Identifying Objects

• Objects can be physical or conceptual.

• Objects have attributes (characteristics), such as size,name, shape, and so on.

• Objects have operations (the things they can do), such assetting a value, displaying a screen, or increasingspeed.

Page 44: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 6 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Identifying Objects

Attributes

Dorsal fin, small

Color, blue Size, large

Operations

CommunicateMigrate

Eat Dive

Page 45: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 7 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Additional Criteria for Recognizing Objects

• Relevance to the problem domain:

• Does the object exist within the boundaries of theproblem domain?

• Is the object required for the system to fulfill itsresponsibility?

• Is the object required as part of an interactionbetween a user and the system?

• Independent existence

Page 46: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 8 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Possible Objects in the DirectClothingCase Study

Order Shirt Customer

Page 47: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 9 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Identifying Object Attributes and Operations

• Attributes = data, such as:

• ID

• Order object

• Operations = actions, such as:

• Delete item

• Change ID

Page 48: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 10 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Object With Another Object as an Attribute

cust omerIDnameaddr essphone numb eremail addr ess*Or der

assign a cust omer ID

Order

order ID

date

*Shirt(s)

total price

*Form of payment

*CSR

status

calculate order ID

calculate the total price

add shirt to order

remove shirt from order

submit the order

Customer

customer ID

name

address

phone number

email address

*Order

assign a customer ID

Page 49: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 11 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Possible Attributes and Operations in theDirectClothing, Inc. Case Study

CustomerShirtOrderorderID

date

*Shirt(s)

totalPrice

*Form of Payment*Form of Payment

*CSR

status

calculate order IDcalculate order ID

calculate the total pricecalculate the total price

add shirt to orderadd shirt to order

remove shirt from orderremove shirt from order

submit the ordersubmit the order

order ID

date

*Shirt(s)

total price

*Form of payment

*CSR

status

calculate order ID

calculate the total price

add shirt to order

remove shirt from order

submit the order

shirtID

price

description

size

color code

calculate shirt ID

display shirt Information

customer ID

name

address

phone number

email address

*Order

assign a customer ID

Page 50: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 12 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Case Study Solution

Order Shirt

order IDdate*Shirt(s)total price*Form of payment*CSRstatus

shirt IDpricedescriptionsizecolor code

calculate order IDcalculate the total priceadd shirt to orderremove shirt from ordersubmit the order

calculate shirt IDdisplay shirt information

Page 51: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 13 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Case Study Solution

Customer Payment

customer IDnameaddressphone numberemail address*Order

check numbercredit card numberexpiration date

assign a customer ID verify credit card numberverify check payment

Page 52: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 14 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Case Study Solution

Catalog CSR

*Shirt(s) nameextension

add a shirtremove a shirt

Page 53: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 15 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 1: Analyzing a Problem Domain

• Objectives

• Tasks

• Solutions

• Discussion

Page 54: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 16 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Designing Classes

Whale Attributes

Dorsal Fin

Color

Size

Dorsal Fin, large

Dorsal Fin, small

Color, blue

Color, black and white

Size, large

Size, medium

Page 55: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 17 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Class and Resulting Objects

Shirt Class Shirt Objects

Shirt

shirtIDpricedescriptionsizecolorCode R=Red, B=Blue, G=Green

calculateShirtID()displayShirtInformation()

Page 56: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 18 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Modeling Classes

• Syntax

• Example

ClassName

attributevariableName [range of values ]attributevariableName [range of values ]attributevariableName [range of values ]...

methodName()methodName()methodName()...

Shirt

shirtIDpricedescriptionsizecolorCode R=Red, B=Blue, G=Green

calculateShirtID()displayShirtInformation()

Page 57: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 2, slide 19 of 19Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 2: Designing a Solution

• Objectives

• Tasks

• Solutions

• Discussion

Page 58: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language

Module 3

Developing and Testing a JavaTechnology Program

Page 59: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 3, slide 2 of 16Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Overview

• Objectives:

• Identify the four components of a class in the Javaprogramming language

• Use the main method in a test class to run a Javatechnology program from the command line

• Compile and execute a Java technology program

• Relevance

Page 60: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 3, slide 3 of 16Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Identifying the Components of a Class

OrderEntry

Order

Customer

Window

Button

Shirt

Date

Page 61: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 3, slide 4 of 16Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Identifying the Components of a Class

• The class declaration

• Attribute variable declarations and initialization(optional)

• Methods (optional)

• Comments (optional)

Page 62: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 3, slide 5 of 16Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Identifying the Components of a Class

1 public class Shirt {23 public int shirtID = 0; // Default ID for the shirt4 public String description = “-description required-”; // default56 // The color codes are R=Red, B=Blue, G=Green, U=Unset7 public char colorCode = ‘U’;89 public double price = 0.0; // Default price for all shirts1011 public int quantityInStock = 0; // Default quantity for all shirts1213 // This method displays the values for an item14 public void displayShirtInformation() {1516 System.out.println(“Shirt ID: “ + shirtID);17 System.out.println(“Shirt description:” + description);18 System.out.println(“Color Code: “ + colorCode);19 System.out.println(“Shirt price: “ + price);

Page 63: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 3, slide 6 of 16Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

20 System.out.println(“Quantity in stock: “ + quantityInStock);2122 } // end of display method23 } // end of class

Page 64: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 3, slide 7 of 16Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The Class Declaration

• Syntax:[ modifier ] class class_identifier

• Example:public class Shirt

Page 65: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 3, slide 8 of 16Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Variable Declarations and Assignments

public int shirtID = 0;public String description = “-description required-”;public char colorCode = ‘U’;public double price = 0.0;public int quantityInStock = 0;

Page 66: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 3, slide 9 of 16Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Comments

• Single-line:public int shirtID = 0; // Default ID for the shirtpublic double price = 0.0; // Default price for all shirts

// The color codes are R=Red, B=Blue, G=Green

• Traditional:/******************************************** Attribute Variable Declaration Section *********************************************/

Page 67: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 3, slide 10 of 16Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Methods

• Syntax:[ modifiers ] return_type method_identifier ([ arguments ]){

method_code_block}

• Example:public void displayShirtInformation() {

System.out.println("Shirt ID: " + shirtID); System.out.println("Shirt description:" + description); System.out.println("Color Code: " + colorCode); System.out.println("Shirt price: " + price); System.out.println("Quantity in stock: " + quantityInStock);

} // end of display method

Page 68: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 3, slide 11 of 16Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Creating and Using a Test Class

Example:1 public class ShirtTest {23 public static void main (String args[]) {45 Shirt myShirt;6 myShirt = new Shirt();78 myShirt.displayShirtInformation();910 }11 }

Page 69: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 3, slide 12 of 16Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The main Method

Syntax:public static void main (String args[])

Page 70: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 3, slide 13 of 16Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Compiling a Program

1. Go the directory where the source code files arestored.

2. Enter the following command for each .java fileyou want to compile.

• Syntax:javac classname .java

• Example:javac Shirt.java

Page 71: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 3, slide 14 of 16Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Executing (Testing) a Program

1. Go the directory where the class files are stored.

2. Enter the following for the class file that contains themain method.

• Syntaxjava filename

• Examplejava ShirtTest

• Output:Shirt ID: 0Shirt description:-description required-Color Code: UShirt price: 0.0Quantity in stock: 0

Page 72: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 3, slide 15 of 16Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Debugging Tips

• Error messages state the line number where the erroroccurs. That line might not always be the actual sourceof the error.

• Be sure that you have a semicolon at the end of everyline where one is required, and no others.

• Be sure that you have an even number of braces.

• Be sure that you have used consistent indenting in yourprogram, as shown in examples in this course.

Page 73: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 3, slide 16 of 16Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise: Writing, Compiling, and Testing aBasic Program

• Objectives

• Tasks

• Discussion

• Solutions

Page 74: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language

Module 4

Declaring, Initializing, and UsingVariables

Page 75: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 2 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Overview

• Objectives:

• Identify the uses for variables and define the syntaxfor a variable

• List the eight Java programming language primitivedata types

• Declare, initialize, and use variables and constantsaccording to Java programming languageguidelines and coding standards

• Modify variable values using operators

• Use promotion and type casting

• Relevance

Page 76: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 3 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Identifying Variable Use and Syntax

Example:

1 public class Shirt {23 public int shirtID = 0; // Default ID for the shirt4 public String description = “-description required-”; // default56 // The color codes are R=Red, B=Blue, G=Green, U=Unset7 public char colorCode = ‘U’;89 public double price = 0.0; // Default price for all shirts1011 public int quantityInStock = 0; // Default quantity for all shirts1213 // This method displays the values for an item14 public void displayShirtInformation() {1516 System.out.println(“Shirt ID: “ + shirtID);17 System.out.println(“Shirt description:” + description);

Page 77: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 4 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 System.out.println(“Color Code: “ + colorCode);19 System.out.println(“Shirt price: “ + price);20 System.out.println(“Quantity in stock: “ + quantityInStock);2122 } // end of display method23 } // end of class

Page 78: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 5 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Uses for Variables

• Holding unique data for an object instance

• Assigning the value of one variable to another

• Representing values within a mathematical expression

• Printing the values to the screen

• Holding references to other objects

Page 79: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 6 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Variable Declaration and Initialization

• Syntax (attribute or instance variables):[ modifiers ] type identifier = [ value ];

• Syntax (local variables):type identifier ;

• Syntax (local variables)type identifier = [ value ];

• Examples:

public int shirtID = 0;public String description = "-description required-";public char colorCode = ’U’;public double price = 0.0;public int quantityInStock = 0;

Page 80: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 7 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Describing Primitive Data Types

• Integral types (byte , short , int , and long )

• Floating point types (float and double )

• Textual type (char )

• Logical type (boolean )

Page 81: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 8 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Integral Primitive Types

Type Length Range Examples of AllowedLiteral Values

byte 8 bits -27 to 27 -1 (-128 to 127,or 256 possible values)

2-114

short 16 bits -215 to 215 -1 (-32,768 to 32,767,or 65,535 possible values)

2-32699

int 32 bits -231 to 231 -1 (-2,147,483,648 to2,147,483,647 or4,294,967,296 possiblevalues)

2147,334,778

long 64 bits -263 to 263 -1(-9,223,372,036854,775,808 to9,223,372,036854,775,807, or18,446,744,073,709,551,616possible values)

2-2,036,854,775,808L1L

Page 82: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 9 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Integral Primitive Types

public int shirtID = 0; // Default ID for the shirtpublic int quantityInStock = 0; // Default quantity for all shirts

Page 83: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 10 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Floating Point Primitive Types

public double price = 0.0; // Default price for all shirts

Type FloatLength

Examples of Allowed Literal Values

float 32 bits 99F-327,456,99.01F4.2E6F (engineering notation for4.2 * 106)

double 64 bits -11112.1E12999,701,327,456,99.999

Page 84: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 11 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Textual Primitive Type

• The only data type is char .

• Used for a single character (16 bits), such as a ‘y’.

• Example:public char colorCode = ’U’;

Page 85: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 12 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Logical Primitive Type

• The only data type is boolean .

• Can store only true or false .

• Used to hold the result of an expression that evaluatesto either true or false .

Page 86: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 13 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Naming a Variable

• Rules:

• Variable identifiers must start with either anuppercase or lowercase letter, an underscore (_), or adollar sign ($).

• Variable identifiers cannot contain punctuation,spaces, dashes, or any of the Java technologykeywords.

Page 87: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 14 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Naming a Variable

• Guidelines:

• Begin each variable with a lowercase letter;subsequent words should be capitalized, such asmyVariable .

• Chose names that are mnemonic and that indicate tothe casual observer the contents of the variable.

Page 88: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 15 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Assigning a Value to a Variable

• Example:price = 12.99;

• Example (boolean ):boolean isOpen = false;

Page 89: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 16 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Declaring and Initializing Several Variablesin One Line of Code

• Syntax:type identifier = value [, identifier = value ];

• Example:double price = 0.0, wholesalePrice = 0.0;

Page 90: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 17 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Additional Ways to Declare Variables andAssign Values to Variables

• Assigning literal values:int ID = 0;float pi = 3.14F;char myChar = ’G’;boolean isOpen = false;

• Assigning the value of one variable to another variable:int ID = 0;int saleID = ID;

Page 91: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 18 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Additional Ways to Declare Variables andAssign Values to Variables

• Assigning the result of an expression to integral,floating point, or Boolean variables

float numberOrdered = 908.5F;float casePrice = 19.99F;float price = (casePrice * numberOrdered);

int hour = 12;boolean isOpen = (hour > 8);

• Assigning the return value of a method call to avariable

Page 92: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 19 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Constants

• Variable (can change):double salesTax = 6.25;

• Constant (cannot change):final double SALES_TAX = 6.25;

• Guideline – Constants should be capitalized withwords separated by an underscore(_).

Page 93: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 20 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Storing Primitives and Constantsin Memory

Heap MemoryStack Memory

Variable declared

inside of a method

Objects with

attribute variables

Page 94: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 21 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 1: Using Primitive Type Variablesin a Program

• Objectives

• Tasks

• Discussion

Page 95: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 22 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Standard Mathematical Operators

Purpose Operator Example Comments

Addition + sum = num1 + num2If num1is 10 and num2is2, sum is 12.

Subtraction – diff = num1 – num2If num1is 10 and num2is2, diff is 8.

Multiplication

* prod = num1 * num2If num1is 10 and num2is2, prod is 20.

Division / quot = num1 / num2If num1is 31 and num2is6, quot is 5

Division returnsan integer value(with noremainder).

Page 96: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 23 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Remainder % mod = num1 % num2If num1is 31 and num2is6, mod is 1.

Remainder findsthe remainder ofthe first numberdivided by thesecond number.

Remainder alwaysgives an answerwith the same signas the firstoperand.

3165 R 1

30

1

Page 97: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 24 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Increment and Decrement Operators

• The long way:age = age + 1;

• The short way:

Operator Purpose Example Notes

++ Pre-Increment(++variable )

int i = 6;int j = ++i;i is 7, j is 7

Post-Increment(variable++ )

int i = 6;int j = i++;i is 7, j is 6

The value of i is assignedto j before i isincremented. Therefore, jis assigned 6.

Page 98: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 25 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

-- Pre-Decrement(-- variable )

int i = 6;int j = --i;i is 5, j is 5

Post-Decrement(variable -- )

int i = 6;int j = i--;i is 5, j is 6

The value i is assigned to jbefore i is decremented.Therefore, j is assigned 6.

Page 99: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 26 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Increment and Decrement Operators(++ and – –)

Examples:

int count=15;int a, b, c, d;a = count++;b = count;c = ++count;d = count;System.out.println(a + “, “ + b + “, “ + c + “, “ + d);

Page 100: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 27 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Operator Precedence

• Rules of precedence:

1. Operators within a pair of parentheses

2. Increment and decrement operators

3. Multiplication and division operators, evaluatedfrom left to right

4. Addition and subtraction operators, evaluated fromleft to right

• Example of need for rules of precedence:c = 25 - 5 * 4 / 2 - 10 + 4;

Is the answer 34 or 9?

Page 101: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 28 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Using Parentheses

Examples:

c = (((25 - 5) * 4) / (2 - 10)) + 4;c = ((20 * 4) / (2 - 10)) + 4;c = (80 / (2 - 10)) + 4;c = (80 / -8) + 4;c = -10 + 4;c = -6;

Page 102: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 29 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Using Promotion and Type Casting

• Example of potential issue:int num1 = 53; // 32 bits of memory to hold the valueint num2 = 47; // 32 bits of memory to hold the valuebyte num3; // 8 bits of memory reservednum3 = (num1 + num2); // causes compiler error

• Example of potential solution:int num1 = 53;int num2 = 47;long num3;num3 = (num1 + num2);

Page 103: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 30 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Promotion

• Automatic promotions:

• If you assign a smaller type to a larger type

• If you assign an integral type to a floating point type

• Examples of automatic promotions:long big = 6;int small = 99L;

Page 104: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 31 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Type Casting

• Syntax:identifier = ( target_type ) value

• Example of potential issue:int num1 = 53; // 32 bits of memory to hold the valueint num2 = 47; // 32 bits of memory to hold the valuebyte num3; // 8 bits of memory reservednum3 = (num1 + num2); // causes compiler error

• Example of potential solution:int num1 = 53; // 32 bits of memory to hold the valueint num2 = 47; // 32 bits of memory to hold the valuebyte num3; // 8 bits of memory reservednum3 = (byte)(num1 + num2); // no data loss

Page 105: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 32 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Type Casting

Examples:

int myInt;long myLong = 99L;myInt = (int) (myLong); // No data loss, only zeroes. // A much larger number would // result in data loss.

int myInt;long myLong = 123987654321L;myInt = (int) (myLong); // Number is "chopped"

Page 106: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 33 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Compiler Assumptions for Integral andFloating Point Data Types

• Example of potential problem:short a, b, c;a = 1 ;b = 2 ;c = a + b ;

• Example of potential solutions:

• Declare c as an int type in the original declaration:int c;

• Typecast the (a+b) result in the assignment line:c = (short)(a+b);

Page 107: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 34 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Floating Point Data Types and Assignment

• Example of potential problem:float float1 = 27.9;

• Example of potential solutions:

• The F notifies the compiler that 27.9 is a float value:float float1 = 27.9F;

• 27.9 is cast to a float value:float float1 = (float) 27.9;

Page 108: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 35 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Example

1 public class Person {23 public int ageYears = 32;45 public void calculateAge() {67 int ageDays = ageYears * 365;8 long ageSeconds = ageYears * 365 * 24L * 60 * 60;910 System.out.println(“You are “ + ageDays + “ days old.”);11 System.out.println(“You are “ + ageSeconds + “ seconds old.”);1213 } // end of calculateAge method14 } // end of class

Page 109: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 4, slide 36 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 2: Using Operators andType Casting

• Objectives

• Tasks

• Discussion

• Solutions

Page 110: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language

Module 5

Creating and Using Objects

Page 111: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 2 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Overview

• Objectives:

• Declare, instantiate, and initialize object referencevariables

• Compare how object reference variables are storedin relation to primitive variables

• Use a class (the String class) included in the JavaSDK

• Use the Java 2 Platform, Standard Edition™ (J2SE™)API documentation to learn about other classes inthis API

• Relevance

Page 112: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 3 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Declaring Object References, InstantiatingObjects, and Initializing Object References

3222 Jones St.

777 Boulder Ln.

Page 113: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 4 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Declaring Object References, InstantiatingObjects, and Initializing Object References

• Example:1 public class ShirtTest {23 public static void main (String args[]) {45 Shirt myShirt;6 myShirt = new Shirt();78 myShirt.displayShirtInformation();910 }11 }

Page 114: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 5 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Declaring Object Reference Variables

• Syntax:Classname identifier;

• Example:Shirt myShirt;

Page 115: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 6 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Instantiating an Object

Syntax:

new Classname()

Page 116: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 7 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Initializing Object Reference Variables

• The assignment operator

• Example:myShirt = new Shirt();

Page 117: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 8 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Using an Object ReferenceVariable to Manipulate Data

• Example:1 public class ShirtTestTwo {23 public static void main (String args[]) {45 Shirt myShirt = new Shirt();6 Shirt yourShirt = new Shirt();78 myShirt.displayShirtInformation();9 yourShirt.displayShirtInformation();1011 myShirt.colorCode=’R’;12 yourShirt.colorCode=’G’;1314 myShirt.displayShirtInformation();15 yourShirt.displayShirtInformation();1617 }18 }19

Page 118: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 9 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Storing Object Reference Variables inMemory

public static void main (String args[]) {

int counter ;counter = 10;Shirt myShirt = new Shirt ( ) ;

}

0x034009

0x99f311

myShirt

yourShirt

Heap MemoryStack Memory

0x034009

shirtID

price

colorCode

0

0.0

U

0

0.0

U

0x99f311

shirtID

price

colorCode

10counter

Page 119: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 10 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Assigning an Object Reference From OneVariable to Another

1 Shirt myShirt = new Shirt( );

2 Shirt yourShirt = new Shirt( );

3 myShirt = yourShirt;

0x034009

0x99f311

0x99f311yourShirt

myShirt

Heap MemoryStack Memory

0x034009

shirtID

price

colorCode

0

0.0

U

0

0.0

U

0x99f311

shirtID

price

colorCode

Page 120: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 11 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 1: Using the ObjectTool to Createand Manipulate Objects

• Objectives

• Tasks

• Discussion

Page 121: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 12 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 2: Creating a Test Class

• Objectives

• Tasks

• Discussion

Page 122: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 13 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Using the String Class

• Creating a String object with the new keyword:myName = new String(“Fred Smith”);

• Creating a String object without the new keyword:String myName = “Fred Smith”;

Page 123: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 14 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Storing String Objects in Memory

0xdef

0x0011f

0x0011f

[C value

Comparator0x2244c

String myString = "Sammy Summary";

0xdefmyString

Heap MemoryStack Memory

Sammy SummarySammy Summary

Page 124: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 15 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Using Reference Variables forString Objects

• Example:1 public class PersonTwo {23 public String name = “Jonathan”;4 public String job = “Ice Cream Taster”;56 public void display(){7 System.out.println(“My name is “ + name + “, I am a “ + job);8 }9 } // end of class

Page 125: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 16 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 3: Using the String Class

• Objectives

• Tasks

• Discussion

Page 126: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 17 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 4: Examining String Objects Withthe ObjectTool

• Objectives

• Tasks

• Discussion

Page 127: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 18 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Investigating the Java Class Libraries

• URL to view the J2SE specification:http://java.sun.com/j2se/ version /docs/api/index.html

• Example:http://java.sun.com/j2se/1.4/docs/api/index.html

Page 128: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 19 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Investigating the Java Class Libraries

Page 129: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 20 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Using the Java Class Library Specificationto Learn About a Method

• The println method:System.out.println( data_to_print_to_the_screen );

• Example:System.out.print("Carpe diem ");System.out.println("Seize the day");

prints this:

Carpe diem Seize the day

Page 130: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 5, slide 21 of 21Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 5: Using the Class LibrarySpecification

• Objectives

• Tasks

• Discussion

Page 131: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 1 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Module 6

Using Operators and DecisionConstructs

Page 132: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 2 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Overview

• Objectives:

• Identify relational and conditional operators

• Examine if and if/else constructs

• Use the switch constructs

• Relevance

Page 133: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 3 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Using Relational and Conditional Operators

If there is an

intersection, turn

left or right?

TM

Page 134: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 4 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The Elevator Example

1 public class Elevator {23 public boolean doorOpen=false; // Doors are closed bydefault4 public int currentFloor = 1; // All elevators start onfirst floor5 public final int MAX_FLOORS = 10;6 public final int MIN_FLOORS = 1;78 public void openDoor() {9 System.out.println(“Opening door.”);10 doorOpen = true;11 System.out.println(“Door is open.”);12 }1314 public void closeDoor() {15 System.out.println(“Closing door.”);16 doorOpen = false;17 System.out.println(“Door is closed.”);

Page 135: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 5 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 }1920 public void goUp() {21 System.out.println(“Going up one floor.”);22 currentFloor++;23 System.out.println(“Floor: “ + currentFloor);24 }2526 public void goDown() {27 System.out.println(“Going down one floor.”);28 currentFloor--;29 System.out.println(“Floor: “ + currentFloor);30 }3132 public int getFloor() {33 return currentFloor;34 }3536 public boolean checkDoorStatus() {37 return doorOpen;38 }39 }

Page 136: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 6 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The Elevator Test Class

1 public class ElevatorTest {23 public static void main(String args[]) {45 Elevator myElevator = new Elevator();67 myElevator.openDoor();8 myElevator.closeDoor();9 myElevator.goDown();10 myElevator.goUp();11 myElevator.goUp();12 myElevator.goUp();13 myElevator.openDoor();14 myElevator.closeDoor();15 myElevator.goDown();16 myElevator.openDoor();17 myElevator.closeDoor();18 myElevator.goDown();19 myElevator.openDoor();20 }21 }

Page 137: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 7 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Relational Operators

Condition Operator Example

Is equal to == inti==1;(i == 1)

Is not equal to != int i=2;(i != 1)

Is less than < int i=0;(i < 1)

Is less than or equalto

<= int i=1;(i <= 1)

Is greater than > int i=2;(i > 1)

Is greater than orequal to

>= int i=1;(i >= 1)

Page 138: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 8 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Testing Equality Between Strings

Example:

1 public class Employees {23 public String name1 = “Fred Smith”;4 public String name2 = “Joseph Smith”;56 public void areNamesEqual() {78 if (name1.equals(name2)) {9 System.out.println(“Same name.”);10 }11 else {12 System.out.println(“Different name.”);13 }14 }15 }

Page 139: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 9 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Conditional Operators

Operation Operator Example

If oneconditionANDanothercondition

&& int i = 2;int j = 8;((i < 1) && (j > 6))

If either oneconditionOR anothercondition

|| int i = 2;int j = 8;((i < 1) || (j > 10))

NOT ! int i = 2;int j = 8;(!(i < 3))

Page 140: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 10 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The if Construct

• Syntax:if ( boolean_expression ) {

code_block ;} // end of if construct// program continues here

• Example of potential output:Opening door.Door is open.Closing door.Door is closed.Going down one floor.Floor: 0 <--- this is a error in logicGoing up one floor.Floor: 1Going up one floor.Floor: 2...

Page 141: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 11 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The if Construct

Example of potential solution:

1 public class IfElevator {23 public boolean doorOpen=false; // Doors are closed by default4 public int currentFloor = 1; // All elevators start on first floor5 public final int MAX_FLOORS = 10;6 public final int MIN_FLOORS = 1;78 public void openDoor() {9 System.out.println(“Opening door.”);10 doorOpen = true;11 System.out.println(“Door is open.”);12 }1314 public void closeDoor() {15 System.out.println(“Closing door.”);16 doorOpen = false;17 System.out.println(“Door is closed.”);

Page 142: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 12 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 }1920 public void goUp() {21 System.out.println(“Going up one floor.”);22 currentFloor++;23 System.out.println(“Floor: “ + currentFloor);24 }2526 public void goDown() {2728 if (currentFloor == MIN_FLOORS) {29 System.out.println(“Cannot Go down”);30 }3132 if (currentFloor > MIN_FLOORS) {33 System.out.println(“Going down one floor.”);34 currentFloor--;35 System.out.println(“Floor: “ + currentFloor);36 }37 }3839 public void setFloor() {

Page 143: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 13 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

4041 int desiredFloor = 5;4243 if (currentFloor < desiredFloor) {44 goUp();45 }4647 if (currentFloor > desiredFloor) {48 goDown();4950 }51 }5253 public int getFloor() {54 return currentFloor;55 }5657 public boolean checkDoorStatus() {58 return doorOpen;59 }60 }

Page 144: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 14 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The if Construct

Example potential output:

Opening door.Door is open.Closing door.Door is closed.Cannot Go down <--- elevator logic prevents problemGoing up one floor.Floor: 2Going up one floor.Floor: 3...

Page 145: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 15 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Nested if Statements

Example:

1 public class NestedIfElevator {23 public boolean doorOpen=false; // Doors are closed by default4 public int currentFloor = 1; // All elevators start on first floor5 public final int MAX_FLOORS = 10;6 public final int MIN_FLOORS = 1;78 public void openDoor() {9 System.out.println(“Opening door.”);10 doorOpen = true;11 System.out.println(“Door is open.”);12 }1314 public void closeDoor() {15 System.out.println(“Closing door.”);16 doorOpen = false;17 System.out.println(“Door is closed.”);

Page 146: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 16 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 }1920 public void goUp() {21 System.out.println(“Going up one floor.”);22 currentFloor++;23 System.out.println(“Floor: “ + currentFloor);24 }2526 public void goDown() {2728 if (currentFloor == MIN_FLOORS) {29 System.out.println(“Cannot Go down”);30 }3132 if (currentFloor > MIN_FLOORS) {3334 if (!doorOpen) {3536 System.out.println(“Going down one floor.”);37 currentFloor--;38 System.out.println(“Floor: “ + currentFloor);39 }

Page 147: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 17 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

40 }41 }4243 public void setFloor() {4445 int desiredFloor = 5;4647 if (currentFloor < desiredFloor) {48 goUp();49 }5051 if (currentFloor > desiredFloor) {52 goDown();53 }54 }5556 public int getFloor() {57 return currentFloor;58 }5960 public boolean checkDoorStatus() {61 return doorOpen;

Page 148: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 18 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

62 }63 }

Page 149: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 19 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The if/else Construct

Syntax:

if ( boolean_expression ) {

code_block ;

} // end of if construct

else {

code_block ;

} // end of else construct

// program continues here

Page 150: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 20 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The if/else Construct

Example:

1 public class IfElseElevator {23 public boolean doorOpen=false; // Doors are closed by default4 public int currentFloor = 1; // All elevators start on first floor5 public final int MAX_FLOORS = 10;6 public final int MIN_FLOORS = 1;78 public void openDoor() {9 System.out.println(“Opening door.”);10 doorOpen = true;11 System.out.println(“Door is open.”);12 }1314 public void closeDoor() {15 System.out.println(“Closing door.”);16 doorOpen = false;17 System.out.println(“Door is closed.”);

Page 151: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 21 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 }1920 public void goUp() {21 System.out.println(“Going up one floor.”);22 currentFloor++;23 System.out.println(“Floor: “ + currentFloor);24 }2526 public void goDown() {2728 if (currentFloor == MIN_FLOORS) {29 System.out.println(“Cannot Go down”);30 }3132 else {33 System.out.println(“Going down one floor.”);34 currentFloor--;35 System.out.println(“Floor: “ + currentFloor);36 }37 }3839 public void setFloor() {

Page 152: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 22 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

4041 int desiredFloor = 5;4243 if (currentFloor < desiredFloor) {44 goUp();45 }4647 if (currentFloor > desiredFloor) {48 goDown();49 }50 }5152 public int getFloor() {53 return currentFloor;54 }5556 public boolean checkDoorStatus() {57 return doorOpen;58 }59 }

Page 153: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 23 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The if/else Construct

Example potential output:

Opening door.Door is open.Closing door.Door is closed.Cannot Go down <--- elevator logic prevents problemGoing up one floor.Floor: 2Going up one floor.Floor: 3...

Page 154: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 24 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Chaining if/else Constructs

Syntax:

if ( boolean_expression ) {

code_block ;

} // end of if construct

else if ( boolean_expression ){

code_block ;

} // end of else if construct

else {

code_block ;}// program continues here

Page 155: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 25 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Chaining if/else Constructs

Example:

1 public class IfElseDate {23 public int month = 10;45 public void calculateNumDays() {67 if (month == 1 || month == 3 || month == 5 || month == 7 ||8 month == 8 || month == 10 || month == 12) {910 System.out.println(“There are 31 days in that month.”);11 }1213 else if (month == 2) {14 System.out.println(“There are 28 days in that month.”);15 }1617 else if (month == 4 || month == 6 || month == 9 || month == 11) {

Page 156: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 26 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 System.out.println(“There are 30 days in that month.”);19 }2021 else {22 System.out.println(“Invalid month.”);23 }24 }25 }

Page 157: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 27 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 1: Using if and if/elseConstructs

• Objectives

• Tasks

• Discussion

Page 158: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 28 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Using the switch Construct

Syntax:

switch (variable) {case literal_value:

code_block;[break;]

case another_literal_value:code_block;[break;]

[default:]code_block;

}

Page 159: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 29 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Using the switch Construct

Example:

1 public class SwitchDate {23 public int month = 10;45 public void calculateNumDays() {67 switch(month) {8 case 1:9 case 3:10 case 5:11 case 7:12 case 8:13 case 10:14 case 12:15 System.out.println(“There are 31 days in that month.”);16 break;17 case 2:

Page 160: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 30 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 System.out.println(“There are 28 days in that month.”);19 break;20 case 4:21 case 6:22 case 9:23 case 11:24 System.out.println(“There are 30 days in that month.”);25 break;26 default:27 System.out.println(“Invalid month.”);28 break;29 }30 }31 }

Page 161: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 31 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

When to Use switch Constructs

• Any equality test

• Tests against a single variable, such as customerStatus

• Tests against the value of an int , short , byte , or chartype

Page 162: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 6, slide 32 of 32Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 2: Using the switch Construct

• Objectives

• Tasks

• Discussion

Page 163: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language

Module 7

Using Loop Constructs

Page 164: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 2 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Overview

• Objectives:

• Create while loops

• Develop for loops

• Create do/while loops

• Relevance

Page 165: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 3 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Creating while Loops

• Syntax:while ( boolean_expression ) {

code_block;

} // end of while construct

// program continues here

Page 166: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 4 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Creating while Loops

Example:

1 public class WhileElevator {23 public boolean doorOpen=false;4 public int currentFloor = 1;5 public int weight = 0;67 public final int CAPACITY = 1000;8 public final int TOP_FLOOR = 5;9 public final int BOTTOM_FLOOR = 1;1011 public void openDoor() {12 System.out.println(“Opening door.”);13 doorOpen = true;14 System.out.println(“Door is open.”);15 }1617 public void closeDoor() {

Page 167: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 5 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 System.out.println(“Closing door.”);19 doorOpen = false;20 System.out.println(“Door is closed.”);21 }2223 public void goUp() {24 System.out.println(“Going up one floor.”);25 currentFloor++;26 System.out.println(“Floor: “ + currentFloor);27 }2829 public void goDown() {30 System.out.println(“Going down one floor.”);31 currentFloor--;32 System.out.println(“Floor: “ + currentFloor);33 }3435 public void setFloor() {3637 int desiredFloor = 5;3839 while (currentFloor != desiredFloor)

Page 168: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 6 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

40 if (currentFloor < desiredFloor) {41 goUp();42 }43 else {44 goDown();45 }46 }4748 public int getFloor() {49 return currentFloor;50 }5152 public boolean checkDoorStatus() {53 return doorOpen;54 }55 }

Page 169: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 7 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Nested while Loops

• Problem:@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

• Example potential solution:1 public class WhileRectangle {23 public int height = 3;4 public int width = 10;56 public void displayRectangle() {78 int colCount = 0;9 int rowCount = 0;1011 while (rowCount < height) {12 colCount=0;

Page 170: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 8 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

1314 while (colCount < width) {15 System.out.print(“@”);16 colCount++;17 }1819 System.out.println();20 rowCount++;21 }22 }23 }

Page 171: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 9 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 1: Using the while Loop

• Objectives

• Tasks

• Discussion

Page 172: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 10 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Developing a for Loop

Syntax:

for ( initialize [, initialize ]; boolean_expression ;update [, update ]) {

code_block ;}

Page 173: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 11 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Developing a for Loop

Example:

1 public class ForElevator {23 public boolean doorOpen=false;4 public int currentFloor = 1;5 public int weight = 0;67 public final int CAPACITY = 1000;8 public final int TOP_FLOOR = 5;9 public final int BOTTOM_FLOOR = 1;1011 public void openDoor() {12 System.out.println(“Opening door.”);13 doorOpen = true;14 System.out.println(“Door is open.”);15 }1617 public void closeDoor() {

Page 174: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 12 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 System.out.println(“Closing door.”);19 doorOpen = false;20 System.out.println(“Door is closed.”);21 }2223 public void goUp() {24 System.out.println(“Going up one floor.”);25 currentFloor++;26 System.out.println(“Floor: “ + currentFloor);27 }2829 public void goDown() {30 System.out.println(“Going down one floor.”);31 currentFloor--;32 System.out.println(“Floor: “ + currentFloor);33 }3435 public void setFloor() {3637 int desiredFloor = 5;3839 if (currentFloor > desiredFloor) {

Page 175: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 13 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

40 for (int down = currentFloor; down != desiredFloor; --down) {41 goDown();42 }43 }4445 else {46 for (int up = currentFloor; up != desiredFloor; ++up) {47 goUp();48 }49 }50 }5152 public int getFloor() {53 return currentFloor;54 }5556 public boolean checkDoorStatus() {57 return doorOpen;58 }59 }

Page 176: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 14 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Nested for Loops

Example:

1 public class ForRectangle {23 public int height = 3;4 public int width = 10;56 public void displayRectangle() {78 for (int rowCount = 0; rowCount < height; rowCount++) {9 for (int colCount = 0; colCount < width; colCount++) {10 System.out.print(“@”);11 }12 System.out.println();13 }14 }15 }

Page 177: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 15 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 2: Using the for Loop

• Objectives

• Tasks

• Discussion

Page 178: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 16 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Coding a do/while Loop

Syntax:

do {

code_block ;}while ( boolean_expression );// Semicolon is mandatory.

Page 179: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 17 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Coding a do/while Loop

Example:

1 public class DoWhileElevator {23 public boolean doorOpen=false;4 public int currentFloor = 1;5 public int weight = 0;67 public final int CAPACITY = 1000;8 public final int TOP_FLOOR = 5;9 public final int BOTTOM_FLOOR = 1;1011 public void openDoor() {12 System.out.println(“Opening door.”);13 doorOpen = true;14 System.out.println(“Door is open.”);15 }1617 public void closeDoor() {

Page 180: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 18 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 System.out.println(“Closing door.”);19 doorOpen = false;20 System.out.println(“Door is closed.”);21 }2223 public void goUp() {24 System.out.println(“Going up one floor.”);25 currentFloor++;26 System.out.println(“Floor: “ + currentFloor);27 }2829 public void goDown() {30 System.out.println(“Going down one floor.”);31 currentFloor--;32 System.out.println(“Floor: “ + currentFloor);33 }3435 public void setFloor() {3637 int desiredFloor = 5;3839 do {

Page 181: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 19 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

40 if (currentFloor < desiredFloor) {41 goUp();42 }43 else {44 goDown();45 }46 }47 while (currentFloor != desiredFloor);48 }4950 public int getFloor() {51 return currentFloor;52 }5354 public boolean checkDoorStatus() {55 return doorOpen;56 }57 }

Page 182: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 20 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Nested do/while Loops

Example:

1 public class DoWhileRectangle {23 public int height = 3;4 public int width = 10;56 public void displayRectangle() {78 int rowCount = 0;9 int colCount = 0;1011 do {12 colCount = 0;1314 do {15 System.out.print(“@”);16 colCount++;17 }

Page 183: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 21 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 while (colCount < width);1920 System.out.println();21 rowCount++;22 }23 while (rowCount < height);24 }25 }

Page 184: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 22 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Comparing Loop Constructs

• Use the while loop to iterate indefinitely throughstatements and to perform the statements zero or moretimes.

• Use the do/while loop to iterate indefinitely throughstatements and to perform the statements one or moretimes.

• Use the for loop to step through statements apredefined number of times.

Page 185: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 7, slide 23 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 3: Using the do/while Loop

• Objectives

• Tasks

• Discussion

Page 186: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language

Module 8

Developing and Using Methods

Page 187: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 2 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Overview

• Objectives:

• Describe the advantages of methods and defineworker and calling methods

• Declare and invoke a method

• Compare object and static methods

• Use overloaded methods

• Relevance

Page 188: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 3 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Creating and Invoking Methods

• Syntax:[ modifiers ] return_type method_identifier ([ arguments ]) {

method_code_block}

Page 189: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 4 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The Basic Form of a Method

Example:

public void displayShirtInformation() {System.out.println("Shirt ID: " + shirtID);System.out.println("Shirt description:" + description);

System.out.println("Color Code: " + colorCode);System.out.println("Shirt price: " + price);System.out.println("Quantity in stock: " + quantityInStock);

} // end of display method

Page 190: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 5 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Invoking a Method From a Different Class

Example:

1 public class ShirtTest {23 public static void main (String args[]) {45 Shirt myShirt;6 myShirt = new Shirt();78 myShirt.displayShirtInformation();910 }11 }12

Page 191: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 6 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Calling and Worker Methods

TM

Caller

Worker

Page 192: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 7 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Invoking a Method in the Same Class

• Example1 public class Elevator {23 public boolean doorOpen=false;4 public int currentFloor = 1;5 public int weight = 0;67 public final int CAPACITY = 1000;8 public final int TOP_FLOOR = 5;9 public final int BOTTOM_FLOOR = 1;1011 public void openDoor() {12 System.out.println(“Opening door.”);13 doorOpen = true;14 System.out.println(“Door is open.”);15 }1617 public void closeDoor() {18 System.out.println(“Closing door.”);

Page 193: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 8 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

19 doorOpen = false;20 System.out.println(“Door is closed.”);21 }2223 public void goUp() {24 System.out.println(“Going up one floor.”);25 currentFloor++;26 System.out.println(“Floor: “ + currentFloor);27 }2829 public void goDown() {30 System.out.println(“Going down one floor.”);31 currentFloor--;32 System.out.println(“Floor: “ + currentFloor);33 }3435 public void setFloor(int desiredFloor) {36 while (currentFloor != desiredFloor)37 if (currentFloor < desiredFloor) {38 goUp();39 }40 else {

Page 194: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 9 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

41 goDown();42 }43 }4445 public int getFloor() {46 return currentFloor;47 }4849 public boolean checkDoorStatus() {50 return doorOpen;51 }52 }

Page 195: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 10 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Guidelines for Invoking Methods

• There is no limit to the number of method calls that acalling method can make.

• The calling method and the worker method can be inthe same class or in different classes.

• The way you invoke the worker method is different,depending on whether it is in the same class or in adifferent class from the calling method.

• You can invoke methods in any order. Methods do notneed to be completed in the order in which they arelisted in the class where they are declared (the classcontaining the worker methods).

Page 196: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 11 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Passing Arguments and Returning Values

1

2

3

9

10

4

5

6

7

8

V1

V2

Object 1 Object 2

Caller method

Worker method

Value 1 being passed

from object 1 to object 2

Object 2 returns

value 2 to object 1

Page 197: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 12 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Declaring Methods With Arguments

• Example:public void setFloor(int desiredFloor) { while (currentFloor != desiredFloor) if (currentFloor < desiredFloor) {

goUp(); } else {

goDown(); } }

• Example:public void multiply(int NumberOne, int NumberTwo)

Page 198: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 13 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The main Method

• Example:public static void main (String args[])

• Example (invocation):java ShirtTest 12.99 R

Page 199: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 14 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Invoking Methods With Arguments

Example:

1 public class ElevatorTest {23 public static void main(String args[]) {45 Elevator myElevator = new Elevator();67 myElevator.openDoor();8 myElevator.closeDoor();9 myElevator.goUp();10 myElevator.goUp();11 myElevator.goUp();12 myElevator.openDoor();13 myElevator.closeDoor();14 myElevator.goDown();15 myElevator.openDoor();16 myElevator.closeDoor();17 myElevator.goDown();

Page 200: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 15 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

1819 int curFloor = myElevator.getFloor();2021 myElevator.setFloor(myElevator.TOP_FLOOR);22 }23 myElevator.openDoor();24 }25 }

Page 201: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 16 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Declaring Methods With Return Values

Declaration:

public int sum(int numberOne, int numberTwo)

Page 202: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 17 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Returning a Value

Example:

public int getSum() { return sum; }

Page 203: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 18 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Receiving Return Values

Example:

1 public class ElevatorTest {23 public static void main(String args[]) {45 Elevator myElevator = new Elevator();67 myElevator.openDoor();8 myElevator.closeDoor();9 myElevator.goUp();10 myElevator.goUp();11 myElevator.goUp();12 myElevator.openDoor();13 myElevator.closeDoor();14 myElevator.goDown();15 myElevator.openDoor();16 myElevator.closeDoor();17 myElevator.goDown();

Page 204: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 19 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

1819 int curFloor = myElevator.getFloor();2021 myElevator.setFloor(myElevator.TOP_FLOOR);22 }23 myElevator.openDoor();24 }25 }

Page 205: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 20 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Advantages of Method Use

• Methods make programs more readable and easier tomaintain.

• Methods make development and maintenance quicker.

• Methods are central to reusable software.

• Methods allow separate objects to communicate and todistribute the work performed by the program.

Page 206: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 21 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 1: Using Arguments and ReturnValues

• Objectives

• Tasks

• Discussion

Page 207: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 22 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Creating Static Methods and Variables

• Comparing instance and static methods andvariables

• Declaring static methods:static Properties getProperties()

• Invoking static methods:Classname . method ();

Page 208: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 23 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Creating static Methods and Variables

Example:

public static char convertShirtSize(int numericalSize) {

if (numericalSize < 10) { return ’S’; }

else if (numericalSize < 14) { return ’M’; }

else if (numericalSize < 18) { return ’L’; }

else { return ’X’;

Page 209: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 24 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Creating static Methods and Variables

• Declaring static variables:static double SALES_TAX = 8.25;

• Accessing static variables:Classname . variable ;

• Example:double myPI;myPI = Math.PI;

Page 210: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 25 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Static Methods and Variables in the Java API

• Examples:

• The Math class

• The System class

• The StrictMath class

Page 211: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 26 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Static Methods and Variables in the Java API

• When to declare a static method or variable:

• Performing the operation on an individual object orassociate the variable with a specific object type is notimportant.

• Accessing the variable or method before instantiatingan object is important.

• The method or variable does not logically belong toan object, but possibly belongs to a utility class suchas the Math class included in the Java API.

Page 212: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 27 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Using Method Overloading

Example overloaded methods:

1 public class Calculator {23 public int sum(int numberOne, int numberTwo){45 System.out.println(“Method One”);67 return numberOne + numberTwo;8 }910 public float sum(float numberOne, float numberTwo) {1112 System.out.println(“Method Two”);1314 return numberOne + numberTwo;15 }1617 public float sum(int numberOne, float numberTwo) {

Page 213: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 28 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

1819 System.out.println(“Method Three”);2021 return numberOne + numberTwo;22 }23 }

Page 214: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 29 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Using Method Overloading

Example method invocation:

1 public class CalculatorTest {23 public static void main(String [] args) {45 Calculator myCalculator = new Calculator();67 int totalOne = myCalculator.sum(2,3);8 System.out.println(totalOne);910 float totalTwo = myCalculator.sum(15.99F, 12.85F);11 System.out.println(totalTwo);1213 float totalThree = myCalculator.sum(2, 12.85F);14 System.out.println(totalThree);15 }16 }17

Page 215: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 30 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Method Overloading and the Java API

Method Use

void println() Terminate the current line by writing theline separator string

void println(boolean x) Print a boolean value and thenterminate the line

void println(char x) Print a character and then terminate theline

void println(char[] x) Print an array of characters and thenterminate the line

void println(double x) Print a double and then terminate theline

void println(float x) Print a float and then terminate the line

void println(int x) Print an int and then terminate the line

void println(long x) Print a long and then terminate the line

void println(Object x) Print an object and then terminate theline

void println(String x) Print a string and then terminate the line

Page 216: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 31 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Uses for Method Overloading

Examples:

public int sum(int numberOne, int numberTwo)public int sum(int numberOne, int numberTwo, int numberThree)public int sum(int numberOne, int numberTwo,int numberThree, int numberFour)

Page 217: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 32 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Uses for Method Overloading

Example:

1 public class ShirtTwo {23 public int shirtID = 0; // Default ID for the shirt4 public String description = “-description required-”; // default56 // The color codes are R=Red, B=Blue, G=Green, U=Unset7 public char colorCode = ‘U’;8 public double price = 0.0; // Default price for all items9 public int quantityInStock = 0; // Default quantity for all items1011 public void setShirtInfo(int ID, String d, double p){12 shirtID = ID;13 description = d;14 price = p;15 }1617 public void setShirtInfo(int ID, String d, double p, char c){

Page 218: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 33 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 shirtID = ID;19 description = d;20 colorCode = c;21 price = p;22 }2324 public void setShirtInfo(int ID, String d, double p, char c, int q){25 shirtID = ID;26 description = d;27 colorCode = c;28 price = p;29 quantityInStock = q;30 }3132 // This method displays the values for an item33 public void display() {3435 System.out.println(“Item ID: “ + shirtID);36 System.out.println(“Item description:” + description);37 System.out.println(“Color Code: “ + colorCode);38 System.out.println(“Item price: “ + price);39 System.out.println(“Quantity in stock: “ + quantityInStock);

Page 219: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 34 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

4041 } // end of display method42 } // end of class

Page 220: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 35 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Uses for Method Overloading

Example:

1 class ShirtTwoTest {23 public static void main (String args[]) {4 ShirtTwo shirtOne = new ShirtTwo();5 ShirtTwo shirtTwo = new ShirtTwo();6 ShirtTwo shirtThree = new ShirtTwo();78 shirtOne.setShirtInfo(100, “Button Down”, 12.99);9 shirtTwo.setShirtInfo(101, “Long Sleeve Oxford”, 27.99, ‘G’);10 shirtThree.setShirtInfo(102, “Shirt Sleeve T-Shirt”, 9.99, ‘B’, 50);1112 shirtOne.display();13 shirtTwo.display();14 shirtThree.display();15 }16 }

Page 221: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 8, slide 36 of 36Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 2: Using Overloaded Methods

• Objectives

• Tasks

• Discussion

Page 222: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Release Level – SRT 1

Module 9

Implementing Encapsulation andConstructors

Page 223: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 2 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Overview

• Objectives:

• Use encapsulation to protect data

• Create constructors to initialize objects

• Relevance

Page 224: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 3 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Using Encapsulation

Page 225: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 4 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The public Modifier

public int currentFloor=1;

public void setFloor(int desiredFloor) {...

}

P

1

2

3

4

5

TM

Elevator

Control Panel

Public Access

Public Access

Public Access

Public Access

Public Access

Public Access

Page 226: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 5 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The public Modifier

Example:

1 public class PublicElevator {23 public boolean doorOpen=false;4 public int currentFloor = 1;56 public final int TOP_FLOOR = 5;7 public final int BOTTOM_FLOOR = 1;8 }

Page 227: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 6 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The public Modifier

Example:

1 public class PublicElevatorTest {23 public static void main(String args[]) {45 PublicElevator pubElevator = new PublicElevator();67 pubElevator.doorOpen = true; //passengers get on8 pubElevator.doorOpen = false; //doors close9 //go down to floor 0 (below bottom of building)10 pubElevator.currentFloor--;11 pubElevator.currentFloor++;1213 //jump to floor 7 (only 5 floors in building)14 pubElevator.currentFloor = 7;15 pubElevator.doorOpen = true; //passengers get on/off16 pubElevator.doorOpen = false;17 pubElevator.currentFloor = 1; //go to the first floor

Page 228: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 7 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 pubElevator.doorOpen = true; //passengers get on/off19 pubElevator.currentFloor++; //elevator moves with door open20 pubElevator.doorOpen = false;21 pubElevator.currentFloor--;22 pubElevator.currentFloor--;23 }24 }25

Page 229: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 8 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The private Modifier

private int currentFloor=1;

private void calculateCapacity() { ...}

Elevator

Control Panel

P

1

2

3

4

5 Private Access

Public Access

Private Access

Private Access

Public Access

Public Access

TM

Page 230: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 9 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The private Modifier

Example:

1 public class PrivateElevator1 {23 private boolean doorOpen=false;4 private int currentFloor = 1;56 private final int TOP_FLOOR = 5;7 private final int BOTTOM_FLOOR = 1;8 }

Page 231: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 10 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The private Modifier

Example:

1 public class PrivateElevator1Test {23 public static void main(String args[]) {45 PrivateElevator1 privElevator = new PrivateElevator1();67 /**************************************************8 * The following lines of code will not compile *9 * because they attempt to access private *10 * variables. *11 **************************************************/1213 privElevator.doorOpen = true; //passengers get on14 privElevator.doorOpen = false; //doors close15 //go down to currentFloor 0 (below bottom of building)16 privElevator.currentFloor--;17 privElevator.currentFloor++;

Page 232: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 11 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

1819 //jump to currentFloor 7 (only 5 floors in building)20 privElevator.currentFloor = 7;21 privElevator.doorOpen = true; //passengers get on/off22 privElevator.doorOpen = false;23 privElevator.currentFloor = 1; //go to the first floor24 privElevator.doorOpen = true; //passengers get on/off25 privElevator.currentFloor++; //elevator moves with door open26 privElevator.doorOpen = false;27 privElevator.currentFloor--;28 privElevator.currentFloor--;29 }30 }

Page 233: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 12 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Interface and Implementation

Elevator

Control Panel

Down

Up

Elevator 1 Going Up Elevator 2 Going Up

Page 234: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 13 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Interface and Implementation

Example:

1 public class PrivateShirt1 {23 private int shirtID = 0; // Default ID for the shirt4 private String description = “-description required-”; // default56 // The color codes are R=Red, B=Blue, G=Green, U=Unset7 private char colorCode = ‘U’;8 private double price = 0.0; // Default price for all items9 private int quantityInStock = 0; // Default quantity for all items1011 public char getColorCode() {12 return colorCode;13 }1415 public void setColorCode(char newCode) {16 colorCode = newCode;17 }

Page 235: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 14 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

1819 // Additional get and set methods for shirtID, description,20 // price, and quantityInStock would follow2122 } // end of class

Page 236: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 15 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Interface and Implementation

Example:

1 public class PrivateShirt1Test {23 public static void main (String args[]) {45 PrivateShirt1 privShirt = new PrivateShirt1();6 char colorCode;78 // Set a valid colorCode9 privShirt.setColorCode(‘R’);10 colorCode = privShirt.getColorCode();1112 // The PrivateShirtTest1 class can set a valid colorCode13 System.out.println(“Color Code: “ + colorCode);1415 // Set an invalid color code16 privShirt.setColorCode(‘Z’);17 colorCode = privShirt.getColorCode();

Page 237: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 16 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

1819 // The PrivateShirtTest1 class can set an invalid colorCode20 System.out.println(“Color Code: “ + colorCode);21 }22 }

Page 238: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 17 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Interface and Implementation

Example:

1 public class PrivateShirt2 {23 private int shirtID = 0; // Default ID for the shirt4 private String description = “-description required-”; // default56 // The color codes are R=Red, B=Blue, G=Green, U=Unset7 private char colorCode = ‘U’;8 private double price = 0.0; // Default price for all items9 private int quantityInStock = 0; // Default quantity for all items1011 public char getColorCode() {12 return colorCode;13 }1415 public void setColorCode(char newCode) {1617 switch (newCode) {

Page 239: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 18 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 case ‘R’:19 case ‘G’:20 case ‘B’:21 colorCode = newCode;22 break;23 default:24 System.out.println(“Invalid colorCode. Use R, G, or B”);25 }26 }2728 // Additional get and set methods for shirtID, description,29 // price, and quantityInStock would follow3031 } // end of class

Page 240: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 19 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Interface and Implementation

Example:

1 public class PrivateShirt2Test {23 public static void main (String args[]) {45 PrivateShirt2 privShirt = new PrivateShirt2();6 char colorCode;78 // Set a valid colorCode9 privShirt.setColorCode(‘R’);10 colorCode = privShirt.getColorCode();1112 // The PrivateShirtTest1 class can set a valid colorCode13 System.out.println(“Color Code: “ + colorCode);1415 // Set an invalid color code16 privShirt.setColorCode(‘Z’);17 colorCode = privShirt.getColorCode();

Page 241: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 20 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

1819 // The PrivateShirtTest2 class cannot set an invalid colorCode.20 // Color code is still R21 System.out.println(“Color Code: “ + colorCode);22 }23 }

Page 242: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 21 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

An Encapsulated Elevator

Example:

1 public class PrivateElevator2 {23 private boolean doorOpen=false;4 private int currentFloor = 1;5 private int weight = 0;67 final int CAPACITY = 1000;8 final int TOP_FLOOR = 5;9 final int BOTTOM_FLOOR = 1;1011 public void openDoor() {12 doorOpen = true;13 }1415 public void closeDoor() {16 calculateCapacity();17

Page 243: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 22 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 if (weight <= CAPACITY) {19 doorOpen = false;20 }21 else {22 System.out.println(“The elevator has exceeded capacity.”);23 System.out.println(“Doors will remain open until someone exits!”);24 }25 }2627 // In reality, the elevator would have weight sensors to28 // check the actual weight in the elevator, but for the sake29 // of simplicity we just pick a random number to represent the30 // weight in the elevator3132 private void calculateCapacity() {33 weight = (int) (Math.random() * 1500);34 System.out.println(“The weight is “ + weight);35 }3637 public void goUp() {38 if (!doorOpen) {39 if (currentFloor < TOP_FLOOR) {

Page 244: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 23 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

40 currentFloor++;41 System.out.println(currentFloor);42 }43 else {44 System.out.println(“Already on top floor.”);45 }46 }47 else {48 System.out.println(“Doors still open!”);49 }50 }5152 public void goDown() {53 if (!doorOpen) {54 if (currentFloor > BOTTOM_FLOOR) {55 currentFloor--;56 System.out.println(currentFloor);57 }58 else {59 System.out.println(“Already on bottom floor.”);60 }61 }

Page 245: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 24 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

62 else {63 System.out.println(“Doors still open!”);64 }65 }6667 public void setFloor(int desiredFloor) {68 if ((desiredFloor >= BOTTOM_FLOOR) && (desiredFloor<=TOP_FLOOR)) {6970 while (currentFloor != desiredFloor) {71 if (currentFloor < desiredFloor) {72 goUp();73 }7475 else {76 goDown();77 }78 }79 }80 else {81 System.out.println(“Invalid Floor”);82 }83 }

Page 246: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 25 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

8485 public int getFloor() {86 return currentFloor;87 }8889 public boolean getDoorStatus() {90 return doorOpen;91 }92 }93

Page 247: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 26 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

An Encapsulated Elevator

Example:

1 public class PrivateElevator2Test {23 public static void main(String args[]) {45 PrivateElevator2 privElevator = new PrivateElevator2();67 privElevator.openDoor();8 privElevator.closeDoor();9 privElevator.goDown();10 privElevator.goUp();11 privElevator.goUp();12 privElevator.openDoor();13 privElevator.closeDoor();14 privElevator.goDown();15 privElevator.openDoor();16 privElevator.goDown();17 privElevator.closeDoor();

Page 248: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 27 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 privElevator.goDown();19 privElevator.goDown();2021 int curFloor = privElevator.getFloor();2223 if (curFloor != 5 && ! privElevator.getDoorStatus()) {24 privElevator.setFloor(5);25 }2627 privElevator.setFloor(10);28 privElevator.openDoor();29 }30 }

Page 249: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 28 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Sample Output

The weight is 453Already on bottom floor.23The weight is 8992Doors still open!The weight is 9741Already on bottom floor.2345

Page 250: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 29 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 1: Writing Encapsulated Classes

• Objectives

• Tasks

• Discussion

Page 251: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 30 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Describing Variable Scope

Example:

1 public class Person2 {23 // begin scope of int age4 private int age = 34;56 public void displayName() {78 // begin scope of String name9 String name = “Peter Simmons”;10 System.out.println(“My name is “ + name + “ and I am “ + age );1112 } // end scope of String name1314 public String getName () {1516 return name; // this causes an error17 }

Page 252: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 31 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 } // end scope of int age

Page 253: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 32 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

How Instance Variables and Local VariablesAppear in Memory

myShirt

counter

Heap MemoryStack Memory

0x034009

shirtID

price

colorCode

425566

0.0

U0x034009

100

public static void main (String args[]) {

int counter = 100;Shirt myShirt = new Shirt ( );

myShirt .shirtID = 425566 ;}

Page 254: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 33 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Creating Constructors

• Syntax:modifiers class ClassName {

ConstructorName([arguments]) {code_block ;

}}

• Example:1 public class ConstructorShirt1 {23 private int shirtID = 0; // Default ID for the shirt4 private String description = “-description required-”; // default56 // The color codes are R=Red, B=Blue, G=Green, U=Unset7 private char colorCode = ‘U’;8 private double price = 0.0; // Default price for all items9 private int quantityInStock = 0; // Default quantity for all items

Page 255: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 34 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

1011 public ConstructorShirt1(char startingCode) {1213 switch (startingCode) {14 case ‘R’:15 case ‘G’:16 case ‘B’:17 colorCode = startingCode;18 break;19 default:20 System.out.println(“Invalid colorCode. Use R, G, or B”);21 }22 }2324 public char getColorCode() {25 return colorCode;26 }27 } // end of class2829

Page 256: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 35 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Creating Constructors

Example:

1 public class ConstructorShirt1Test {23 public static void main (String args[]) {45 ConstructorShirt1 constShirt = new ConstructorShirt1(‘R’);6 char colorCode;78 colorCode = constShirt.getColorCode();910 System.out.println(“Color Code: “ + colorCode);11 }12 }

Page 257: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 36 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The Default Constructor

• Example:ConstructorShirt constShirt = new ConstructorShirt();

• Example:1 public class DefaultShirt {23 private int shirtID = 0; // Default ID for the shirt4 private String description = “-description required-”; // default56 // The color codes are R=Red, B=Blue, G=Green, U=Unset7 private char colorCode = ‘U’;8 private double price = 0.0; // Default price for all items9 private int quantityInStock = 0; // Default quantity for all items1011 public DefaultShirt() {12 colorCode = ‘R’;13 }14

Page 258: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 37 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

15 public char getColorCode() {16 return colorCode;17 }18 } // end of class19

Page 259: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 38 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Overloading Constructors

Example:

1 public class ConstructorShirt2 {23 private int shirtID = 0; // Default ID for the shirt4 private String description = “-description required-”; // default56 // The color codes are R=Red, B=Blue, G=Green, U=Unset7 private char colorCode = ‘U’;8 private double price = 0.0; // Default price for all items9 private int quantityInStock = 0; // Default quantity for all items1011 public ConstructorShirt2() {12 colorCode = ‘R’;13 }1415 public ConstructorShirt2 (char startingCode) {1617 switch (startingCode) {

Page 260: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 39 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 case ‘R’:19 case ‘G’:20 case ‘B’:21 colorCode = startingCode;22 break;23 default:24 System.out.println(“Invalid colorCode. Use R, G, or B”);25 }26 }2728 public ConstructorShirt2 (char startingCode, int startingQuantity) {2930 switch (startingCode) {31 case ‘R’:32 colorCode = startingCode;33 break;34 case ‘G’:35 colorCode = startingCode;36 break;37 case ‘B’:38 colorCode = startingCode;39 break;

Page 261: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 40 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

40 default:41 System.out.println(“Invalid colorCode. Use R, G, or B”);42 }4344 if (startingQuantity > 0 || startingQuantity < 2000) {45 quantityInStock = startingQuantity;46 }4748 else {49 System.out.println(“Invalid quantity. Must be > 0 or < 2000”);50 }51 }5253 public char getColorCode() {54 return colorCode;55 }565758 public int getQuantityInStock() {59 return quantityInStock;60 }6162 } // end of class63

Page 262: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 41 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Overloading Constructors

Example:

1 public class ConstructorShirt2Test {23 public static void main (String args[]) {45 ConstructorShirt2 constShirtFirst = new ConstructorShirt2();6 ConstructorShirt2 constShirtSecond = new ConstructorShirt2(‘G’);7 ConstructorShirt2 constShirtThird = new ConstructorShirt2(‘B’,1000);89 char colorCode;10 int quantity;1112 colorCode = constShirtFirst.getColorCode();13 System.out.println(“Object 1 Color Code: “ + colorCode);1415 colorCode = constShirtSecond.getColorCode();16 System.out.println(“Object 2 Color Code: “ + colorCode);

Page 263: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 42 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

1718 colorCode = constShirtThird.getColorCode();19 quantity = constShirtThird.getQuantityInStock();20 System.out.println(“Object 3 Color Code: “ + colorCode);21 System.out.println(“Object 3 Quantity on Hand: “ + quantity);22 }23 }

Page 264: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 9, slide 43 of 43Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 2: Using Constructors

• Objectives

• Tasks

• Discussion

Page 265: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language

Module 10

Creating and Using Arrays

Page 266: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 2 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Overview

• Objectives:

• Code one-dimensional arrays

• Set array values using the length attribute and aloop

• Pass arguments to the main method for use in aprogram

• Create two-dimensional arrays

• Relevance

Page 267: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 3 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Creating One-Dimensional Arrays

Example:

int ageOne = 27;int ageTwo = 12;int ageThree = 82;int ageFour = 70;int ageFive = 54;int ageSix = 6;int ageSeven = 1;int ageEight = 30;int ageNine = 34;int ageTen = 42;

Page 268: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 4 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Creating One-Dimensional Arrays

425566 15 200 1 1151 7205 8000 609834

Hugh

Mongus

AaronDatires

Hugh

Morris

Stan

Ding

Albert

Kerkie

Carrie

DeKeys

Walter

Mellon

MoeDeLawn

Array of int

Array of Shirts

Array of Strings

Page 269: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 5 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Declaring a One-Dimensional Array

• Syntax:type [] array_identifier ;

• Examples:char [] status;int [] ages;

Shirt [] shirts;String [] names;

Page 270: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 6 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Instantiating a One-Dimensional Array

• Syntax:array_identifier = new type [ length ];

• Examples:status = new char [20];ages = new int [5];

names = new String [7];shirts = new Shirt [3];

Page 271: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 7 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Initializing a One-Dimensional Array

• Syntax:array_identifier [ index ] = value ;

• Examples:ages[0] = 19;ages[1] = 42;ages[2] = 92;ages[3] = 33;ages[4] = 46;

shirts[0] = new Shirt();shirts[1] = new Shirt(‘G’);shirts[2] = new Shirt(‘G’, 1000);

Page 272: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 8 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Declaring, Instantiating, and InitializingOne-Dimensional Arrays

• Syntax:type [] array_identifier = { comma-separated list of values or expressions };

• Examples:int [] ages = {19, 42, 92, 33, 46};

Shirt [] shirts = {new Shirt(), new Shirt(121,”Work Shirt”, ‘B’, 12.95),new Shirt(122,”Flannel Shirt”, ‘G’, 22.95)};

int [] ages;ages = {19, 42, 92, 33, 46};

Page 273: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 9 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Accessing a Value Within an Array

Examples:

status[0] = ’3’;names[1] = "Fred Smith";ages[1] = 19;prices[2] = 9.99F;

char s = status[0];String name = names [1];int age = ages[1];double price = prices[2];

Page 274: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 10 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Storing Primitive Variables and Arrays ofPrimitives in Memory

char size = 'L'char [] sizes = {'S','M','L'};

L

0x334009sizes

size

Heap MemoryStack Memory

S

M

L

0x334009

2

0

1

Page 275: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 11 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Storing Reference Variablesand Arrays of References in

Memory1 Shirt myShirt = new Shirt() ;

2 Shirt [] shirts = {new Shirt(), new Shirt(), new Shirt()} ;

0x99f311

0x179009

myShirt

shirts

Heap MemoryStack Memory

0x99f311

shirtID

price

colorCode

0

0.0

U

0x00099

0x00327

0x00990

0x179009

0

1

2

0x00099

shirtID

price

colorCode

0

0.0

U

0x00327

shirtID

price

colorCode

0

0.0

U

0x00990

shirtID

price

colorCode

0

0.0

U

Page 276: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 12 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 1: Creating and UsingOne-Dimensional Arrays

• Objectives

• Tasks

• Discussion

Page 277: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 13 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 2: Viewing Arrays Using theObjectTool

• Objectives

• Tasks

• Discussion

Page 278: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 14 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Setting Array Values Using the lengthAttribute and a Loop

Example:

int [] myArray;myArray = new int[100];

for (int count = 0; count < myArray.length; count++) {myArray[count] = count;

}

Page 279: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 15 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 3: Using Loops and Arrays

• Objectives

• Tasks

• Discussion

Page 280: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 16 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Using the args Array in the main Method

• Example:public static void main (String args[]);

• Example:1 public class ArgsTest {23 public static void main (String args[]) {45 System.out.println(“args[0] is “ + args[0]);6 System.out.println(“args[1] is “ + args[1]);7 }8 }

Page 281: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 17 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Converting String Arguments to OtherTypes

Example:

int ID = Integer.parseInt(args[0]);

Page 282: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 18 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 4: Parsing the args[] Array

• Objectives

• Tasks

• Discussion

Page 283: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 19 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Describing Two-Dimensional Arrays

Sunday

Monday

Tuesday

Wedsday

Thursday

Friday

Saturday

Week 1

Week 2

Week 3

Week 4

Page 284: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 20 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Declaring a Two-Dimensional Array

• Syntax:type [][] array_ identifier;

• Example:int [][] yearlySales;

Page 285: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 21 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Instantiating a Two-Dimensional Array

• Syntax:array_ identifier = new type [ number_of_arrays ] [length] ;

• Example:// Instantiates a two-dimensional array: 5 arrays of 4 elements eachYearlySales = new int[5][4];

Quarter 1 Quarter 2 Quarter 3 Quarter 4

Year 1

Year 2

Year 3

Year 4

Year 5

Page 286: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 22 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Initializing a Two-Dimensional Array

Example:

yearlySales[0][0] = 1000;yearlySales[0][1] = 1500;yearlySales[0][2] = 1800;yearlySales[1][0] = 1000;yearlySales[2][0] = 1400;yearlySales[3][3] = 2000;

Quarter 1 Quarter 2 Quarter 3 Quarter 4

Year 1 1000 1500 1800

Year 2 1000

Year 3 1400

Year 4 2000

Year 5

Page 287: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 10, slide 23 of 23Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 5: Creating and UsingTwo-Dimensional Arrays

• Objectives

• Tasks

• Discussion

Page 288: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language

Module 11

Implementing Inheritance

Page 289: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 2 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Overview

• Objectives:

• Define and test your use of inheritance

• Explain abstraction

• Explicitly identify class libraries used in your code

• Relevance

Page 290: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 3 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Inheritance

Hat Sock

hatIDpricedescriptioncolorCode R=Red, B=Blue, G=GreenquantityInStock

sockIDpricedescriptioncolorCode R=Red, B=Blue, G=GreenquantityInStock

calculateHatID()displayHatInformation()

calculateSockID()displaySocksInformation()

Pant Shirt

pantIDpricesizegender M=Male, F=FemaledescriptioncolorCode B=Blue, T=TanquantityInStock

shirtIDpricedescriptioncolorCode R=Red, B=Blue, G=GreenquantityInStock

calculatePantID()displayPantInformation()

calculateShirtID()displayShirtInformation()

Page 291: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 4 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Superclasses and Subclasses

Mammal

Warm Blooded

Breathes Air

Whale

Flukes

Flippers

Page 292: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 5 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Testing Superclass and SubclassRelationships

Clothing

Description

Price

Quantity

Shoes Socks HatShirt

Page 293: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 6 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Modeling Superclasses and Subclasses

Hat:Clothing Sock:Clothing

colorCode R=Red, B=Blue,G=Green

colorCode R=Red, B=Blue,G=Green

displayHatInformation() displaySockInformation()

Pant:Clothing Shirt:Clothing

sizegender M=Male, F=FemalecolorCode B=Blue, T=Tan

sizecolorCode R=Red, B=Blue,G=Green

displayClothingInformation() displayShirtInformation()

Page 294: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 7 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Modeling Superclasses and Subclasses

Clothing

IDpricedescriptionquantityInStock

calculateID()

Page 295: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 8 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Declaring a Subclass

• Syntax:[class_modifier] class class_identifier extends superclass_identifier

• Example:1 public class Shirt extends Clothing {23 // The color codes are R=Red, B=Blue, G=Green, U=Unset4 public char colorCode = ‘U’;56 // This method displays the values for an item7 public void displayShirtInformation() {89 System.out.println(“Shirt ID: “ + getID());10 System.out.println(“Shirt description:” + getDescription());11 System.out.println(“Color Code: “ + colorCode);12 System.out.println(“Shirt price: “ + getPrice());13 System.out.println(“Quantity in stock: “ + getQuantityInStock());1415 } // end of display method16 } // end of class

Page 296: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 9 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Declaring a Subclass

Example:

1 public class Clothing {23 private int ID = 0; // Default ID for all clothing4 private String description = "-description required-"; // default56 private double price = 0.0; // Default price for all clothing7 private int quantityInStock = 0; // Default quantity for all clothing89 // This method displays the values for an item10 public void calculateID() {11 int uniqueID = 0;12 ++uniqueID;1314 ID = uniqueID;15 }1617 public int getID() {

Page 297: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 10 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

18 return ID;19 }2021 public void setDescription(String d) {22 description = d;23 }2425 public String getDescription() {26 return description;27 }2829 public void setPrice(double p) {30 price = p;31 }3233 public double getPrice() {34 return price;35 }3637 public void setQuantityInStock(int q) {38 quantityInStock = q;39 }

Page 298: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 11 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

4041 public int getQuantityInStock() {42 return quantityInStock;43 }4445 } // end of class

Page 299: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 12 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 1: Creating Superclasses andSubclasses

• Objectives

• Tasks

• Discussion

Page 300: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 13 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Exercise 2: Viewing Class HierarchiesUsing the ObjectTool

• Objectives

• Tasks

• Discussion

Page 301: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 14 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Abstraction

• What is abstraction?

• Abstraction in the DirectClothing, Inc. case study

Page 302: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 15 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Classes in the Java API

• Implicitly available classes: the java.lang package

• Importing and qualifying classes:

• The java.awt package

• The java.applet package

• The java.net package

• The java.io package

• The java.util package

Page 303: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 16 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The import Statement

• Syntax:import package_name.class_name ;import package_name .*

• Example:import java.awt.*;public class MyPushButton1 extends Button { // class statements

}

Page 304: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language Module 11, slide 17 of 17Copyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Specifying the Fully Qualified Name

• Syntax:package_name . class_name

• Example:public class MyPushButton2 extends java.awt.Button { // class statements}

Page 305: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Fundamentals of the Java™ Programming Language iCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Course Contents

About This Course ....................................................................................... Preface-ivCourse Goals .................................................................................................................................Preface-vCourse Map ..................................................................................................................................Preface-viTopics Not Covered ...................................................................................................................Preface-viiHow Prepared Are You? ......................................................................................................... Preface-viiiIntroductions ............................................................................................................................... Preface-ixHow to Use the Icons ................................................................................................................... Preface-xTypographical Conventions .....................................................................................................Preface-xiiAdditional Conventions ...........................................................................................................Preface-xiv

Explaining Java™ Technology ............................................................................... 1-1Overview .................................................................................................................................................. 1-2Key Concepts of the Java Programming Language ........................................................................... 1-3Object-Oriented ....................................................................................................................................... 1-4Distributed ............................................................................................................................................... 1-6Simple ....................................................................................................................................................... 1-7Multithreaded .......................................................................................................................................... 1-8Secure ........................................................................................................................................................ 1-9Platform-Dependent Programs ........................................................................................................... 1-10Platform-Independent .......................................................................................................................... 1-14Identifying Java Technology Product Groups .................................................................................. 1-15Using the Java™ 2 Platform, Standard Edition SDK Components ............................................... 1-16The Product Life Cycle (PLC) Stages ................................................................................................. 1-17The Analysis Stage ................................................................................................................................ 1-18The Design Stage ................................................................................................................................... 1-19The Development Stage ....................................................................................................................... 1-20The Testing Stage .................................................................................................................................. 1-21

Page 306: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language iiCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

The Implementation Stage ................................................................................................................... 1-22The Maintenance Stage ........................................................................................................................ 1-23The EOL Stage ....................................................................................................................................... 1-24

Analyzing a Problem and Designing a Solution .................................................... 2-1Overview .................................................................................................................................................. 2-2Analyzing a Problem Using Object-Oriented Analysis ..................................................................... 2-3Identifying a Problem Domain ............................................................................................................. 2-4Identifying Objects .................................................................................................................................. 2-5Additional Criteria for Recognizing Objects ....................................................................................... 2-7Possible Objects in the DirectClothing

Case Study ............................................................................................................................................. 2-8Identifying Object Attributes and Operations .................................................................................... 2-9Object With Another Object as an Attribute ..................................................................................... 2-10Possible Attributes and Operations in the DirectClothing, Inc. Case Study ................................ 2-11Case Study Solution .............................................................................................................................. 2-12Exercise 1: Analyzing a Problem Domain ......................................................................................... 2-15Designing Classes ................................................................................................................................. 2-16Class and Resulting Objects ................................................................................................................ 2-17Modeling Classes .................................................................................................................................. 2-18Exercise 2: Designing a Solution ......................................................................................................... 2-19

Developing and Testing a Java Technology Program .......................................... 3-1Overview .................................................................................................................................................. 3-2Identifying the Components of a Class ................................................................................................ 3-3Identifying the Components of a Class ................................................................................................ 3-4The Class Declaration ............................................................................................................................. 3-7Variable Declarations and Assignments .............................................................................................. 3-8Comments ................................................................................................................................................ 3-9Methods .................................................................................................................................................. 3-10

Page 307: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language iiiCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Creating and Using a Test Class ......................................................................................................... 3-11The main Method .................................................................................................................................. 3-12Compiling a Program ........................................................................................................................... 3-13Executing (Testing) a Program ............................................................................................................ 3-14Debugging Tips ..................................................................................................................................... 3-15Exercise: Writing, Compiling, and Testing a Basic Program .......................................................... 3-16

Declaring, Initializing, and Using Variables ........................................................... 4-1Overview .................................................................................................................................................. 4-2Identifying Variable Use and Syntax ................................................................................................... 4-3Uses for Variables ................................................................................................................................... 4-5Variable Declaration and Initialization ................................................................................................ 4-6Describing Primitive Data Types .......................................................................................................... 4-7Integral Primitive Types ........................................................................................................................ 4-8Floating Point Primitive Types ........................................................................................................... 4-10Textual Primitive Type ......................................................................................................................... 4-11Logical Primitive Type ......................................................................................................................... 4-12Naming a Variable ................................................................................................................................ 4-13Assigning a Value to a Variable .......................................................................................................... 4-15Declaring and Initializing Several Variables in One Line of Code ................................................ 4-16Additional Ways to Declare Variables and Assign Values to Variables ....................................... 4-17Constants ................................................................................................................................................ 4-19Storing Primitives and Constants

in Memory ........................................................................................................................................... 4-20Exercise 1: Using Primitive Type Variables in a Program .............................................................. 4-21Standard Mathematical Operators ..................................................................................................... 4-22Increment and Decrement Operators ................................................................................................. 4-24Operator Precedence ............................................................................................................................ 4-27Using Parentheses ................................................................................................................................. 4-28Using Promotion and Type Casting ................................................................................................... 4-29

Page 308: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language ivCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Promotion ............................................................................................................................................... 4-30Type Casting .......................................................................................................................................... 4-31Compiler Assumptions for Integral and Floating Point Data Types ............................................ 4-33Floating Point Data Types and Assignment ..................................................................................... 4-34Example .................................................................................................................................................. 4-35Exercise 2: Using Operators and

Type Casting ....................................................................................................................................... 4-36

Creating and Using Objects .................................................................................... 5-1Overview .................................................................................................................................................. 5-2Declaring Object References, Instantiating Objects, and Initializing Object References .............. 5-3Declaring Object Reference Variables .................................................................................................. 5-5Instantiating an Object ........................................................................................................................... 5-6Initializing Object Reference Variables ................................................................................................ 5-7Using an Object Reference Variable to Manipulate Data .................................................................. 5-8Storing Object Reference Variables in Memory .................................................................................. 5-9Assigning an Object Reference From One Variable to Another ..................................................... 5-10Exercise 1: Using the ObjectTool to Create and Manipulate Objects ............................................ 5-11Exercise 2: Creating a Test Class ......................................................................................................... 5-12Using the String Class ........................................................................................................................ 5-13Storing String Objects in Memory .................................................................................................... 5-14Using Reference Variables for

String Objects .................................................................................................................................. 5-15Exercise 3: Using the String Class .................................................................................................... 5-16Exercise 4: Examining String Objects With the ObjectTool .......................................................... 5-17Investigating the Java Class Libraries ................................................................................................ 5-18Using the Java Class Library Specification to Learn About a Method .......................................... 5-20Exercise 5: Using the Class Library Specification ............................................................................. 5-21

Page 309: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language vCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Using Operators and Decision Constructs ............................................................ 6-1Overview .................................................................................................................................................. 6-2Using Relational and Conditional Operators ..................................................................................... 6-3The Elevator Example ............................................................................................................................ 6-4The Elevator Test Class .......................................................................................................................... 6-6Relational Operators ............................................................................................................................... 6-7Testing Equality Between Strings ......................................................................................................... 6-8Conditional Operators ............................................................................................................................ 6-9The if Construct ................................................................................................................................... 6-10Nested if Statements ........................................................................................................................... 6-15The if/else Construct ....................................................................................................................... 6-19The if/else Construct ....................................................................................................................... 6-20Chaining if/else Constructs ............................................................................................................. 6-24Exercise 1: Using if and if/else Constructs .................................................................................. 6-27Using the switch Construct ................................................................................................................ 6-28When to Use switch Constructs ........................................................................................................ 6-31Exercise 2: Using the switch Construct ............................................................................................ 6-32

Using Loop Constructs ........................................................................................... 7-1Overview .................................................................................................................................................. 7-2Creating while Loops ............................................................................................................................ 7-3Nested while Loops ............................................................................................................................... 7-7Exercise 1: Using the while Loop ......................................................................................................... 7-9Developing a for Loop ........................................................................................................................ 7-10Nested for Loops ................................................................................................................................. 7-14Exercise 2: Using the for Loop ........................................................................................................... 7-15Coding a do/while Loop ..................................................................................................................... 7-16Nested do/while Loops ...................................................................................................................... 7-20Comparing Loop Constructs ............................................................................................................... 7-22Exercise 3: Using the do/while Loop ................................................................................................ 7-23

Page 310: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language viCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Developing and Using Methods .............................................................................. 8-1Overview .................................................................................................................................................. 8-2Creating and Invoking Methods ........................................................................................................... 8-3The Basic Form of a Method .................................................................................................................. 8-4Invoking a Method From a Different Class ......................................................................................... 8-5Calling and Worker Methods ................................................................................................................ 8-6Invoking a Method in the Same Class .................................................................................................. 8-7Guidelines for Invoking Methods ...................................................................................................... 8-10Passing Arguments and Returning Values ....................................................................................... 8-11Declaring Methods With Arguments ................................................................................................. 8-12The main Method .................................................................................................................................. 8-13Invoking Methods With Arguments .................................................................................................. 8-14Declaring Methods With Return Values ............................................................................................ 8-16Returning a Value ................................................................................................................................. 8-17Receiving Return Values ...................................................................................................................... 8-18Advantages of Method Use ................................................................................................................. 8-20Exercise 1: Using Arguments and Return Values ............................................................................ 8-21Creating Static Methods and Variables ......................................................................................... 8-22Static Methods and Variables in the Java API .................................................................................. 8-25Using Method Overloading ................................................................................................................. 8-27Method Overloading and the Java API ............................................................................................. 8-30Uses for Method Overloading ............................................................................................................. 8-31Exercise 2: Using Overloaded Methods ............................................................................................. 8-36

Implementing Encapsulation and Constructors ................................................... 9-1Overview .................................................................................................................................................. 9-2Using Encapsulation ............................................................................................................................... 9-3The public Modifier .............................................................................................................................. 9-4The private Modifier ............................................................................................................................ 9-8Interface and Implementation ............................................................................................................. 9-12

Page 311: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language viiCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

An Encapsulated Elevator ................................................................................................................... 9-21Sample Output ...................................................................................................................................... 9-28Exercise 1: Writing Encapsulated Classes ......................................................................................... 9-29Describing Variable Scope ................................................................................................................... 9-30How Instance Variables and Local Variables Appear in Memory ................................................ 9-32Creating Constructors .......................................................................................................................... 9-33The Default Constructor ...................................................................................................................... 9-36Overloading Constructors ................................................................................................................... 9-38Exercise 2: Using Constructors ............................................................................................................ 9-43

Creating and Using Arrays .................................................................................... 10-1Overview ................................................................................................................................................ 10-2Creating One-Dimensional Arrays ..................................................................................................... 10-3Declaring a One-Dimensional Array ................................................................................................. 10-5Instantiating a One-Dimensional Array ............................................................................................ 10-6Initializing a One-Dimensional Array ............................................................................................... 10-7Declaring, Instantiating, and Initializing One-Dimensional Arrays ............................................. 10-8Accessing a Value Within an Array ................................................................................................... 10-9Storing Primitive Variables and Arrays of Primitives in Memory .............................................. 10-10Storing Reference Variables and Arrays of References in Memory ............................................ 10-11Exercise 1: Creating and Using

One-Dimensional Arrays ................................................................................................................ 10-12Exercise 2: Viewing Arrays Using the ObjectTool ......................................................................... 10-13Setting Array Values Using the length Attribute and a Loop .................................................... 10-14Exercise 3: Using Loops and Arrays ................................................................................................. 10-15Using the args Array in the main Method ..................................................................................... 10-16Converting String Arguments to Other Types ............................................................................. 10-17Exercise 4: Parsing the args[] Array .............................................................................................. 10-18Describing Two-Dimensional Arrays .............................................................................................. 10-19Declaring a Two-Dimensional Array ............................................................................................... 10-20

Page 312: SL-110 - pudn.comread.pudn.com/downloads89/ebook/340510/Fundamentals of the Java... · Fundamentals of the Java™ Programming Language Fundamentals of the Java™ Programming Language

Sun Educational Services

Fundamentals of the Java™ Programming Language viiiCopyright 2002 Sun Microsystems, Inc. All Rights Reserved. Enterprise Services, Revision D

Instantiating a Two-Dimensional Array .......................................................................................... 10-21Initializing a Two-Dimensional Array ............................................................................................. 10-22Exercise 5: Creating and Using

Two-Dimensional Arrays ............................................................................................................... 10-23

Implementing Inheritance ...................................................................................... 11-1Overview ................................................................................................................................................ 11-2Inheritance .............................................................................................................................................. 11-3Superclasses and Subclasses ................................................................................................................ 11-4Testing Superclass and Subclass Relationships ................................................................................ 11-5Modeling Superclasses and Subclasses ............................................................................................. 11-6Declaring a Subclass ............................................................................................................................. 11-8Exercise 1: Creating Superclasses and Subclasses .......................................................................... 11-12Exercise 2: Viewing Class Hierarchies Using the ObjectTool ....................................................... 11-13Abstraction ........................................................................................................................................... 11-14Classes in the Java API ....................................................................................................................... 11-15The import Statement ........................................................................................................................ 11-16Specifying the Fully Qualified Name ............................................................................................... 11-17