oracle10g java programming - electronic presentation.pdf

Upload: jurgen1871

Post on 05-Jul-2018

238 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    1/434

    Oracle10g: Java Programming

    Electronic Presentation

    D17249GC11

    Edition 1.1

     August 2004

    D39817

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    2/434

    Copyright © 2004, Oracle. All r ights reserved.

    This documentation contains proprietary information of Oracle Corporation. It is provided under a

    license agreement containing restrictions on use and disclosure and is also protected by copyright

    law. Reverse engineering of the software is prohibited. If this documentation is delivered to a U.S.

    Government Agency of the Department of Defense, then it is delivered with Restricted Rights and the

    following legend is applicable:

    Restricted Rights Legend

    Use, duplication or disclosure by the Government is subject to restrictions for commercial computer

    software and shall be deemed to be Restricted Rights software under Federal law, as set forth in

    subparagraph (c)(1)(ii) of DFARS 252.227-7013, Rights in Technical Data and Computer Software

    (October 1988).

    This material or any portion of it may not be copied in any form or by any means without the express

    prior written permission of Oracle Corporation. Any other copying is a violation of copyright law and

    may result in civil and/or criminal penalties.

    If this documentation is delivered to a U.S. Government Agency not within the Department of

    Defense, then it is delivered with “Restricted Rights,” as defined in FAR 52.227-14, Rights in Data-

    General, including Alternate III (June 1987).

    The information in this document is subject to change without notice. If you find any problems in the

    documentation, please report them in writing to Education Products, Oracle Corporation, 500 Oracle

    Parkway, Box SB-6, Redwood Shores, CA 94065. Oracle Corporation does not warrant that this

    document is error-free.

     All references to Oracle and Oracle products are trademarks or registered trademarks of Oracle

    Corporation.

     All other products or company names are used for identification purposes only, and may be

    trademarks of their respective owners.

    Authors

    Jeff Gallus

    Glenn Stokol

    Technical Contributors

    and Reviewers

    Kenneth Cooper Peter Driver Christian DugasCraig Hollister Chika Izumi

    Pete LaseauGlenn MaslenMonica MotleyGayathri Rajagopal

    Publisher

    Poornima G

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    3/434

    Copyright © 2004, Oracle. All rights reserved.

    Introduction

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    4/434

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

    Objectives

     After completing this course, you should be able to do

    the following:• Write stand-alone applications with the Java

    programming language

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

    by using Oracle JDeveloper 10g

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

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

    Course Overview

    • This course teaches you how to write Java

    applications.• You also learn how to build, debug, and deploy

    applications by using Oracle JDeveloper 10g.

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

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    6/434Copyright © 2004, Oracle. All rights reserved.

    Introducing the Java

    and Oracle Platforms

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

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

    Objectives

     After completing this lesson, you should be able to do

    the following:• Identify the key elements of Java

    • Describe the Java Virtual Machine (JVM)

    • Examine how Java is used to build applications• Identify the key components of the J2SE Java

    Development Kit (known as JDK or SDK)

    • Describe Java deployment options

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

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

    What Is Java?

    Java:

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

    consumer electronics

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

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

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

    Key Benefits of Java

    • Object-oriented

    • Interpreted and platform-independent• Dynamic and distributed

    • Multithreaded

    • Robust and secure

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

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

     An Object-Oriented Approach

    • Objects and classes

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

    • Class models elaborate:

     –  Existing classes and objects –  Behavior, purpose, and structure

     –  Relationships between classes

     –  Relationships between run-time objects

    • Same models exist throughout the project.

     Analysis ImplementationIntegrationand testing

    Design

    CLASS MODELS

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

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

    Platform Independence

    • Java source code is stored as text in a .java file.

    • The .java file is compiled into .class files.•  A .class fi le contains Java bytecodes

    (instructions).

    • The bytecodes are interpreted at run time. –  The Java .class fi le is the executable code.

    Compile

     Movie.java

    JVM

    Running program Movie.class

    (javac) (java)

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    12/4341-7 Copyright © 2004, Oracle. All rights reserved.

    Using Java with Enterprise

    Internet ComputingWeb

    server 

     Application

    server 

    Presentation Businesslogic

    • Servlets

    • JavaServer 

    Pages (JSPs)

    • Enterprise

    JavaBeans (EJB)

    • CORBA

    Client Data

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    13/4341-8 Copyright © 2004, Oracle. All rights reserved.

    Using the Java Virtual Machine

    Operating system

    JVM

     Application

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    14/4341-9 Copyright © 2004, Oracle. All rights reserved.

    How Does JVM Work?

    • The class loader loads all required classes.

     –  JVM uses a CLASSPATH setting to locate class files.• JVM Verifier checks for il legal bytecodes.

    • JVM Verifier executes bytecodes.

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

    dereferenced object back to the OS.

     –  JVM handles Garbage collection.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    15/434

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

    Benefits of Just-In-Time (JIT) Compilers

    JIT compilers:

    • Improve performance•  Are useful if the same bytecodes are executed

    repeatedly

    • Translate bytecodes to native instruction• Optimize repetitive code, such as loops

    • Use Java HotSpot VM for better performance and

    reliability

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    16/434

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

    Implementing Security

    in the Java Environment

    Interface-specific access

    Class loader 

    Bytecode verifier 

    Language and compiler 

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    17/434

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

    Deployment of Java Applications

    • Client-side deployment:

     –  JVM runs stand-alone applications from thecommand line.

     –  Classes load from a local disk, eliminating the need

    to load classes over a network.

    • Server-side deployment:

     –  Serves multiple clients from a single source

     –  Is compatible with a multit ier model for Internet

    computing.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    18/434

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

    Using Java with Oracle 10g

    Oracle

    database

    Web

    server Client

     Application

    server 

    PresentationBusiness

    logic

    Data

    Oracle

     Application Server 

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    19/434

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

    Java Software Development Kit

    Sun Java J2SE (known as JDK and Java SDK)

    provides:• Compiler (javac)

    • Core class library

     –   classes.zip

     –   rt.jar

    • Debugger (jdb)

    • Bytecode interpreter: The JVM (java)

    • Documentation generator (javadoc)

    • Java Archive utility (jar)

    • Others

    J2SE

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    20/434

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

    Using the Appropriate Development Kit

    Java2 comes in three sizes:

    • J2ME (Micro Edition): Version specifically targetedat the consumer space

    • J2SE (Standard Edit ion): Complete ground-up

    development environment for the Internet

    • J2EE (Enterprise Edition): Everything in the J2SE

    plus an application server and prototyping tools

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    21/434

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

    Integrated Development Environment

    Development

    UML

     ADF

    XML

    SCM

    Synchronized changes

    Debug

    Exchange

    Database

    HTML

    Deployment

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    22/434

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

    Exploring the JDeveloper Environment

    System Navigator Code Editor Property Inspector  

    Component Palette

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    23/434

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

    Oracle10g Products

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    24/434

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

    Summary

    In this lesson, you should have learned the following:

    • Java code is compiled into platform-independentbytecodes.

    • Bytecodes are interpreted by JVM.

    • Java applications can be stand-alone orimplemented across an Internet-computing model.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    25/434

    Copyright © 2004, Oracle. All rights reserved.

    Defining Object-Oriented Principles

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    26/434

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

    Objectives

     After completing this lesson, you should be able to do

    the following:• Define objects and explain how they are used

    •  Associate objects so that they can communicate

    and interact via messages

    • Define classes and explain how they are used

    • Describe object-oriented (OO) principles: classes,

    objects, and methods

    • Describe the value of Reusable Software

    Components

    • Examine the OO model that is used in this course

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    27/434

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

    What Is Modeling?

    • Models perform the following functions:

     –  Describe exactly what the business needs –  Facil itate discussion

     –  Prevent mistakes

    • Modeling and implementation are treated

    separately.

    • Before coding can begin, the model must be

    correct.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    28/434

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

    What Are Classes and Objects?

    •  A class:

     –  Models an abstraction of objects –  Defines the attr ibutes and behaviors of

    objects

     –  Is the blueprint that defines an object

    •  An object:

     –  Is stamped out of the class mold

     –  Is a single instance of a class

     –  Retains the structure and behavior of a class

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    29/434

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

     An Object’s Attributes Maintain Its State

    • Objects have knowledge about their current state.

    • Each piece of knowledge is called an attribute. –  The values of attributes dictate the objects’ state.

     Attribute: Ink amount

     Attribute: Cash available

    Object: My blue pen

    Object: Acme Bank ATM

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    30/434

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

    Objects Have Behavior 

    •  An object exists to provide behavior (functionality)

    to the system.• Each distinct behavior is called an operation.

    Operation: Write

    Operation: Withdraw

    Object: My blue pen

    Object: Acme Bank ATM

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    31/434

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

    Objects Are Modeled as Abstractions

    •  A Java object is modeled as an abstract

    representation of a real-world object.• Model only those attributes and operations that

    are relevant to the context of the problem.

    Real-world attr ibutes/operations that you may not want to model:

    •  Attributes: Ink color 

    • Operations: Refil l, change color, point, write

    •  Attributes: Model, manufacturer, price

    • Operations: Change price

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

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    32/434

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

     A PC may be

    an object.

     A PC may have a

    keyboard, mouse, and

    network card, all of which

    may be objects.

     A PC may have a

    CD drive, which

    may be an object.

    Defining Object Composition

    • Objects can be composed of other objects.

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

    aggregation.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    33/434

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

    The Donut Diagram

    getAge()

    Client or sender 

    Person

    Messagenameaddress

    birthdate

    getName

    setBirthdate getAge

    getAddress setAddress

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    34/434

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

    Guided Practice:

    Spot the Operations and Attributes

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    35/434

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

    Collaborating Objects

    Collaborating objects work together to complete a task

    and form the basis of an application system.

    •  All methods are defined within a class and are not

    defined globally as in traditional languages.

    •  All objects are created from classes and contain

    all the attr ibutes and methods of that class.

    • Objects must associate with each other to

    collaborate on common tasks.

    •  Associated objects communicate by sendingmessages.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    36/434

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

    Objects Interact Through Messages

    • Objects communicate by sending messages.

    •  A sending object must be associated with orlinked to the receiving object.

    • The message sender requests the receiver toperform the operation that is named in themessage.

    • This communication is similar to calling aprocedure:

     –  The sender calls a method of the receiver.

     –  The receiver executes the called method.

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

     –  write (myPen): Traditional structured

    programming

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    37/434

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

    When you create my blue pen, you do not have to

    specify its operations or attributes. You simply

    say what class it belongs to.

    What Is a Class?

    •  A class is a template for objects.

    •  A class definition specifies the operations andattributes for all instances of that class.

    •  A class is used to manage complexity.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    38/434

    C i Cl d Obj

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    39/434

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

    Comparing Classes and Objects

    • Classes are static definitions that you can use to

    understand all the objects of that class.

    • Objects are the dynamic entit ies that exist in the

    real world and your simulation of it.

    • Caution: OO people almost always use the words

    classes and objects interchangeably; you mustunderstand the context to differentiate between

    the two meanings.

    Wh t I E l ti ?

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    40/434

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

    What Is Encapsulation?

    Encapsulation hides the internal structure and

    operations of an object behind an interface.

    •  A bank ATM is an object that gives its users cash.

     –  The ATM hides (encapsulates) the actual operation

    of withdrawal from the user.

     –  The interface (way to operate the ATM) is providedby the keyboard functions, screen, cash dispenser,

    and so on.

     –  Bypassing the encapsulation is bank robbery.

    • Bypassing encapsulation in object-oriented

    programming is impossible.

    Wh t I I h it ?

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    41/434

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

    What Is Inheritance?

    • There may be a commonality between different

    classes.

    • Define the common properties in a superclass.

    • The subclasses use inheritance to include those

    properties.

    Savings account Checking account Account

    U i th “ I Ki d f” R l ti hi

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    42/434

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

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

    •  A subclass object

    “ is-a-kind-of”

    superclass

    object.

    •  A subclass must

    have all theattributes and

    behaviors of the

    superclass.

    Savings account

     Account Pen

    Pencil

    What Is Polymorphism?

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    43/434

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

    What Is Polymorphism?

    Polymorphism refers to:

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

    meaning to different objects. However, each object

    implements the operation in a unique way.

    • The principles of inheritance and object

    substitution.

    Load passengers

    Architecture Rules for Reuse

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    44/434

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

     Architecture Rules for Reuse

    Write code that contains:

    • Events that can interact with your Java application• Properties that can be exposed

    • Methods that can be invoked

    Write code that supports:• Introspection or reflection

    • Customization

    • Persistence

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    45/434

    Order Entry UML Diagram

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    46/434

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

    Order Entry UML Diagram

    Summary

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    47/434

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

    Summary

    In this lesson, you should have learned the following:

    •  An object is an abstraction of a real-world object.•  A class is a template or blueprint for objects.

    • Classes form inheritance trees: Operations that

    are defined in one class are inherited by all

    subclasses.

    • Polymorphism frees the caller from knowing the

    class of the receiving object.

    Practice 2: Overview

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    48/434

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

    Practice 2: Overview

    This practice covers:

    • Identifying business objects for the Order Entrysystem

    • Identifying methods for the classes

    • Identifying attributes for the classes

    • Searching for inheritance in the classes

    • Examining UML class model for course

    application

    Order Entry System

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    49/434

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

    Order Entry System

    Partial UML Class ModelOrder 

    id: int

    orderDate: Date

    shipDate: Date

    shipMode: StringorderTotal: double

    addItem()

    removeItem()

    setOrderDate()

    getOrderDate()setShipDate()

    :

    OrderItem

    lineNo: int

    quantity: int

    price: double

    getQuantity()

    setQuantity()

    setPrice()

    getPrice()

    getItemTotal()

    :

    Customer 

    name: String

    address: String

    phone: StringgetName()

    setName()

    setAddress()

    getAddress()

    :

    Companycontact: String

    discount: int

    getContact()

    setContact()

    :

    Individual

    licNumber: String

    setLicNumber()

    getLicNumber()

    :

    Product

    id: intname: String

    description: String

    retailPrice: double

    getPrice()

    :

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    50/434

    Copyright © 2004, Oracle. All rights reserved.

    Basic Java Syntax and Coding

    Conventions

    Objectives

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    51/434

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

    Objectives

     After completing this lesson, you should be able to dothe following:

    • Identify the key components of the Java language• Identify the three top-level constructs in a Java

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

    keywords• Identify the basic constructs of a Java program

    • Compile and run a Java application• Examine the JavaBean architecture as an exampleof standard coding practices

    • Use the CLASSPATH variable and understand its

    importance during compile and run time

    Examining Toolkit Components

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    52/434

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

    Examining Toolkit Components

    The J2SE/J2EE from Sun provides:

    • Compiler • Bytecode interpreter 

    • Documentation generator 

    J2SE

    Exploring Packages in J2SE/J2EE

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    53/434

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

    Exploring Packages in J2SE/J2EE

    The J2SE/J2EE from Sun provides standard packages

    for:

    • Language

    • Windowing

    • Input/output

    • Network communication

    J2SE

    Documenting Using the J2SE

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    54/434

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

    g g

    The J2SE/J2EE from Sun provides documentation

    support for:

    • Comments

     –  Implementation

     –  Documentation

    • Documentation generator 

    J2SE

    Contents of a Java Source

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    55/434

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

    •  A Java source file can contain three top-level

    constructs:

     –  Only one package keyword followed by the package

    name, per f ile

     –  Zero or more import statements followed by fully

    qualified class names or “ *” qualified by a packagename

     –  One or more class or interface definitions

    followed by a name and block

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

    Establishing Naming Conventions

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    56/434

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

    g g

    Naming conventions include:

    • Class names

     –  Customer, RentalItem , InventoryItem 

    • File names

     –  Customer.java, RentalItem.java

    • Method names

     –  getCustomerName(), setRentalItemPrice()

    • Package names

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

    More About Naming Conventions

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    57/434

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

    g

    • Variables:

     –  customerName, customerCreditLimit

    • Constants:

     –  MIN_WIDTH, MAX_NUMBER_OF_ITEMS

    • Uppercase and lowercase characters

    • Numerics and special characters

    Defining a Class

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    58/434

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

    Class definitions typically include:

    •  Access modifier 

    • Class keyword

    • Instance fields

    • Constructors

    • Instance methods

    • Class fields

    • Class methods

    Rental Class: Example

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    59/434

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

     public class Rental {

    //Class variablestatic int lateFee;

    // Instance variables

    int rentalId;

    String rentalDate;

    float rentalAmountDue;

    // Instance methods

    float getAmountDue (int rentId) {

    }

    }

    Declaration

    Instance

    variable

    Instance

    method

     Access modifier 

    Creating Code Blocks

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    60/434

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

    • Enclose all class declarations.

    • Enclose all method declarations.

    • Group other related code segments.

     public class SayHello {

     public static void main(String[] args) {

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

    }

    }

    Defining Java Methods

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    61/434

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

    •  Always define within a class.

    • Specify:

     –   Access modifier 

     –  Static keyword

     –   Arguments

     –  Return type

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

    "method-name" ([arguments]) {

    "java code block“ … }

    return

    Examples of a Method

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    62/434

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

     public float getAmountDue (String cust){

    // method variables

    int numberOfDays;float due;

    float lateFee = 1.50F;

    String customerName;

    // method body

    numberOfDays = getOverDueDays();

    due = numberOfDays * lateFee;

    customerName = getCustomerName(cust);return due;

    }

    Declaration

    Method

    variables

    Method

    statements

    Return

    Declaring Variables

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    63/434

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

    • You can declare variables anywhere in a class

    block, and outside any method.

    • You must declare variables before they are used

    inside a method.

    • It is typical to declare variables at the beginning of

    a class block.• The scope or visibility of variables is determined

    in the code block.

    • You must initialize method variables before usingthem.

    • Class and instance variables are automatically

    initialized.

    Examples of Variables

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    64/434

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

    in the Context of a Method public float getAmountDue (String cust) {

    float due = 0;

    int numberOfDays = 0;float lateFee = 1.50F;

    {int tempCount = 1; // new code block

    due = numberOfDays * lateFee;

    tempCount++;

    } // end code block

    return due;}

    Method

    variables

    Temporary

    variables

    Rules for Creating Statements

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    65/434

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

    • Use a semicolon to terminate statements.

    • Define multiple statements within braces.

    • Use braces for control statements.

    What Are JavaBeans?

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    66/434

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

     A JavaBean is a platform-neutral reusable software

    component that:

    • Can be manipulated visually in a builder tool

    • Communicates with other JavaBeans via events

    • Comprises visible components that must inherit

    from other visible components

    • Provides an architecture for constructing the

    building blocks of an application

    Managing Bean Properties

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    67/434

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

    • Properties are the bean class member variables.

    (Variables can be primitive types or objects.)

    •  A property can be:

     –  Unbound, which is a simple property

     –  Bound, which triggers an event when the field is

    altered –  Constrained, in which changes are accepted or

    vetoed by interested listener objects

    Exposing Properties and Methods

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    68/434

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

    Getter 

    methods(public)

    Setter 

    methods(public void)

     privateT var;T[] arr;

    T getVar()

    T[] getArr()

     boolean isVar()

    setVar(T val)

    setArr(T[] val)

    setVar(boolean val)

    JavaBean Standards at Design Time

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    69/434

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

    The benefits at design t ime include:

    •  A facilitated interaction between designer, tool,

    and bean

    • Instantiated and functioning beans in a visual tool

    • Highly iterative development environment

    • Building applications in small bits that plug in and

    out

    • Storage and recovery of instantiated

    objects

    Compiling and Running

    a Java Application

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    70/434

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

    a Java Application

    • To compile a .java file:

    • To execute a .class file:

    • Remember that case matters.

     prompt> javac SayHello.java

    … compiler output …

     prompt> java SayHello

    Hello world 

     prompt>

    The CLASSPATH Variable

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    71/434

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

    • Is defined in the operating system

    • Directs the JVM and Java applications where tofind .class files

    • References built-in libraries or user-defined

    libraries

    • Enables interpreter to search paths, and loadsbuilt-in classes before user-defined classes

    • Can be used with “ javac” and “ java” commands

    CLASSPATH: Example

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    72/434

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

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

    Setting CLASSPATH

    Location of .class files in the oe package

    Summary

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    73/434

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

    In this lesson, you should have learned the following:

    • J2SE provides basic Java tools.

    • J2SE provides a rich set of predefined classes and

    methods.

    • Java programs are made up of classes, objects,

    and methods.

    •  Adhering to programming standards makes code

    easier to read and reuse.

    Practice 3: Overview

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    74/434

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

    This practice covers:

    • Examining the Java environment

    • Writing and running a simple Java application

    • Examining the course solution application

    • Inspecting classes, methods, and variables

    • Creating class files and an application class with a main( ) method

    • Compiling and running an application

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    75/434

    Copyright © 2004, Oracle. All rights reserved.

    Exploring Primitive Data Typesand Operators

    Objectives

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    76/434

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

     After completing this lesson, you should be able to dothe following:

    • Distinguish between reserved words and othernames in Java

    • Describe Java primitive data types and variables

    • Declare and initialize primitive variables• Use operators to manipulate primitive variables

    • Describe uses of literals and Java operators

    • Identify valid operator categories and operatorprecedence

    • Use String object literals and the concatenation

    operator 

    Reserved Keywords

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    77/434

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

    abstract

    final

    native private

     protected 

     public

    staticsynchronized 

    transient

    volatile

    strictfp

     break

    case

    catchcontinue

    default

    do

    elsefinally

    for

    if

    return

    switch

    throw

    try

    while

     boolean

     byte

    chardouble

    float

    int

    longshort

    void 

    truefalse

    null

    class

    extends

    implementsinterface

    throws

    instanceof

    newsuper

    this

    import package

    Variable Types

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    78/434

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

    • Eight primitive data types:

     –  Six numeric types

     –   A character type

     –   A Boolean type (for truth values)

    • User-defined types:

     –  Classes –  Interfaces

     –   Arrays

    abc

    Primitive Data Types

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    79/434

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

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

    Integer Floating

    PointCharacter 

    TrueFalse

    byteshort

    intlong

    floatdouble

    char boolean

    1, 2, 3, 4207

    0xff 

    0

    3.0F.3337F

    4.022E23

    0.0f 

    'a' '\141''\u0061'

    '\n'

    ‘\u0000’

    truefalse

    false

    What Are Variables?

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    80/434

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

    •  A variable is a basic unit of storage.

    • Variables must be explicitly declared.

    • Each variable has a type, an identifier, and ascope.

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

    int myAge;

     boolean isAMovie;

    float maxItemCost = 17.98F;

    Type

    Identifier Init ial value

    Title: “ BlueMoon”

    Declaring Variables

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    81/434

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

    • Basic form of variable declaration:

     –  type identifier [ = value];

    • Variables can be initialized when declared.

     public static void main(String[] args) {

    int itemsRented = 1;

    float itemCost;

    int i, j, k;

    double interestRate;

    }

    Local Variables

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    82/434

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

    • Local variables are defined only within a methodor code block.

    • They must be initialized before their contents areread or referenced.

    class Rental {

     private int instVar; // instance variable

     public void addItem() {

    float itemCost = 3.50F; // local variable

    int numOfDays = 3; // local variable

    }

    }

    Defining Variable Names

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    83/434

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

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

    • Other characters may include digits.

    • Use meaningful names for variables, such as

    customerFirstName and ageNextBirthday.

    a item_Cost

    itemCost _itemCostitem$Cost itemCost2

    item#Cost item-Cost

    item*Cost abstract2itemCost

    What Are Numeric Literals?

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    84/434

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

    0 1 42 -23795 (decimal)

    02 077 0123 (octal)

    0x0 0x2a 0X1FF (hex)

    365L 077L 0x1000L (long)

    1.0 4.2 .47

    1.22e19 4.61E-9

    6.2f 6.21F

    Integer literals

    Floating-pointliterals

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

    What Are Nonnumeric Literals?

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    85/434

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

    true false

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

    "Hello, world\n"String li terals

    Boolean literals

    Character li terals

    Guided Practice: Declaring Variables

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    86/434

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

    Find the mistakes in this code and fix them:

     byte sizeof = 200;

    short mom = 43;

    short hello mom;

    int big = sizeof * sizeof * sizeof;

    long bigger = big + big + big // ouch

    double old = 78.0;

    double new = 0.1;

     boolean consequence = true;

     boolean max = big > bigger;

    char maine = "New England state";

    char ming = 'd';

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    What Are Operators?

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    87/434

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

    • Operators manipulate data and objects.

    • Operators take one or more arguments and

    produce a value.

    • There are 44 different operators.

    • Some operators change the value of the operand.

    Categorizing Operators

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    88/434

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

    There are five types of operators:

    •  Assignment

    •  Arithmetic

    • Integer bitwise

    • Relational

    • Boolean

    Using the Assignment Operator 

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    89/434

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

    The result of an assignment operation is a value andcan be used whenever an expression is permitted.

    • The value on the right is assigned to the identif ieron the left:

    • The expression on the right is always evaluated

    before the assignment.•  Assignments can be strung together:

    int var1 = 0, var2 = 0;

    var1 = 50; // var1 now equals 50

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

    var1 = var2 = var3 = 50;

    Working with Arithmetic Operators

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    90/434

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

    • Perform basic arithmetic operations.

    • Work on numeric variables and literals.

    int a, b, c, d, e;

    a = 2 + 2; // addition

     b = a * 3; // multiplication

    c = b - 2; // subtraction

    d = b / 2; // division

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

    More on Arithmetic Operators

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    91/434

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

    Most operations result in int or long:

    •  byte, char, and short values are promoted to

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

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

    the long type.

     byte b1 = 1, b2 = 2, b3;

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

    // b3 is byte

    Examining Conversions and Casts

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    92/434

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

    • Java automatically converts a value of onenumeric type to a larger type.

    • Java does not automatically “ downcast.”

     byteshort

    char int long

     byte longintshortchar

    Incrementing and Decrementing Values

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    93/434

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

    • The ++ and -- operators increment and decrement

    by 1, respectively:

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

    int var1 = 3;

    var1++; // var1 now equals 4

    int var1 = 3, var2 = 0;

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

    // then assign to var2.

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

    // then increment var1.

    Relational and Equality Operators

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    94/434

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

    greater thangreater than or equal to

    less thanless than or equal toequal tonot equal to

    >

    >=

    < var1); // res now equals true

    Using the Conditional Operator (?:)

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    95/434

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

    • Useful alternative to if…else:

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

     boolean_expr ? expr1 : expr2

    int val1 = 120, val2 = 0;

    int highest;

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

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

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    96/434

    Compound Assignment Operators

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    97/434

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

     An assignment operator can be combined with anyconventional binary operator:

    double total=0, num = 1;

    double percentage = .50;

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

    total += num; // total is now 2

    total -= num; // total is now 1

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

    num %= percentage; // num is now 0

    Operator Precedence

    Operators CommentsOrder Assoc.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    98/434

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

    Operators

    ++ -- + - ~

    ! (type)

    * / %

    + - +> >>>

    < > =

    instanceof

    == !=&

    ^

    |

    &&

    ||

    ?:

    = op =

    Comments

    Unary operators

    Multiply, divide, remainder 

     Add, subtract, add stringShift (>>> is zero-fill shift)

    Relational, type compare

    EqualityBit/logical ANDBit/logical exclusive ORBit/logical inclusive ORLogical ANDLogical ORConditional operator 

     Assignment operators

    Order 

    1

    2

    34

    5

    67

    8

    9

    10

    11

    12

    13

     Assoc.

    R

    L

    LLL

    LLLLLLRR

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    99/434

    Concatenating Strings

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    100/434

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

    The + operator creates and concatenates strings:

    String name = "Jane ";

    String lastName = "Hathaway";

    String fullName;

    name = name + lastName; // name is now//"Jane Hathaway"

    // OR 

    name += lastName; // same result

    fullName = name;

    Summary

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    101/434

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

    In this lesson, you should have learned the following:

    • Java has eight primitive data types.

    •  A variable must be declared before it can be used.

    • Java provides a comprehensive set of operators.

    • Explicit casting may be necessary if you use data

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

    concatenate str ings.

    Practice 4: Overview

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    102/434

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

    This practice covers:

    • Declaring and initializing variables

    • Using various operators to compute new values

    • Displaying results on the console

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    103/434

    Copyright © 2004, Oracle. All rights reserved.

    Controlling Program Flow

    Objectives

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    104/434

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

     After completing this lesson, you should be able to do

    the following:

    • Use decision-making constructs• Perform loop operations

    • Write switch statements

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    105/434

    Using Flow Control in Java

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    106/434

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

    • Each simple statement terminates with a

    semicolon (;).

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

    the flow of control structure.

    {

     boolean finished = true;

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

    i++;

    }

    Using the if Statement

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    107/434

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

    if ( boolean_expr )

    statement1;

    [elsestatement2];

    if (i % 2 == 0)

    System.out.println("Even");

    else

    System.out.println("Odd");

    …if (i % 2 == 0) {

    System.out.print(i);

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

    }

    Examples:

    General:

    Nesting if Statements

    if (speed >= 25)if (speed > 65)

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    108/434

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

    ( p )

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

    else

    System.out.println("Speed >= 25 but

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    109/434

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

    int x = 3, y = 5;

    if (x >= 0)

    if (y < x)

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

    else

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

    int x = 7;

    if (x = 0)

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

    int x = 14, y = 24;

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

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

    1

    2

    3

    Defining the switch Statement

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    110/434

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

    • The switch

    statement is useful

    when selecting anaction from several

    alternative integer

    values.

    • Integer_expr mustbe byte, int, char,

    or short.

    switch ( integer_expr ) {

    case constant_expr1:statement1;

     break;

    case constant_expr2:

    statement2;

    break ;

    [default:

    statement3 ;]}

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    111/434

    Looping in Java

    Th th t f l i J

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    112/434

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

    • There are three types of loops in Java:

     –  while

     –  do…while –  for

    •  All loops have four parts:

     –  Initialization –  Iteration condit ion

     –  Body

     –  Termination

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    113/434

    Using the do…while Loop

    d hil loops place the test at the end:

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    114/434

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

    do…while loops place the test at the end:

    do

    statement;

    while ( termination );

    int i = 0;

    do {

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

    i++;

    } while (i < 10);

    Example:

    Using the for Loop

    for loops are the most common loops:

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    115/434

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

    for loops are the most common loops:

    How would this for loop look using a while loop?

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

    System.out.println(i);

    for ( initialization; termination; iteration )statement;

    Example:

    More About the for Loop

    • Variables can be declared in the initialization part

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    116/434

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

    • Variables can be declared in the init ialization partof a for loop:

    • Init ialization and iteration can consist of a list ofcomma-separated expressions:

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

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

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

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

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

    }

    Guided Practice: Spot the Mistakes

    int x = 10; 1

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    117/434

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

    int x 10;

    while (x > 0);

    System.out.println(x--);

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

    int x = 10;

    while (x > 0)

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

    x--;

    int sum = 0;

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

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

    1

    2

    3

    The break Statement

    • Breaks out of a loop or switch statement

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    118/434

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

    • Breaks out of a loop or switch statement

    • Transfers control to the first statement after the

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

    while (age = 250000)

     break;

    age++;}

    Summary

    In this lesson you should have learned the following:

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    119/434

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

    In this lesson, you should have learned the following:

    • The primary means of decision-making is the if

    statement, with the optional else.• Java also offers the switch statement.

    • Java provides three loop statements: while,

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

    Practice 5: Overview

    This practice covers:

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    120/434

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

    This practice covers:

    • Performing tests by using if…else statements

    • Using loops to perform iterative operations• Using the break statement to exit a loop

    • Using the &&, ||, and ! operators in Boolean

    expressions

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    121/434

    Copyright © 2004, Oracle. All rights reserved.

    Building Applications with

    Oracle JDeveloper 10g

    Objectives

    After completing this lesson, you should be able to do

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    122/434

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

     After completing this lesson, you should be able to do

    the following:

    • Create new projects, workspaces, andapplications

    • Build Java applications in JDeveloper 

    • Enhance user interface frame design• Debug an application by using JDeveloper

    debugger 

    • Define classes by using JDeveloper 

    • Describe how JDeveloper can be used to build

    enterprise applications

    What Is Oracle JDeveloper 10g?

    • Oracle JDeveloper 10g provides an integrated

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    123/434

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

    Oracle JDeveloper 10g provides an integrated

    development environment (IDE).

    • Build, compile, and run Java applications by usingOracle JDeveloper.

    • Use wizards to help build source code.

    • View objects from many perspectives: code,structure, layout, and so on.

    Exploring the JDeveloper Environment

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    124/434

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

    System Navigator  Code Editor  Property Inspector 

    Component Palette

    Examining Workspaces

    • Contain multiple projects

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    125/434

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

    p p j

    • Enable you to view

    currently used objectsWorkspace

    Navigator

    pane

    Structure

    pane

    What Are Projects?

    • Contain related

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    126/434

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

    files

    • Manage project andenvironment

    settings

    • Manage compiler

    and debug options

    Project

    Project

    files

    Creating JDeveloper Items

    • JDeveloper items are

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    127/434

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

    invoked by selecting

    File > New.• They are categorized by

    type:

     –  General

     –  Business Tier 

     –  Client Tier 

     –  Database Tier 

     –  Web Tier 

    • Create any JDeveloper

    element.

    Creating an Application Workspace

    In the General

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    128/434

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

    category, select

     ApplicationWorkspace to invoke

    the Property pane.

    Specifying Project Details

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    129/434

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

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    130/434

     Adding a New J2SE

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    131/434

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

    New J2SE definitions include:

    • Java executable

    •  A classpath•  A source path

    •  A doc path

    Looking at the Directory Structure

    JDeveloper creates and stores .java and .class files

    b i th f ll i ti

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    132/434

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

    by using the following convention:

    •   \jdev\mywork• Followed by the workspace

    name

    • Followed by the project name –  \classes\\

     –  \src\\

    • Followed by class and src files

    Exploring the Skeleton Java Application

    Contains application and frame classes

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    133/434

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

    Finding Methods and Fields

    Find methods and fields by using the Structure pane.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    134/434

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

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    135/434

    Customizing JDeveloper 

    Customize the IDE

    L k d f l

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    136/434

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

    • Look and feel

    • General environment• Dockable windows

    • Component Palette

    • Load preset keymapsRename classes and packages by using refactoring.

    Using the Help System

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    137/434

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

    Obtaining Help on a Topic

    Use [F1] to invoke

    context-specific Help.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    138/434

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

    Oracle JDeveloper 10g Debugger 

    • Helps find and fix program errors:

    Run time errors

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    139/434

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

     –  Run-time errors

     –  Logic errors•  Allows control of execution

    •  Allows examination of variables

    Setting Breakpoints

    Setting breakpoints:

    • Manage multiple breakpoints

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    140/434

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

    • Manage multiple breakpoints

    • Manage conditional breakpoints• Define columns displayed in window

     –  Description

     –  Type –  Status, and so on

    • Control scope of action

     –  Global > Workspace > Project

    Using the Debugger Windows

    View Debug information:

    • Classes: Displays list of loaded classes and status

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    141/434

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

    • Classes: Displays list of loaded classes and status

    • Watch: Evaluates and displays expressions• Monitors: Displays information about active

    monitors

    • Threads: Displays the names and statuses of allthreads

    • Smart Data: Analyzes source code near execution

    point

    • … and more

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    142/434

    Watching Data and Variables

    • The Smart Data tab displays analyzed variables

    and fields.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    143/434

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

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

    • To watch other variables:

     –  Select a variable in the source window and right-

    click.

     –  Select Watch... at Cursor from the context menu.

     –  View the variable in the Watch tab.

     –  Right-click a data item to modify it.

    Summary

    In this lesson, you should have learned how:

    • JDeveloper builds debugs and runs all types of

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    144/434

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

    JDeveloper builds, debugs, and runs all types of

    Java applications• JDeveloper can be used to develop:

     –  Java applications

     –  Java servlets

     –  JSPs

     –  EJBs

    • JDeveloper can be used to build enterprise

    applications

    Practice 6: Overview

    This practice covers:

    • Exploring the Oracle JDeveloper 10g IDE

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    145/434

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

    Exploring the Oracle JDeveloper 10g IDE

    • Creating a workspace and project• Including application files from the earlier lesson

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    146/434

    Objectives

     After completing this lesson, you should be able to do

    the following:

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    147/434

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

    • Define instance variables and methods• Define the no-arg (default) constructor method

    • Instantiate classes and call instance methods

    • Perform encapsulation by using packages togroup related classes

    • Control access with public and private access

    modifiers

    • Use class variables and methods

    Using Java Classes

    Methods Objects

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    148/434

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

    Packages

    Objectreferences Attributes

    Contained in a class

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    149/434

    Creating Objects

    • Objects are typically created by using the new

    operator:

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    150/434

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

    • For example, to create two Movie objects:

     Movie mov1 = new Movie("Gone ...");

     Movie mov2 = new Movie("Last ...");

    ClassName objectRef = new ClassName();

    title: “ Gone with…”rating: “ PG”

    title: “ Last Action…”rating: “ PG-13”

    Using the new Operator 

    The new operator performs the following actions:

    •  Allocates and initializes memory for the new

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    151/434

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

    object• Calls a special initialization method in the class,

    called a constructor 

    • Returns a reference to the new object

     Movie mov1 = new Movie("Gone with…");

     mov1(When instantiated)

    title: “ Gone with…”rating: “ PG”

    Comparing Primitives and Objects

    Primitive variables

    hold a value.

    Object variables

    hold references.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    152/434

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

    int i;

    int j = 3;  Movie mov1 = new Movie();

    title: null

    rating: nul l

     mov1

     Movie mov1;

     mov1

    0

    3j

    inull

    Using the null Reference

    •  A special null value may be assigned to an object

    reference, but not to a primitive.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    153/434

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

    • You can compare object references to null.• You can remove the association to an object by

    setting the object reference to null.

     Movie mov1; //Declare object reference…

    if ( mov1 == null) //Ref not initialized?

     mov1 = new Movie(); //Create a Movie object

     mov1 = null; //Forget the Movie object

     Assigning References

     Assigning one reference to another results in two

    references to the same object:

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    154/434

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

     Movie mov1 = new Movie("Gone...");

     mov1

     Movie mov2 = mov1;

     mov2

    title: “ Gone with…”

    rating: “ PG”

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    155/434

     Accessing public Instance Variables

     public instance variables can be accessed by using

    the dot operator:

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    156/434

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

     public class Movie {

     public String title;

     public String rating;

    } Movie mov1 = new Movie(); mov1.title = "Gone ...";

    if (mov1.title.equals("Gone ... ") )

     mov1.rating = "PG";

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    157/434

    Calling a Method

    Objects communicate by using messages:

    •  All methods are defined within a class and are not

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    158/434

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

    defined globally as in traditional languages.• When you call a method, it is always in the context

    of a particular object.

     –  myPen.write( ): Object-oriented programming

     –  Write (myPen): Traditional structured

    programming

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    159/434

    Returning a Value from a Method

    • Use a return statement to exit a method and to

    return a value from a method:

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    160/434

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

    • If the return type is void, then no return is needed.

    • You can use a return without a value to terminate

    a method with a void return type.

     public class Movie { private String rating;

     public String getRating () {

    return rating 

    }

    }

    Calling Instance Methods

     public class Movie {

     private String title, rating;

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    161/434

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

     public String getRating(){

    return rating;

    }

     public void setRating(String newRating){

    rating = newRating;

    }

    } Movie mov1 = new Movie();

    String r = mov1.getRating();

    if (r.equals("G")) …Use the dot

    operator:

     Applying Encapsulation in Java

    • Instance variables must bedeclared as private.

    var 

    aMethod

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    162/434

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

    • Only instance methods can access private instance variables.

    •  private decouples the interfaceof the class from its internal operation.

     Movie mov1 = new Movie();

    String rating = mov1.getRating();

    String r = mov1.rating; // error: private. . .

    if (rating.equals("G"))

    aMethod()

    Passing Primitives into Methods

    When a primitive or object reference value is passed

    into a method, a copy of the value is generated:

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    163/434

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

     public void aMethod(int arg) {

    if (arg < 0 || arg > 100)

    arg = 0;System.out.println("arg: " + arg);

    }

    int num = 150;

    anObj.aMethod(num);

    System.out.println("num: " + num);

    arg

    150

    num 

    150

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    164/434

    What Are Class Variables?

    Class variables:

    • Belong to a class and are common to all instancesof that class

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    165/434

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

    •  Are declared as static in class definitions

     public class Movie {

     private static double minPrice; // class var

     private String title, rating; // inst vars

     Movie class variable  Movie objects

    title

    rating

    title

    rating

    titleratingminPrice

    Initializing Class Variables

    • Class variables can be initialized at declaration.

    • Initialization takes place when the class is loaded.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    166/434

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

    • Use a static initializer block for complexinitialization.

    •  All class variables are initialized implicitly to

    default values depending on data type.

     public class Movie {

     private static double minPrice = 1.29;

     private String title, rating; private int length = 0;

    What Are Class Methods?

    Class methods are:

    • Shared by all instances

    • Useful for manipulating class variables

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    167/434

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

    p g

    • Declared as static

     A class method is called by using the name of theclass or an object reference.

     public static void increaseMinPrice(double inc) {

     minPrice += inc;

    }

     Movie.increaseMinPrice(.50);

     mov1.increaseMinPrice(.50);

    Guided Practice: Class Methods

    or Instance Methods

     public class Movie {

     private static float price = 3.50f;

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    168/434

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

     private String rating;…

     public static void setPrice(float newPrice) {

     price = newPrice;

    } public String getRating() {

    return String;

    }

    }

     Movie.setPrice(3.98f); Movie

     mov1 = new Movie(…);

     mov1.setPrice(3.98f);String a = Movie.getRating();

    String b = mov1.getRating();Legal or not?

    Examples in Java

    Examples of static methods and variables:

    •  main()

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    169/434

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

    •  Math.sqrt()• System.out.println()

     public class MyClass {

     public static void main(String[] args) {

    double num, root;

    root = Math.sqrt(num);System.out.println("Root is " + root);

    } …

    Creating Classes Using the Class Editor 

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    170/434

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

    What Are Java Packages?

    oe

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    171/434

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

    Customer Order Util

    OrderEntry OrderItem 

    Grouping Classes in a Package

    • Include the package keyword followed by thepackage name at the top of the Java source file.Use the dot notation to show the package path.

    If it th k k d th th

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    172/434

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

    • If you omit the package keyword, then thecompiler places the class in a default “ unnamed”package.

    • Use the –d flag with the javac compiler to create

    the package tree structure relative to the specifieddirectory.

    • Running a main() method in a packaged classrequires:

     –  That the CLASSPATH contains the directory havingthe root name of the package tree

     –  That the class name must be qualif ied by itspackage name

    Setting the CLASSPATH with Packages

    The CLASSPATH includes the directory containing the

    top level of the package tree:

    Package name .class location

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    173/434

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

    C:\>set CLASSPATH=E:\Curriculum\courses\java\les06

    CLASSPATH

     Access Modifiers

    acmevideo acmetools

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    174/434

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

     private

     protected 

     public public

    Summary

    In this lesson, you should have learned the following:

    •  A class definition specifies a template for building

    objects with identical features, such as instance

    i bl d th d

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    175/434

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

    variables and methods.

    •  An object is an instance of a particular class.

     –  Create an object by using new.

     –  Manipulate an object by using its public instancemethods.

    Practice 7: Overview

    This practice covers:

    • Defining new classes

    • Specifying the classes’ instance variables and

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    176/434

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

    • Specifying the classes instance variables andinstance methods

    • Creating Customer objects in main()

    • Manipulating Customer objects by using public

    instance methods

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    177/434

    Objectives

     After completing this lesson, you should be able to do

    the following:

    • Provide two or more methods with the same name

    in a class

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    178/434

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

    in a class

    • Provide one or more constructors for a class

    • Use initializers to initialize both instance and class

    variables

    • Describe the class loading and initializing

    process, and the object life cycle

    • Define and use inner classes

    Overloading Methods

    • Several methods in a class can have the same

    name.

    • The methods must have different signatures.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    179/434

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

     public class Movie {

     public void setPrice() {

     price = 3.50F;}

     public void setPrice(float newPrice) {

     price = newPrice;

    } …

    }

     Movie mov1 = new Movie();

     mov1.setPrice();

     mov1.setPrice(3.25F);

    Using the this Reference

    Instance methods receive an argument called this,

    which refers to the current object.

    public class Movie {

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    180/434

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

     public class Movie {

     public void setRating(String newRating) {

    this.rating = newRating;

    }

    void anyMethod() {

     Movie mov1 = new Movie();

     Movie mov2 = new Movie();

     mov1.setRating("PG"); …

    title: null

    rating: nul l mov2

     mov1

    title : null

    rating: “ PG”

    this

    Initializing Instance Variables

    • Instance variables can be explicitly initialized at

    declaration.

    • Initialization happens at object creation.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    181/434

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

    •  All instance variables are initialized implicitly to

    default values depending on data type.

    • More complex initialization must be placed in a

    constructor.

     public class Movie {

     private String title;

     private String rating = "G";

     private int numOfOscars = 0;

    What Are Constructors?

    • For proper initialization, a class must provide a

    constructor.

    •  A constructor is called automatically when an

    object is created:

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    182/434

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

    object is created:

     –  It is usually declared public.

     –  It has the same name as the class.

     –  It must not specify a return type.

    • The compiler supplies a no-arg constructor i f and

    only if a constructor is not explicitly provided.

     –  If any constructor is explicitly provided, then thecompiler does not generate the no-arg constructor.

    Defining and Overloading Constructors

     public class Movie {

     private String title;

     private String rating = "PG";

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    183/434

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

     public Movie() {

    title = "Last Action …";

    }

     public Movie(String newTitle) {

    title = newTitle;

    }

    }

     Movie mov1 = new Movie();

     Movie mov2 = new Movie("Gone…

    ");

     Movie mov3 = new Movie("The Good …");

    The Movie class

    now provides twoconstructors.

    Sharing Code Between Constructors

     public class Movie {

     private String title;

     private String rating;

     A constructorcan call another

    constructor byusing thi ()

     Movie mov2 = new Movie();

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    184/434

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

     public Movie() {

    this("G");

    }

     public Movie(String newRating) {

    rating = newRating;

    }}

    yusing this().

    What happenshere?

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    185/434

    Reclaiming Memory

    • When all references to an object are lost, the

    object is marked for garbage collection.

    • Garbage collection reclaims memory that is used

    by the object.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    186/434

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

    y j

    • Garbage collection is automatic.

    • There is no need for the programmer to do

    anything, but the programmer can give a hint toSystem.gc();.

    Using the finalize() Method

    • If an object holds a resource such as a fi le, then

    the object should be able to clean it up.

    • You can provide a finalize() method in that

    class.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    187/434

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

    • The finalize() method is called just before

    garbage collection.

     public class Movie {

     public void finalize() {

    System.out.println("Goodbye");}

    }

     Any problems?

    What Are Inner Classes?

    • Inner classes are nested classes, defined in a

    class or method.

    • They enforce a relationship between two classes.

    • They are of four types:

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    188/434

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

    They are of four types:

     –  Static

     –  Member 

     –  Local

     –   Anonymous

     public class Outer { …

    class Inner { …

    }

    }

    Enclosing class

    Using Member Inner Class

    • It is declared within another class.

    • Nesting is allowed.

    • It can access variables within its own class and

    any enclosing classes.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    189/434

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

    a y e c os g c asses

    • It can only declare final static methods.

     public class CalendarPopup {

    ...class MonthSelector {

    class DayOfMonth{...};DayOfMonth[] NumberOfDaysInMonth...

    }}

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    190/434

    Defining Anonymous Inner Classes

    • They are defined at method level.

    • They are declared within a code block.

    • They lack the class, extends, and implements

    keywords.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    191/434

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

    y

    • They cannot have a constructor.

     public class Outer {

    ... public void outerMethod(){

    ... myObject.myAnonymous(new SomeOtherClass(){...

    } )}

    }

    Using the Calendar Class

    • It converts between a date object and a set of

    integer fields.

    • It represents a specific moment in time.

    • Subclasses interpret a date according to the

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    192/434

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

    p g

    specific calendar system.

     public class Order {

    ... public void String getShipDate(){

    ...Calendar c = Calendar.getInstance();c.setTime(orderDate);

    ...}}

    Summary

    In this lesson, you should have learned the following:

    • Methods can be overloaded in Java.

    • Instance methods receive a this reference to the

    current object.

  • 8/15/2019 Oracle10g Java Programming - Electronic Presentation.pdf

    193/434

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

    • Most classes provide one or more constructors to

    initialize new objects.

    • Class variables and class methods can