Learning Center
Plans & pricing Sign in
Sign Out



									Java OOP Overview
    Review of Java
                Course Objectives
Upon completing this course you should be able to:
    Describe the three main OOP concepts.
    Differentiate between “is-a” and “has-a” Relationships.
    Use Java standards for coding.
    Describe the Java environment and how it works.
    Write java programs.
    Create objects out of classes.
    Create classes and interfaces.
    Use Java I/O capabilities.
    Use the Java API.
    Create and manage a hierarchy of classes and interfaces.
    Create packages and document them.
    Connect to a database using JDBC.
Course Organization
   Part 1: OOP Model
   Part 2: Java Basics
   Part 3: Java implementation of OOP Model
   Part 4: Java OO Design Issues
   Part 5: Introduction to the Java API
         Introduction to Swing
         Java I/O
         Exception Handling
         Java JDBC
         SQL Review
         Servlets
         The Collection Framework
         Threads
         More…
Part 1
    OOP Model
   Objects can be described in terms of:
     Their attributes
     Their behaviors
     Their interactions
   Object‟s attributes and behaviors are
    encapsulated together as a data type.
   Objects have a lifecycle:
     Creating objects
     Manipulating objects
     Cleaning up objects
                OOP Five Rules
   Alan Kay summarized five basic
    characteristics of Smalltalk:
     1.   Everything is an object.
     2.   A program is a bunch of objects telling
          each other what to do by sending
          messages to each other.
     3.   Each object has its own memory made up
          of other objects.
     4.   Every object has a type.
     5.   All objects of a particular type can receive
          the same messages.
     Objects have Interfaces
   An object has to have an interface.
   The interface will provide a way to let other
    objects communicate with it.
   It will also hide the details of the object‟s
     An   example: A lightbulb!

                    OOP Big Goals (1)
   Hiding the Implementation!
       Breaks up the playing field into:
          Class creators (those who create new data types)
          Client programmers (those who use these types for their own
           tasks. They only deal with the interfaces.)
          End users: they only use the created applications

     The goal of the class creator is to build a class that
      exposes only what‟s necessary to the client programmer
      and keeps everything else hidden.
     Three reasons for controlling the access:
          To keep client programmers‟ hands off portions they shouldn‟t
          To avoid accidental (or malicious!) changes/deletions

          To allow the library designer to change the internal workings
           of the class without worrying about how it will affect the client
OOP Big Goals (2)
   Implementation Reuse:
     Software reusability is not so easy to achieve as many would
      hope; it takes experience and insight to produce a good
     OOP provides ways for reuse:
          Composition
          Inheritance (Reusing the interface)

          Polymorphism

       OOP relationships between classes and objects can be:
          Inheritance/Generalization (between classes) – “is-a”
          Association (between objects) – relationships that are described
           as “has-a”
          Aggregation (between objects) – “composed-of” (strong
           aggregation/composition) and “consists-of” (weak aggregation)
             • Aggregations (weak and strong/composition) are considered a more
               tightly coupled type of association and also have the same
               OOP Big Goals (3)
   Polymorphism
     Allows  you to make the derived types behave
      differently from their base types.
     It uses “late binding” instead of “early binding”
     Example:

            Goose                    Penguin
            Move()                   Move()
              Overriding or Overloading
   Polymorphism translates from Greek as many forms ( poly –
    many, morph - forms)
   Method overloading is the primary way polymorphism is
    implemented in Java
   Overloaded methods appear in a subclass with same name but
    different parameter lists and return types
   Late-binding (or run-time binding) also supports overriding
   Overriding allows a subclass to re-define a method it inherits
    from it's superclass
       An over-ridden method in a subclass has the same
        signature (name and parameter list) and also the same
        return type (different from C++!)
Program Design and Development

    The word implement means “to put into effect according to
     a definite plan”
    In software engineering, implementation is the actual
     production of software (i.e., coding) based on a plan
    These plans are usually conceived during the design
    But the way software engineering/computer science is
     taught is reversed!
    First you learn how to program (code), then you learn how
     to analyze and design it, finally you learn how to (formally)
     figure out the requirements/specifications!
Software Engineering/Computer
   Software Development proceeds, in practice and theory, in
    this manner (followed by testing!):

   However, it‟s learned as follows (with testing in there

   It‟s taught backwards!
Program Performance Measures
    Understand what constitutes a good implementation
        Implementation is actual production of software (i.e., coding)
    Good programs should provide:
        Clarity
        Efficiency
             Not as much of an issue as the others nowadays
        Robustness
             Making it bullet-proof (to errors or misuses by the user)
        Extensibility
        Reusability
    Programming-in-the-large
        Developing large projects in a distributed manner
    Procedural vs. OO

   Procedure-oriented programming:
     Has the capability of producing clear, efficient, robust
      programs that can be programmed in the large
     Does   not produce reusable and extensible programs
     Very cumbersome and extremely time-consuming
      and costly to extend or reuse in new applications
   Object-oriented technology (OOT):
     Produces   both extendable and reusable code
    Moving to OOTechnology
   True OOT (Object Oriented Technology):
   One works with objects from the problem definition
    stage through the programming stage
   Encompasses:
       OOR:    object-oriented requirements/specifications
       OOA:    object-oriented analysis
       OOD:    object-oriented design
       OOP:    object-oriented programming
       OOTe: object-oriented testing
   Same discrepancy in how it‟s
    practiced and how it‟s taught!
Part 2
    Java Basics
History of C++
   First there was C.
   C initially became widely known as the
    development language of the UNIX OS.
   C++ evolved as an extension to C.
   It mainly provides the capabilities of
    Object-Oriented Programming to the C
   C++ is a hybrid language.
   Both procedural style and object-oriented
    style can be developed using C++.
History of Java
   Java was developed by James Gosling at Sun Microsystems in 1991.
       Java was initially developed to be used with interactive TV technology
        which had failed to find a market.
   His original aim was to develop a low cost, Hardware Independent
    Language based on C++.
      Due to technical reasons, that idea was dropped .
   A new programming Language called Oak was developed based on C++
    but removed undesirable features of C++. E.g., it removed:
      Multiple Inheritance
      Automatic type conversions
      Memory Management.
            Use of pointers
   By 1994 the World Wide Web Emerged and Oak was Re-named as Java.
   When The World-Wide Web became popular in 1995 , Java came to life
   Java is now considered as the native language of the Internet.
   Java is a C/C++ based language.
   Java is a Fully object-oriented language
         So, what is Java?
According to Sun's definition:
 Java is a "simple, object-
 oriented, interpreted, robust,
 secure, architecture-neutral,
 portable, high-performance,
 multithreaded, and dynamic
                     Java Environment
     Draft                 Editor               .java file

    .java file            Compiler             .class File

    .class File          Class Loader       Byte code on RAM

Byte code on RAM       Byte code Verifier   Verified Byte code
                                            Executed machine
Verified Byte code        Interpreter       code
    Compiling/Running Java
   Write your .java source code file in any text editor
   To compile your program, use command:
        c:\> javac
   To run your program, use command:
        c:\> java MyProgramName
              Java Virtual Machine
   Also called pseudo-
    machine or pMachine
   Hence, the bytecode
    generated for it is
    sometimes called
    pCode (NOT to be
    confused with pseudo-
   Interacts with OS:
                Using IDEs
   Eclipse, JCreator, BlueJ, JBuilder, and NetBeans
Program skeleton
1    //the skeleton of a java application
     package packagename;
                                              Java is a case

3    import packagename.ClassName;
4    public class ProgramName
                                               sensitive language
5    {                                        Braces must occur
         // Define program variables here.
                                               on matching pairs
7        . . .
8        // Define program methods here.      Coding styles
9        . . .                                 should be followed.
10       //Define the main method here.
11       public static main(String args[])
12       {
13           // Main method body
14       }//end of the main method.
15   } //End of class HelloWorld
Comment Styles
    Comments are used to make clear the logic of the
     code and to increase its readability.
    Comments are ignored by the compiler.
    Java uses three types of comments:
      Single-line comment(//). Example:
        //single-line comment here
      Multiple-line comment(/*…*/). Example:
                line 1 here
                line 2 here …
      Documentation comment(/**…*/). It is multiple-line
       and used with “javadoc” utility to create application
Playing With Strings
   A string is a group of characters
   We use class String to define a string.
         Example:       String name;
   Strings are bounded by double
    quotations.         Example:
    String name = “Jane”;
   We can concatenate two or more strings
    using the operator +
   Strings can contain escape characters
    like “\n”, “\t”, “\\”, “\””.
    Variable Definitions
   Variables are used to represent the data that a
    program deals with
   As the name might imply, the data that a variable
    holds can change.
   We have to define a variable before using it
       Here are some examples of defining a variable:
        int number;
        String name;
   Different kind of variables (class, instance, and local)
   Different default initializations
       Instance variables get default values; local variables
   Primitives Data types
Type      Size in bits   Values
boolean   8              true or false
char      16             \u0000 - \uFFFF
byte      8              -128 - 127
short     16             -32,768 – 32,767
int       32             -2,147,483,648 - +2,147,483,647
long      64             -9,223,372,036,854,775,808 -
float     32             -3.40292347E+38 - -+3.40292347E+38
double    64             -1.79769313486231570E+308 to -
   Arithmetic Operations
  Operation      Operator   Java Expression

Addition            +          a + 8
Subtraction         -          b - 7
Multiplication      *         p * 10
Division            /          c / 9
Modulus             %          b % 6
Decision making operations
      Operation         Operator   Java Expression
                                    if (x == 1) …
Equal to                  ==
                                    if (y != 5) …
Not equal to              !=
                                   while (x > y) …
Greater than               >
                                   while (x < y) …
Less than                  <
                                    if (X >= y) …
Greater than or equal     >=
                                   if ( y <= z) …
Less than or equal        <=
Assignment Operators
Operator   Expression      Equivalent to
   =       c = 5;          c = 5
   +=      a   +=   10 ;   a   =   a + 10;
   -=      a   -=   b;     a   =   a –b;
   *=      c   *=   13;    c   =   c * 13;
   /=      a   /=   b;     a   =   a/b;
   %=      b   %=   c ;    b   =   b% c;
     Increment /decrement
 Operator   expression      Equivalent to

++          count++;     Count = count + 1;
--          --count;     Count = count - 1;
                Logical Operators
   Logical operators allow more complex conditions
   && (logical AND)
       Returns true if both conditions are true
   || (logical OR)
       Returns true if either of its conditions are true
   ! (logical NOT, logical negation)
       Reverses the truth/falsity of its condition
            Unary operator, has one operand
   Short circuit evaluation
       Evaluate left operand, decide whether to evaluate right
            If left operand of && is false, will not evaluate right operand
Operator                                     Associativity
( )                                          From left to right   High
++                  --                       From right to left
*          /             %                   From left to right
+               -                            From left to right
<          <=             >        >=        From left to right
==             !=                            From left to right
&                                            From left to right
^                                            From left to right
|                                            From left to right
&&                                           From left to right
||                                           From left to right
?:                                           From right to left
=     +=        -=            *=        /=   From right to left
                Java Keywords
Keywords are words reserved for Java and cannot be
used as identifiers or variable names

     Ja va Keyw o rd s
     abstract   boolean    break       byte            case
     catch      char       class       continue        default
     do         double     else        extends         false
     final      finally    float       for             if
     implements import     instanceof int              interface
     long       native     new         null            package
     private    protected public       return          short
     static     super      switch      synchronized    this
     throw      throws     transient   true            try
     void       volatile   while
     Keywords that are reserved but not used by Java
     const      goto
                     If – if/else structures
   if statement looks like:      If/else statement looks like:
    if (condition) {           if (condition)
               …               {
    }                             //do something.
   Conditions are             else
    evaluated to either true   {
    or false                     //do something else.
      The switch Structure
   switch statements
    – Useful to test a variable for different values
    – switch ( value ){
       case '1':
       case '2':
    – break; causes exit from structure
                    While Structure
   while repetition structure
     Repeat an action while some condition remains true
     while loop repeated until condition becomes false

     Body may be a single or compound statement
     If the condition is initially false then the body will never
      be executed
     Example:
        int product = 2;
        while ( product <= 1000 )
          product = 2 * product;
                   The for Structure
   for "does it all" : initialization, condition, increment
   General format
    for ( initialization; loopContinuationTest; increment )

   If multiple statements needed, enclose in braces
   Control variable only exists in body of for structure
   If loopContinuationTest is initially false, body not
   Methods
       Modularize a program
            Break it up into functions and objects that have functions
       All variables declared inside methods are local variables
            Known only in method defined
       Parameters
            Communicate information between methods
              • Difference between actual and formal parameters
   Benefits
       Divide and conquer
            Manageable program development
       Software reusability
          Avoids code repetition
          Existing methods are building blocks for new programs

          Hides unnecessary details

       Abstraction - hide internal details (library methods)
                      Method Definitions
   Method definition format
    return-value-type method-name( parameter-list )
           declarations and statements
     Method-name: any valid identifier
     Return-value-type: data type of the result (default int)
            void - method returns nothing
          Can return at most one value
          An access modifier (later)

       Parameter-list: comma separated list, declares
                     return Statement
   When method call encountered
      Control transferred from point of invocation to method
   Returning control
      If nothing returned: return;
            Or until reaches right brace
       If value returned: return expression;
            Returns the value of expression
   Example user-defined method:
       public int square( int y )
               return y * y
                  Calling methods
   Three ways
     Method   name and arguments
        Can be used by methods of the same class
        within that class:
       square( 2 );
     Dot   operator - used with references to objects
       g.drawLine( x1, y1, x2, y2 );
     Dot operator - used with static methods of
      classes by using the Class name:
       Integer.parseInt( myString );
        Coercion of arguments
   Forces arguments to appropriate type for method
       Example:
          Math methods only take double
          Math.sqrt( 4 ) evaluates correctly

          Integer promoted to double before passed to
   Promotion rules
     Specify how types can be converted without losing
     If data will be lost (i.e. double to int), explicit cast must
      be used
     If y is a double,
             square( (int) y );
    Duration of Identifiers
   Duration (lifetime) of identifiers
     When exists in memory
     Automatic duration
            Local variables in a method
              • Called automatic or local variables
          Exist in block they are declared
          When block becomes inactive, they are destroyed

       Static duration
          Created when defined
          Exist until program ends

          Does not mean can be referenced/used anywhere
              • See Scope Rules
               Scope Rules (1)
   Scope
     Where  identifier can be referenced
     Local variable declared in block can only be
      used in that block
     That’s called local scope

   Class scope
     Begins at opening brace, ends at closing
      brace of class
     Methods and instance variables
     Can be accessed by any method in class
                      Scope Rules (2)
   Block scope
     Begins at identifier's declaration, ends at terminating
     Local variables and parameters of methods
        When nested blocks, need unique identifier names

     If  local variable has same name as instance
            Instance variable "hidden"
   Method scope
       For labels (used with break and continue)
            Only visible in method in which it is used
                     Method Overloading
   Method overloading
     Methods with same name and different parameters
     Overloaded methods should perform similar tasks
            Method to square ints and method to square doubles

        public int square( int x ) { return x * x; }
        public float square( double x ) { return x * x; }

       Program calls method by signature
          Signature determined by method name and parameter
          Overloaded methods must have different parameters

          Return type cannot distinguish method
   Array
     Group of consecutive memory locations
     Same name and type
     Static(Remain same size)
   To refer to an element, specify
       Array name and Position number (index)
   Format:
       arrayname[position number]
            First element at position (index) 0
   Every array knows its own length c.length
Declaring/Allocating Arrays
   Declaring arrays
     Specify    type, use new operator
        Place brackets after array reference variable name
         in declaration
        Allocate memory for actual array object

        Specify number of elements in allocation

     Two   steps:
       int c[];           //declaration
       c = new int[ 12 ]; //allocation
      Or one step:
       int c[] = new int[ 12 ];
     Primitive  elements are initialized to zero or
      false while Non-primitive references are
      initialized to null
References and Reference
   Passing arguments to methods
     Call-by-value: pass copy of argument
     Call-by-reference: pass original argument
     Pass-by-reference improves performance but
      weakens security
   In Java, you cannot choose how to pass
     Primitive data types passed call-by-value
     References to objects passed call-by-reference
            Original object can be changed in method
       Arrays in Java treated as objects
            Passed call-by-reference
Passing Arrays to Functions
   Passing arrays
     Specify array name without brackets
      int myArray[ 24 ];
      myFunction( myArray );
     Arrays passed call-by-reference
            Modifies original memory locations
       Header for method modifyArray might be
        void modifyArray( int b[] )
   Passing array elements
       Passed by call-by-value
            Pass subscripted name (i.e., myArray[3]) to method
Multiple-Subscripted Arrays
   Represent tables
      Arranged by m rows and n columns (m by n array)
           Can have more than two subscripts
   Array of arrays
      Fixed rows and columns
        arrayType arrayName[][] = new
           arrayType[ numRows ][numColumns ];
          int b[][] = new int[ 3 ][ 3 ];
     Initializer   lists
        arrayType arrayName[][] = { {row1 sub-list},
           {row2 sub-list}, ... };
         int b[][] = { { 1, 2 }, { 3, 4 } };

     Can have variable rows and columns, too (ragged
                      Java Applets
   Java applets are programs that run on a java enabled
   Java applets do not have main methods.
       Use init() and paint() instead of main() or constructors
   To compile your program, use command:
        c:\> javac
   To run your program, use command:
        c:\> appletviewer my_html.html
   Applet Development Process:
     Step 1: Write the applet program
     Step 2: compile .java file and get .class file
     Step 3: create HTML file
     Step 4: test the applet using appletviewer
     Step 5: Publish the applet
              What can an applet do?
   Applets can use almost all java API capabilities.
   Applets have a great graphical capabilities.
       Applets can play sounds.
   Applets make the web page extremely interactive
   Applets can usually make network connections to the host
    they came from.
   Applets can interact with other applets on the same page.
What can an applet not do?
    An applet cannot load libraries or define native methods.
    It cannot read or write files on the host that's executing it.
        It cannot read certain system properties.
    It cannot make network connections except to the host
     that it came from.
    It cannot start any program on the host that's executing it.
    Windows that an applet brings up look different than
     windows that an application brings up.
              HTML Applet Tag
     CODE = “appletFile”
     WIDTH = “pixels”
  HEIGHT = “pixels”
Part 3
    Java Implementation of the OOP Model
    Java is a full object-oriented programming language.
    The class is the unit of Java programming. Java supports:
       Classes
       Inner classes
       Anonymous classes
       Abstract Classes
       Interfaces
    Java OOP is build on the single rooted hierarchy which means that all
     classes should be inherited from a single base class. In Java the name of
     this ultimate base class is simply “Object”.
    A class in Java represent a data type that Encapsulates data (attributes) and
     methods (behaviors) that are closely related.
                        Creating Packages (1)
   Packages
       Directory structures that organize classes and interfaces
            Mechanism for software reuse
   Creating packages
     Create a public class
     If not public, can only be used by classes in same package
     Choose a package name and add a package statement to
      source code file
     Compile class (placed into appropriate directory)
     Use Java standards in naming the packages.
                    Creating Packages (2)
   import
       Use import when classes are not of same package.
       If no package specified for a class, it is put in the default
        package which includes compiled classes of the current
       If class in same package as another, import not required
   Follow these steps to create a package:
       Create a directory called classes inside directory
       Use the following command for compilation:
        javac –d c:\jdk1.2\jre\classes
       Once the package has been created you can use import
        statement to use its classes.
      Creating Java Classes (1)
   A class in Java is just a blueprint telling what the
    objects created from it will look and act like.
   Every class in Java is a subclass of the ultimate base
    class “Object”
   Every Class has three components:
     Instance variables (Class Attributes).
     Member methods (Class Behavior)
     Constructors. ( For initialization and consistency)

   A class has a header (or heading) and a body
   Class body is delineated by braces { }
Creating Java Classes (2)
       Class Declarations
   For class declaration, we use one or more of the following:
      public = the class can be used by any class regardless of its package.
      abstract = the class cannot be instantiated.
      final = that the class cannot be subclassed.
      class NameOfClass = to indicate to the compiler that this is a class
       declaration and that the name of the class is NameOfClass.
      extends Super = to identify Super as the superclass of the class.
      implements Interfaces = to declare that the class implements one or
       more interfaces.
      Body defined within {}
                      Class Constructors
    All Java classes have constructors that are used to initialize a new
    object of that type.
   A constructor has the same name as the class. Example
     public Stack() {
          items = new Vector(10);
   Java supports name overloading for constructors so that a class can
    have any number of constructors. Example:
     public Stack(int initialSize) {
          items = new Vector(initialSize);
   The compiler differentiates these constructors based on the number of
    parameters in the list and their types.
   Constructors cannot return values. There is no return type, not even
Declaring Member Variables
    Member variables represent the state of the object.
    They should be initialized in some way when creating the
     object to make sure that the object is in a consistent state.
    We use modifiers when declaring Member variables.
Method Declaration
   Methods are the ways through which objects
    communicate with each other
   A method's declaration provides a lot of information
    about the method to the compiler, to the runtime
    system, and to other classes and objects
   We use modifiers when declaring Methods.
              Methods Overriding
   Overriding a method in a subclass means re-
    writing or modifying its code so that it acts
    differently from what it used to.
   Method overriding is related to a very important
    feature of OOP known as “polymorphism”
   Example: Overriding methods init() or
    paint() in applets.
Class Inheritance & Polymorphism
   Inheritance
     Constructing   one class from another
   E.g., constructing a Sphere from a Circle class:

   Polymorphism
     Provides the ability to redefine how methods of related
      classes operate based on the object being referenced
Managing Inheritance (1)
   Inheritance is a form of software reusability where
      New classes created from existing ones
      Subclasses absorb super-classes‟ attributes and behaviours
      Subclasses also add in their own attributes and behaviours
   The Object class defines and implements behavior that every class
    in the Java system needs.
   The following will be the hierarchy that every class in Java will end
    up part of.
Managing Inheritance (2)
   What Members Does a Subclass Inherit?
      Subclasses inherit those superclass members declared as public or
      Subclasses inherit those superclass members declared with no
       access specifier as long as the subclass is in the same package as
       the superclass.
      Subclasses don't inherit a superclass's member if the subclass
       declares a member with the same name.
   Hiding Member Variables
      Member variables defined in the subclass hide member variables
       that have the same name in the superclass. While this feature of the
       Java language is powerful and convenient, it can be a fruitful source
       of errors.
   Overriding Methods
      The ability of a subclass to override a method in its superclass
       allows a class to inherit from a superclass whose behavior is "close
       enough" and then supplement or modify the behavior of that
      Managing Inheritance (3)
   A Subclass is more specific than a superclass
   Every subclass can be described by its
    superclass, but not vice-versa
   Unlike C++, Java does not support multiple
   To inherit from a class use keyword extends
    class TwoDimensionalShape extends Shape
    { ... }
   Inheritance does also apply to Java interfaces.
             Derived Class Properties
   Derived class:
     Derived  from base
     Also called:
        Child   or Subclass
     Completely    new class
        Incorporates all the variables and methods of
         the base class
     Adds new data and method members
     Can override any base class method
   Permits the same method name to invoke:
       One response in objects of a base class
       Another response in objects of a derived class
       The determination of which overloaded method is
        actually called is made at run time
       Known as run-time binding
       Object being operated on ultimately determines the
        appropriate method to be called
              Overriding or Overloading
   Polymorphism translates from Greek as many forms ( poly –
    many, morph - forms)
   Method overloading is the primary way polymorphism is
    implemented in Java
   Overloaded methods appear in a subclass with same name but
    different parameter lists and return types
   Late-binding (or run-time binding) also supports overriding
   Overriding allows a subclass to re-define a method it inherits
    from it's superclass
       An over-ridden method in a subclass has the same
        signature (name and parameter list) and also the same
        return type (different from C++!)
Kinds of Inheritance
   Simple inheritance
     Each   derived type has only one immediate base type
   Multiple inheritance
     Derived   type has two or more base types
        Not   supported in Java

   Class hierarchies
     Illustrate   the order in which one class is derived from
    Being a Descendent of
    Object (1)
   The Object class sits at the top of the class hierarchy tree
    in the Java platform. This class defines the basic state and
    behavior that all objects must have.
   Your classes may want to override the following Object
       clone - equals/hashCode - finalize -
   Your class cannot override these Object methods:
    getClass - notify - notifyAll - wait
Being a Descendent of Object (2)
    The clone Method:You use the clone method to create an
     object from an existing object.
    The finalize Method: The Object class provides a method,
     finalize, that cleans up an object before it is garbage
    The toString Method: Object's toString method returns a
     String representation of the object.
    The getClass Method: The getClass method is a final
     method that returns a runtime representation of the class
     of an object.
    Your class cannot override these Object methods:
     getClass - notify - notifyAll - wait
Controlling Access to Class
Members (1)
   In Java, you can use access specifiers to protect both a
    class's variables and its methods when you declare them.
   The Java language supports four distinct access levels for
    member variables and methods: private, protected, public,
    and, if left unspecified, package.
   Private:
      The most restrictive access level is private.
      A private member is accessible only to the class in which
       it is defined. Inheritance does not apply on the private
       members. They are Just like secrets.
      Use private keyword to create private members.
               Controlling Access to
   Protected:
               Class Members (2)
     Allows the class itself, subclasses, and all
      classes in the same package to access the
     Use the protected access level when it's
      appropriate for a class's subclasses to have
      access to the member, but not unrelated
      classes. Protected members are like family
     To declare a protected member, use the
      keyword protected
                 Controlling Access to
                 Class Members (3)
   Public:
     The  easiest access specifier is public.
     Any class, in any package, has access to a
      class's public members.
     Declare public members only if such access
      cannot produce undesirable results if an outsider
      uses them.
     There are no personal or family secrets here; this
      is for stuff you don't mind anybody else knowing.
     To declare a public member, use the keyword
                     Controlling Access to
   Package
                     Class Members (4)
     The package access level is what you get if you don't
      explicitly set a member's access to one of the other levels.
     This access level allows classes in the same package as
      your class to access the members. This level of access
      assumes that classes in the same package are trusted
     To summarize:
                      Specifier class subclass package world
                      private       X

                      protected     X       X         X
                      public        X       X         X        X
                      package       X                 X
   Class scope
                        Class Scope
     Includes Instance variables and methods
     Class members are accessible to class methods. They can
      be referenced simply by name.
     Outside scope, cannot be referenced by name
     Visible (public) members accessed through a handle
         objectReferenceName.variableName or .methodName()
       Static public members can be accessed through class
        name like:, Font.PLAIN, System.out.print(“”);
   Block scope
       Variables defined in a method known only to that method
            If variable has same name as class variable, class variable is
             hidden in that method.
final Variables, Methods,
and Classes
   Declaring variables final
      Indicates they cannot be modified after declaration
            Indicate that they are constants
      Must be initialized when declared. Can not be changed after that
      Use all-caps identifiers. Example:
       private final int INCREMENT = 5;
   Declaring methods final
      Cannot be overridden in a subclass
      static and private methods are implicitly final
      You can only “hide” a static method:
            Static means one per class, not one for each object no matter how many instance of a class might
             exist. This means that you can use them without creating an instance of a class.Static methods are
             implicitly final, because overriding is done based on the type of the object, and static methods are
             attached to a class, not an object. A static method in a superclass can be shadowed by another
             static method in a subclass, as long as the original method was not declared final. However, you
             can't override a static method with a nonstatic method. In other words, you can't change a static
             method into an instance method in a subclass.
   Declaring classes final
      Cannot be a super-class (cannot inherit from it)
            All methods in class are implicitly final
        Static Class Members (1)
   Static variables
       Class data members are divided into two groups:
          Instance variables: every object of the class has its own copies
           of them.
          Class variables: they are allocated once for the class.

          All objects of class share the same class variable.

     Keyword static is used to create class variables.
     static class variables shared among all objects of class
            One copy for entire class to use
               • static class variables exist even when no objects do
       public static members
            Accessed through references or class name and dot operator
               • MyClass.myStaticVariable
       private static members
            Accessed through class methods.
    Static Class Members (2)
   static methods
     Can only access static members
     Have no this reference
            static variables are independent of objects
       They can be called even if no object is created.
   Examples:
     The main method in
       public static void main(String []args)
     Method exit() in
     Method showMessageDialog() in
      JOptionPane.showMessageDialog(. . .);
Initializing Objects
    Initialization is a must every time an object is created out
     of a class.
    Java compiler will initialize all class members and
     creating default constructors that initialize data members
     as follows: 0 for primitive numeric types, false for
     boolean, null for references.
    Initialization mainly happened in the class constructors.
    A class could have more than one way (constructor) of
    Initializers are passed as arguments to constructor
                 Object Instantiating
   Classes only describe data types. To put then in
    use at runtime, objects have to be created
    (instantiated) from them.
   “new” keyword is used to instantiate an object
    from a class. Example:
     public Font myFnt = new
        Font(“Arial”, Font.ITALIC, 12);
   No objects can be instantiated from Abstract
    classes. You can not use new here.
   Composition means that a class has
    references to other objects as members
        These   objects have to be initialized.
         • Default constructor or available constructors are
           used to initialize these objects.
   Composition is a powerful way of software
   Composition is related to the “has a”
    relationship in the OOP model.
      Using this Reference
   Each object has a reference to itself . It is called
    this reference
   Implicitly used to refer to instance variables and
   Used inside methods
   If a parameter or a local variable has the same
    name as an instance variable, use
    this.variableName to explicitly refer to the
    instance variable. Use variableName to refer to
    the parameter
   It helps clarify the program logic.
                        Abstract Classes
    Sometimes, a class that you define represents an abstract concept and,
    as such, should not be instantiated.
   For example, the Number class in the java.lang package represents
    the abstract concept of numbers. Number class makes sense only as a
    superclass to classes like Integer or Float.
   An abstract class is a class that can only be subclassed-- it cannot be
   To declare that your class is an abstract class, use the keyword abstract
    before the class keyword in your class declaration:
     abstract class Number { . . . }
   An abstract class may contain abstract methods, that is, methods with
    no implementation. In this way, an abstract class can define a complete
    programming interface, thereby providing its subclasses with the method
    declarations for all of the methods necessary to implement that
    programming interface.
Abstract methods cannot be:
   Abstract methods cannot be declared as:
       static or final
   final not allowed because it doesn‟t allow over-riding by
   static because you can only “hide” a static method:
       Static means one per class, not one for each object no matter
        how many instance of a class might exist. This means that you
        can use them without creating an instance of a class.Static
        methods are implicitly final, because overriding is done based
        on the type of the object, and static methods are attached to a
        class, not an object. A static method in a superclass can be
        shadowed by another static method in a subclass, as long as
        the original method was not declared final. However, you can't
        override a static method with a nonstatic method. In other
        words, you can't change a static method into an instance
        method in a subclass.
                Inner Classes
   Inner classes are classes defined inside other
   Inner classes have access to all the members of the
    outer classes.
   Usually we use inner classes as helper classes of
    adapter classes.
   Inner classes can be anonymous (without names)
   They are used intensively to write event listeners
    such as ActionListener, MouseListener, KeyListener,
    and the like.
Abstract Classes and Interfaces

    Abstract class:
      Can  only be used as a base class for another class
      Can not be instantiated
      Created using the abstract reserved word in the
       class header
      Typically contains one or more abstract methods:
         Method    does not contain a body, only a header
             • Derived classes must define abstract method
      Class   can also include non-abstract methods

           An Interface consists of constants and
            abstract methods only
              Syntax:
               interface interfaceName {
                   constant declarations;
                   abstract method declarations;
Interfaces (continued)

   Interface:

       Methods must be public and

       Constants must be public and final

       No need to actually use these modifiers
        in method and constant definitions since
        they‟re understood for an interface!
Implementing an interface

   Implementing an interface syntax:

      class className implements interfaceName
          override defns of all abstract methods;
                    Java Interfaces (1)
    An interface defines a protocol of behavior that can be
    implemented by any class anywhere in the class
   An interface defines a set of methods but does not
    implement them. A class that implements the interface
    agrees to implement all the methods defined in the
    interface, thereby agreeing to certain behavior.
   An interface is not part of the class hierarchy. Unrelated
    classes can implement the same interface.
   Two elements are required in an interface declaration--the
    interface keyword and the name of the interface.
   The public access specifier indicates that the interface can
    be used by any class in any package.
    Java Interfaces (2)
   An interface can inherit from one or more comma-
    separated superinterfaces using keyword extends.
   The interface body contains method declarations ; each
    followed by a semicolon (;). All methods declared in an
    interface are implicitly public and abstract.
   An interface can also contain constant declarations. All
    constant values defined in an interface are implicitly
    public, static, and final.
Implementing an Interface
   An interface defines a protocol of behavior. A class that
    implements an interface adheres to the protocol defined
    by that interface.
   To declare a class that implements an interface, include
    an implements clause in the class declaration.
   Your class can implement more than one interface (the
    Java platform supports multiple inheritance for interfaces.
    For instance,
    public class StockApplet extends Applet
       implements StockWatcher {
       public void valueChanged(String
          tickerSymbol, double newValue){…}
Simulated Multiple
   Since Java does not support direct multiple
    inheritance, it provides an alternate mechanism
    to allow for the full power of multiple inheritance
   This is via implementation of multiple interfaces,
    as needed
   This also supports polymorphism (with run-time
    binding) as an interface reference variable (but
    NOT an interface object as you CANNOT
    instantiate interfaces) can point to an object of
    any descendant class that implements that
      The methods of the interface are over-ridden
        in the descendant classes that implement that
Part 4
    Java OOP Design Issues
UML Diagram Types
   Class         Component
   Object        Deployment
   State         Collaboration
   Sequence
   Activity
   Use-case

   • Objects have three responsibilities:
 What they know about themselves – (e.g., Attributes)
 What they do – (e.g., Operations)
What they know about other objects – (e.g., Relationships)
            Defining Class
  A CLASS is a template (specification, blueprint)
  for a collection of objects that share a common
  set of attributes and operations.

Class                       attributes

   The three basic relationships include:
       Association (between objects) – relationships that are
        described as “has-a”

       Aggregation (between objects) – “composed-of” (strong
        aggregation/composition) and “consists-of” (weak
            Aggregations (weak and strong/composition) are
             considered a more tightly coupled type of association and
             also have the same multiplicities/cardinalities

       Generalization (between classes) – “is-a”
                    • Relationships
       A RELATIONSHIP is what a class or an object
          knows about another class or object.

 Generalization (Class-to-Class) (Superclass/Subclass)
   • Inheritance
   • Ex: Person - FacultyPerson, StudentPerson, Staff...
   • Ex: ModesOfTravel - Airplane, Train, Auto, Cycle, Boat...
 [Object] Associations
   • FacultyInformation - CourseInformation
   • StudentInformation - CourseInformation
 [Object] Aggregations & Composition (Whole-Part)
   • Assembly - Parts
   • Group - Members
   • Container - Contents
Java Programming Styles (1)
    Packages:
      Package names are entirely in lower case.
      Package name should start with the web domain
       name reversed
      Examples:
    Files:
        The file name must have the same base name as the
         name of the public class defined in the file.
             Example:
                  – If you have a public class named “RecordList”,
                    the file containing this class should be named
Java Programming Styles (2)
   Classes and Interfaces:
    Use  meaningful identifiers for classes
     , and interfaces.
    Capitalize each word contained in a
     class identifier name.
    No underscores.
        Examples:
            public class RecordList {…}
            public interface PanelFace {…}
Java Programming Styles (3)
   Variables:
     Use meaningful identifiers for variables.
     Capitalize each word contained in a name of a variable
      except the first word.
     Use nouns to identify variables as possible.
     For boolean variables, use identifirs that are like
     Use all-caps indentifiers for constants.
           Examples:
              int number;
              String myName;
              boolean isValid;
              final int CODE = 707;
Java Programming Styles (4)
   Methods:
     Use meaningful identifiers for methods.
     Capitalize each word contained in a name of a
      method except the first word.
     Use verbs to identify methods as possible.
     For the methods dealing with objects’ properties,
      start the method identifier with get or set.
     If the method returns boolean use “is” or “are”
      instead of get to name this method.
           Examples:
             private boolean paint()…
             boolean isObjectValid()…
             Font getFont()…
             void setFont(Font f)…
    Java Programming Styles (5)
   General Considerations:
       Use three-space indentation style. Example
         if(num < 10)
             System.out.println(“Not Enough”);
       Use comments to mark the beginning and the end of blocks
       Use three-line style to comment your code. Use either one of:
         //                           /*
         // This part is to … or * This part is to …
         //                             */
       Use empty lines to increase the readability of your code
       Use spaces between the operators such as +, -, =, … and the
        operands. Example:
         c = a + b;
    Software Reusability Issues
   Software
        Constructed from existing, well-defined, carefully tested,
         portable, widely available components
             Speeds development of powerful, high-quality software
   Use library classes as much as you can
   Never re-invent the wheel
   Organize your code so that you can use it again.
   Apply principle of least privilege
        Each component has enough access to accomplish
         its task, nothing more
             Prevents accidental/malicious errors
Using Set and Get Methods
   Set methods (Mutator methods)
     public method that sets private variables
     Does not violate notion of private data
            Change only the variables you want
       Called mutator methods (change value)
   Get methods (Accessor methods)
     public method that displays private variables
     Again, does not violate notion of private data
            Only display information you want to display
       Also called accessor or query methods
   If implementation changes
       Clients can still use the same methods
            Do not know implementation details
Documentation Generator
   Java has its own standard tool for creating API
    documentation on the fly. This tool is “javadoc”.
   javadoc goes through the source files looking for
    a comment of the style /** … */ to add to the
   The result of the javadoc utility is HTML
    documentation that is the same as the Java
    standard API documentation in format.
Part 5
    Java Essentials API
             AWT to Swing
   AWT: Abstract Windowing Toolkit
        import   java.awt.*
   Swing: new with Java2
        import javax.swing.*
        Extends AWT

        Tons o‟ new improved components

        Standard dialog boxes, tooltips, …

        Look-and-feel, skins

        Event listeners

   API:
GUI Component API
   Java: GUI component = class

     Properties

     Methods

     Events
                         Using a GUI Component
1.   Declare it
             Declare object: JButton b;
2.   Create it
             Instantiate object: b = new JButton(“press me”);
3.   Configure it
             Methods:    b.setText(“press me”);
4.   Add it
             contentPane.add(b);                     JButton
5.   Listen to it
             Events: Add Listeners for its events!
   Anatomy of an Application GUI
            GUI                   Internal structure

JFrame                                 JFrame
 JPanel             containers


                                 JButton        JLabel
       Using a GUI Component 2
1.   Create it                       order is
2.   Configure it                    important
3.   Add children (if container)
4.   Add to parent (if not JFrame)
5.   Listen to it
                     Build from bottom up
   Create (bottom-up):
        Frame                                      JButton
        Panel

        Components    & their Listeners
   Add (top-down):                            JPanel
        listenersinto components
        components into panel

        panel into frame

JFrame f = new JFrame(“title”);
JPanel p = new JPanel( );
JButton b = new JButton(“press me”);

p.add(b);              // add button to panel
f.setContentPane(p);   // add panel to frame

                                  press me
                  Application Code
import javax.swing.*;

class hello {
   public static void main(String[] args){
       JFrame f = new JFrame(“title”);
       JPanel p = new JPanel();
       JButton b = new JButton(“press me”);

        p.add(b);              // add button to panel
        f.setContentPane(p);   // add panel to frame

                                              press me
Layout Managers
   Automatically control placement of
    components in a panel
         Layout Manager Heuristics
        null             FlowLayout        GridLayout

                         Left to right,
                        Top to bottom
     sets x,y,w,h

BorderLayout             CardLayout       GridBagLayout

w         c         e   One at a time          JButton

JButton JButton

                             JButton    JButton
              n             JPanel: FlowLayout
     JPanel: BorderLayout

              Code: null layout
JFrame f = new JFrame(“title”);
JPanel p = new JPanel( );
JButton b = new JButton(“press me”);

b.setBounds(new Rectangle(10,10, 100,50));
p.setLayout(null);       // x,y layout
f.setContentPane(p);               press me
                   Code: FlowLayout
    Set layout manager before adding components

JFrame f =   new JFrame(“title”);
JPanel p =   new JPanel( );
FlowLayout   L = new FlowLayout( );
JButton b1   = new JButton(“press me”);
JButton b2   = new JButton(“then me”);

                                          press me then me
                   Applets                     JApplet

   JApplet is like a JFrame                 contentPane
   Already has a panel
   Access panel with JApplet.getContentPane()

import javax.swing.*;                          JButton

class hello extends JApplet {
  public void init(){
      JButton b = new JButton(“press me”);
                 Applet Methods
   Called by browser:

     init()    - initialization
     paint()   - redraw stuff („expose‟ event)
     start()   - resume processing (e.g. animations)
     stop()    - pause
     destroy() - cleanup
                        Application + Applet
import javax.swing.*;

class helloApp {
   public static void main(String[] args){         Command line         Browser
         // create Frame and put mainPanel in it
         JFrame f = new JFrame(“title”);
         mainPanel p = new mainPanel();
   }                                                  JFrame    or      JApplet

class helloApplet extends JApplet {                                  contentPane
   public void init(){
         // put my mainPanel in the Applet
         mainPanel p = new mainPanel();

// my main GUI is in here:
class mainPanel extends JPanel {
         setLayout(new FlowLayout());
         JButton b = new JButton(“press me”);              JButton
           Applet Security
   Applets are in a “sandbox”
   No read/write on client machine
   Can‟t execute programs on client machine
   Communicate only with server
   “Java applet window” Warning
Swing Container Idioms…
    Before Java 2, each Top-Level Container had only one layer.
    Java 2 top-level Containers (JFrame, JApplet, etc.) have several layers (panes): root, content,
     layered, and glass.
         Programs normally reference only the content pane.
    You can add Components (like JButtons, etc.) to the main Container (contentPane) of any Top-
     Level Container (e.g., JFrame, JApplet, JDialog, etc.) using one of the following idioms:
    1.    Use the existing content pane: use a Container (ancestor class) object that points to the current Frame's
          contentPane (assuming your class extends JFrame, e.g.)
              class MyWindow extends JFrame {
                  MyWindow() { // constructor
                    Container content = getContentPane(); // Use the default content pane.
    2.    Create your own contentPane using a JPanel pane and set it as the contentPane of the current Top-
          Level Container
              class MyWindow extends JFrame {
                  MyWindow() { // constructor
                    JPanel content = new JPanel(); // Create a new content pane.
    3.    Don‟t extend JFrame at all and just create a new JFrame and add everything to its contentPane (by
          getting a Container reference to it or just using getContentPane().add())
              class MyWindow {
                  MyWindow() { // constructor
                    mainFrame = new JFrame(str1);
                    Container content = mainFrame.getContentPane();
The Root Pane
   Most Swing
    (like JFrame,
    JWindow, and
    contain an
    instance of
    another class,
    as their only
    and implement
    a common
More details about containers,
content panes, etc.

               What is the layout of the panes? It‟s all
                centered around a special container
                called JRootPane, as shown above,
                that extends JComponent
               Contains fixed set of components: a
                Component called glassPane and
                another JLayeredPane called
               The layeredPane contains two other
                Components: a JMenuBar and a
                Container called the contentPane
                Java API
   One of the most powerful freatures of Java is that it is an
    extensible language in the sense that new API libraries
    are always added to it.
   Java mainly comes with the following API‟s:
     java.lang              -
     java.util              -
              -   java.beans
     java.rmi               -   java.sql
   Java also has a huge collection of windowing classes
    called JFC(Java Foundation Classes) which include:
     Swing collection              - AWT collection
     Drag and drop collection      - look and feel collection
     Accessibility collection
      Java I/O
    Java I/O capabilities are based on the concept of “streams”.
    A stream is an ordered sequence of bytes that have a source and
     destination like this

    Java stream classes are divided into two class hierarchies, based on the
     data type on which they operate.
    Are either characters or bytes
    Generally, the algorithms for sequentially reading and writing data are
     basically the same:
    Reading                            Writing
      open a stream                       open a stream
      while more information              while more information
           read information                     write information
      close the stream                    close the stream
Character Streams
Byte Streams
                Standard I/O
   The term standard I/O refers to the Unix concept of a
    single stream of information that is used by a program.
   E.g, stdin, stdout, and stderr
   Following the standard I/O model, Java has, System.out, and System.err.
    System.out, and System.err are already pre-
    wrapped as a PrintStream object, so they can be used
    write away.
 must be wrapped before you can read from
Standard I/o-Example
public class StdInRead {
   public static void main(String[] args)
      throws IOException
       "Enter Your input. Empty line to exit.\n");
      BufferedReader in =
         new BufferedReader(
            new InputStreamReader(;
      String s;
      while((s = in.readLine()).length() != 0)
         System.out.println("YOU ENTERED: " + s);
    Accessing File System
   Java provides class File to let you deal with the files and
   It is an abstract representation of file and directory
   Using File you can do things like:
     Checking whether or not files exists/Deleting them
     Creating/renaming/listing contents of directories
     Checking the path names
     Creating new files
     Creating the URL of the files
  Using Files – An Example
public class Files
   public static void main (String []args)
      File d = new File("c:/jdk1.3/bin");
      File[] f= d.listFiles();
      for(int i = 0; i < f.length; i++)
Reading / writing Files
public class Copy {
   public static void main(String[] args)throws
       IOException {
      File inputFile = new File(“oldfile.txt");
      File outputFile = new File(“newfile.txt");
      FileReader in = new FileReader(inputFile);
      FileWriter out = new
      int c;
      while ((c = != -1)
    Concatenating Files
public class Concatenate {
   public static void main(String[] args) throws
       IOException {
      File inF1 = new File(“f1.txt");
      File inF2 = new File(“f2.txt");
      FileInputStream in1 = new FileInputStream(inF1);
      FileInputStream in2 = new FileInputStream(inF2);

        SequenceInputStream s = new
         SequenceInputStream(in1, in2);
        int c;
        while ((c = != -1)
                        Object Serialization
   Java‟s object serialization allows you to take any object that implements
    the Serializable interface and turn it into a sequence of bytes that can
    later be fully restored to regenerate the original object.
   Object serialization is interesting because it allows you to implement
    lightweight persistence.
   Object serialization was added to the language to support two major
    features; Java‟s (RMI) and JavaBeans.
   To serialize an object, you create some sort of OutputStream object and
    then wrap it inside an ObjectOutputStream object. At this point you need
    only call writeObject( ) and your object is serialized and sent to the
   To reverse the process, you wrap an InputStream inside an
    ObjectInputStream and call readObject( ).
Object Serialization
class Data implements Serializable {
   int i;
   Data(int x) { i = x; }
   public String toString() { return "THE DATA IS " + i; }
public class Serialize {
   public static void main(String[] args)
      throws IOException, ClassNotFoundException {
      Data dout = new Data(100);
      System.out.println("OUT OBJECT:: " + dout.toString());
      ObjectOutputStream out = new ObjectOutputStream(
         new FileOutputStream("data.out"));
      out.writeObject(dout);     out.close();
      ObjectInputStream in = new ObjectInputStream(
         new FileInputStream("data.out"));
      Data di = (Data) in.readObject();   in.close();
      System.out.println("IN OBJECT:: " + di.toString());
               Exception Handling
   The basic philosophy of Java is that “badly
    formed code will not be run.”
   The ideal time to catch an error is at compile-
    time, before you even try to run the program.
   However, not all errors can be detected at
    compile-time. The rest of the problems must be
    handled at run-time.
        JDBC (Introduction)
   A great promise of Java has been the ability to build platform-
    independent client/server database applications. This has come to
    fruition with Java DataBase Connectivity (JDBC).
   JDBC is designed to be platform-independent, so you don‟t need to
    worry about the database you‟re using while you‟re programming
   JDBC, like many of the APIs in Java, is designed for simplicity. The
    method calls you make correspond to the logical operations you‟d
    think of doing when gathering data from a database: connect to the
    database, create a statement and execute the query, and look at the
    result set.
   To allow this platform independence, JDBC provides a driver manager
    that dynamically maintains all the driver objects that your database
    queries will need
                   Database URL
   To open a database, you must create a “database
    URL” that specifies:
       That you‟re using JDBC with “jdbc.”
       The “subprotocol”: the name of the driver or the name of
        a database connectivity mechanism. Since the design of
        JDBC was inspired by ODBC, the first subprotocol
        available is the “jdbc-odbc bridge,” specified by “odbc.”
       The database identifier. This varies with the database
        driver used, but it generally provides a logical name that
        is mapped by the database administration software to a
        physical directory where the database tables are
       In windows it is usually called DSN.
       Example:
        String dbUrl = "jdbc:odbc:people";
    Getting JDBC To Work (1)
   STEP 1: Find the JDBC Driver
     To   Locate the driver we use the following:
       catch(SQLException exp){
         System.err.println("Failed to connect");
     Ifthe statement above does not catch any
      exceptions it means that the driver is loading
    Getting JDBC To Work (2)
   STEP 2: Configure the database
      From   Control Panel create a DSN for your data
      The DSN you create in this step will part of the
       database URL discussed in a previous slide
      Example:
        If your DSN is named “emaildsn”, the database URL
           will be like:
         String dbUrl = "jdbc:odbc:emaildsn";
Getting JDBC To Work (3)
   STEP 3: Connect and Test the Configuration
   We use the following to connect to a datadase:
     Connection c = DriverManager.getConnection(
      dbUrl, user, password);
    catch(SQLException exp){
      System.err.println("Failed to connect");
   If the statement above does not catch any
    exceptions, it means that the configurations are
    correct and the connection is established
Getting JDBC To Work (4)
   STEP 4: Generate your SQL Queries
       Use something like:
         Statement s = c.createStatement();
         ResultSet r = s.executeQuery( “SQL QUERY");
       The ResultSet object “r” contains the result coming back
        from the database. The following loop can be used to print
        the results.
         while( {
              r.getString(“FIELD 1") + ", "
              + r.getString(“FIELD 2“) + . . .);
       Close the statement and result ser objects using:
    Updating The Database
   Updating a database means changing the data or the
    structure of a database.
   We usually update a database by executing one of the
    following SQL commands:
     DELETE
     UPDATE
     ALTER
     INSERT
   To update a database in JDBC we use method
    executeUpdate() instead of executeQuery()
    method in the statement object.
               Batch Jobs
   JDBC allows programmers to create a list of SQL
    commands that can be sent as a batch to the
    database drivers.
 Use method addBatch(String sql) in
  a statement object to add the given SQL
  command to the current list of commands
  for this Statement object.
 The commands in this list can be executed
  as a batch by calling the method
JDBC/ODBC Overview
     Introduction to JDBC/ODBC
   ODBC (Open Database Connectivity) is an API
    introduced by Microsoft that allows applications to
    access databases by using SQL.
   By using ODBC, a single application can access
    remote databases under different DBMSs (i.e.,
    Informix, Oracle, Sybase, etc.)
   The idea behind ODBC is to have a single API to
    interact with a database
     However,    there is a lot of work to be done in order
      to get all operating systems to use ODBC, and that
      may not be possible or even desirable given that
      there is JDBC.
                      Open ODBC Standards
   The X/Open Group and ISO have made ODBC a standard, though
    there are differences from this standard and the Microsoft
      ODBC can be used on UNIX/Linux systems using products provided
        by third party software vendors and the Free Software Foundation.
      OpenAccess, from provides UNIX clients
        ODBC connectivity to Windows based databases.
      unixODBC, from is a freeware
        implementation of ODBC available for Linux/FreeBSD systems.
   ODBC relies on data drivers to convert the ODBC calls to different
    database formats.
   At development time, the application developer only needs to
    know the ODBC calls to connect to a database, execute SQL
    statements, and retrieve results.
n-Tier Architectures   Database server
                          (someone else‟s
                          C program)

    1-tier

    2-tier

    3-tier
   Setup a database for Web access
   Load a driver
   Connect to database
   Create Statement
   Execute Statement
   Process the results
             Remember to catch errors
Web access to a Database
   Basic steps
    •   Create a Database (e.g., MS Access or FoxPro)
    •   Create the data source using the ODBC
    •   In Windoze 98, etc.: Open StartControl
        PanelODBC Data Sources (32bit)
    •   OR in WinXP, etc.: Open StartControl
        PanelAdministrative ToolsODBC Data Source
    •   Click System DSN tab then Add button
Click System DSN tab then Add button
Choose the ODBC Driver and press Finish button
Give new Data Source Name, Description and
path of the Database then press OK
To Configure/Re-Configure a Connection
press File DSN tab, Add, choose Driver and
give same data source as System DSN
Give the path of the database
   Java DB connectivity API
   Similar to ODBC
   Why do you need it:
    Simple API
JDBC Architecture
   Supports n-Tier architectures
   Tabular data handling
   SQL but
    not only SQL
    JDBC Driver Types

•   JDBC database drivers are classified into four types based on
    the nature of the driver provided
    1. Bridges. Convert from JDBC to another standard for
        example ODBC. That standard then converts into the
        vendor specific API.
    2. Part Java part Native. Driver contains some Java code
        and some Native code
    3. Intermediate Server. JDBC talks directly to a separate
        server which then converts from JDBC to native API
        (great for intranets)
          1. Pure Java. JDBC driver converts directly to
              native API and sends through vendor specific
              network protocol (great for intranets)
                                            CCTM: Course material developed by James King (
    JDBC-ODBC Bridge
• Microsoft has developed the standard ODBC Open DataBase Connectivity as
  a windows specific standard. It converts from ODBC to the vendor’s native
• The JDBC driver converts from JDBC to ODBC.
• This is the only way to access Microsoft Access because MS Access does not
  provide direct access to its own API.
• Requires you have ODBC and JDBC drivers installed
• This makes accessing Microsoft Access via Java slow and less reliable
  because two sets of conversion and divers are required

     Java application   application process                                     Data source

                                              ODBC process

       JDBC API         JDBC-ODBC Bridge        ODBC API                        ODBC Layer

                                                     CCTM: Course material developed by James King (
 The Driver manager
• It is possible that a Java application may need to talk to multiple
  databases, possibly from different vendors (especially if it is a
  distributed system)
• The JDBC driver manager provides the ability to communicate with
  multiple databases and keep track of which driver is needed for which
• Even if you only talk to one database you need to connect to it via the
  driver manager
                               JDBC Driver Manager

               ODBC             Oracle Driver                      XYZ Driver

              Access               Oracle                             xyzBase
                                                     CCTM: Course material developed by James King (
  Java JDBC Programming Model
– DriverManager allows you to connect to one or more to databases
– Connection represents the connection to a single database
– Statement contains an SQL statement to be sent down the connection
  to be executed by the database
– ResultSet contains the results of an SQL query such as SELECT

                                          Driver Manager                            Database
SQL            Statement

SQL            Statement

                                             CCTM: Course material developed by James King (
Java JDBC Programming Steps
          Class.forName() loads the DriverManager
           DriverManager.getconnection() connects to a database and
           returns a Connection object

           Connection.createStatement() provides a Statement object you
           can insert SQL into

                                         CCTM: Course material developed by James King (
             The JDBC Steps
1. Importing Packages
2. Registering the JDBC Drivers
3. Opening a Connection to a Database
4. Creating a Statement Object
5. Executing a Query and Returning a Result Set
6. Processing the Result Set
7. Closing the Result Set and Statement Objects
8. Closing the Connection
1: Importing Packages
  // Program name:
  // Purpose: Basic selection using prepared

    //Import packages
    import java.sql.*; //JDBC packages
    import java.math.*;
    import oracle.jdbc.driver.*;
2: Registering JDBC Drivers

   class LecExample_1a {

   public static void main (String args []) throws
     SQLException {

   // Load Oracle driver
   DriverManager.registerDriver (new
JDBC Universal Resource
Locators (URLs)

     Provides a way of identifying a database
      Allow different drivers to use different
       schemes for naming database
      Allow driver writers to encode all
       necessary connection information within
      Allow a level of indirection
Step 3: Connecting to a Database, part I

   • The getConnection method of DriverManager requires the name of the database to
    connect to, the name of the user connecting and their password it returns a Connection
   •The syntax for the name of the database is a little messy and is unfortunately
    Driver specific

   •A JDBC URL represents a driver and has following three-part syntax

  Protocol: JDBC is                           Subname: indicates the location
                        identifies a
  the only protocol                           and name of the database to be
      in JDBC                                   accessed. Syntax is driver

Step 3: Connecting to a Database, part II
The DriverManager allows you to connect to a database using the specified JDBC driver,
 database location, database name, username and password.
It returns a Connection object which can then be used to communicate with the database.

The password is passed to the database in plain text and therefore anyone who can see

 the .java or .class file can find out the password!

                                                                          Password in plain
                                      Vendor of database,                  text!!!!!!!!!!!!!!!
                                   Location of database server
                                     and name of database            Username

Connection connection =
3: Opening connection to a Database
   //Prompt user for username and password
     String user;
     String password;

     user     = readEntry("username: ");
     password = readEntry("password: ");

   // Connect to the local database
     Connection conn =
     ", user, password);
4. Creating a Statement Object
   // Query the hotels table for resort =
     'palma nova’
   // Please notice the essential trim
   PreparedStatement pstmt =
     conn.prepareStatement ("SELECT
     hotelname, rating FROM hotels WHERE
     trim(resort) = ?");
   pstmt.setString(1, "palma nova");
Step 5: Executing SQL (Querying the Database)

     SQL which queries the database uses the executeQuery method of Statement
     ExecuteQuery returns a ResultSet which we can then look at to see what records
      matched the query
     Lets assume the database has a table called test with a single column called value
     We will list the entire table in SQL this would be SELECT * FROM test

                                                SQL statement surrounded by " "
 Contains the any matched records

  ResultSet rs=statement.executeQuery("SELECT * FROM test");
Step 6: Processing the Returned Data, part I

  • When executeQuery has finished it returns a ResultSet.
  • ResultSet has an internal pointer which can be moved forward and backwards.
    You can only retrieve the values of the record it points at.
      • Next(), Previous(), First() and Last() move the internal pointer between
        records they return true if the record is valid
           •So if the pointer is already on the first record and you use previous it will
           return false etc.
      • isLast() and isFirst() return true if the pointer is at the last or first record

                    Internal Pointer         ResultSet

              Record 1            Record 2               Record 3       Record 4
Step 6: Processing the Returned Data, part II

       • The pointer points at the record to retrieve.
       • However, we still have to get the value of each of its columns

                          Name of the field inside the record to fetch

       • GetString("name") returns the value of the column called name as a String
       • GetInt("name") returns the value of the column name as a int etc...

  while (                        Moves to the next record and returns true if
   {                                       the record is valid. If the record is not valid
   int value=rs.getInt("value");                          the loop exits

                              NOTE this code will not skip the first record because
              Do              the pointer starts one before the first record!
          with value
5. Executing a Query,
   Returning a Result Set Object &
6. Processing the Result Set
ResultSet rset = pstmt.executeQuery ();

// Print query results
while ( ())
      System.out.println (rset.getString (1)+" "+ rset.getString(2));
7. Closing the Result Set and Statement Objects
8. Closing the Connection

    // close the result set, statement, and the connection
ODBC JDBC Example using Microsoft Access
                   From Core Java 2
                   by Cay Horstmann
                   Screen displays by Dongchan Choo
Example: Make DB

   Create a MS Access file called “mssql1”

   Create DSN for “mssql1”
     Go to Start (in MS window)
     Go to control panel
     Go to Data Source ODBC
Example: Make DB(con’t)
   Select “System DSN”
   Select “Add”
Example: Make DB(con’t)
   Select “MS Access Driver”
Example: Make DB(con’t)
   Input Data Source Name: mssql1
   Select “source”
Example: Make DB(con’t)
   Select Database Name by directory
                  Example: Make DB
Create “Books1.dat” file using Note Pad
                    Example: Make DB
Create “” file
import java.sql.*;
import java.util.*;
class MakeDB1
{ public static void main (String args[])
  { try
    { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
       Connection con = DriverManager.getConnection(
          "jdbc:odbc:mssql1", "", "");
                    Example: Make DB
Statement stmt = con.createStatement();
     String tableName = "";
     if (args.length > 0)
        tableName = args[0];
     { System.out.println("Usage: MakeDB TableName");

     BufferedReader in = new BufferedReader(new
      FileReader(tableName + ".dat"));
                     Example: Make DB
createTable(tableName, in, stmt);
     showTable(tableName, stmt);
                            Example: Make DB
         catch (IOException ex)
         { System.out.println("Exception: " + ex);
           ex.printStackTrace ();}
         catch (Exception e)
        { System.out.println("Error: " + e.toString()
               + e.getMessage());}

Example: Make DB
public static void createTable(String tableName,
   BufferedReader in, Statement stmt)
   throws SQLException, IOException
 { String line = in.readLine();
   String command = "CREATE TABLE " + tableName
      + "(" + line + ")";

     while ((line = in.readLine()) != null)
     { command = "INSERT INTO " + tableName
         + " VALUES (" + line + ")";
       stmt.executeUpdate(command);         }
Example: Make DB
public static void showTable(String tableName,
   Statement stmt) throws SQLException
 { String query = "SELECT * FROM " + tableName;
   ResultSet rs = stmt.executeQuery(query);
   ResultSetMetaData rsmd = rs.getMetaData();
   int columnCount = rsmd.getColumnCount();
   while (
   { for (int i = 1; i <= columnCount; i++)
     { if (i > 1) System.out.print(", ");
        System.out.print(rs.getString(i));  }
   rs.close(); } }
SQL Review
  Including transactions, stored procedures,
  PL/SQL vs. SQLJ, etc.
Standard Query Language (SQL)
    Composed of two categories:
    Data Manipulation Language (DML)
      used   to manipulate the data
         select

         delete

         update

    Data Definition Language (DDL)
      create database
      create table
      drop database
    Data Manipulation Language
   SELECT - query the database
     select   * from customer where id > 1001
   INSERT - adds new rows to a table.
     Insert   into customer values (1009, „John Doe‟)
   DELTE - removes a specified row
     delete

   UPDATE - modifies an existing row
     update    customers set amount = 10 where id >
Data Definition Language
       CREATE DATABASE - allows you
        to create a database
       CREATE TABLE - allows you to
        create a table definition in a
       DROP TABLE - removes a table
        from a database
       ALTER TABLE - modifies the
        definition of a table in a database
   A transaction consists of one or more statements that
    have been executed, completed, and then either
    committed or rolled back (commit or rollback).
   A new connection is in auto-commit mode by default.
   If auto-commit mode is disabled, the transaction will not
    terminate until the method commit or rollback is invoked
   JDBC-compliant drivers must support transactions
   DatabaseMetaData gives information on the level of
    transaction support
         Stored Procedures
   A Stored Procedure is written in a metalanguage
    defined by the DBMS vendor
   Used to batch or group multiple SQL statements that
    are stored in executable form at the database
   Written in some internal programming language of the
        Oracle‟s PL/SQL
        Sybase‟s Transact-SQL
    one DBMS to another (with the exception of the SQLJ
    standard, which allows you to write SQL in standard
    Java and have that understood by any DBMS that
    supports the SQLJ standard).
    Why Use Stored Procedures?
   Faster Execution of SQL (compiled and in-memory stored query
   Reduced Network Traffic
   Modular Programming
   Automation of complex or sensitive transactions
   Syntax checking at time of creation of SP
   Syntax supports if, else, while loops, goto, local variables, etc., all
    of which dynamic SQL doesn‟t have
SQLJ vs JDBC comparison
                    SQLJ      JDBC
  SQL s tatem ents static     dy namic

  Strong typing     y es      no

  Checking          static    runtime only

  Syntax            concise   API

  Standard          ANSI      Sun

  Portable          y es      y es

  Object s upport   y es*     y es*
Use SQLJ to write your
program when
   you want to be able to check your program
    for errors at translation-time rather than at
   you want to write an application that you can
    deploy to another database. Using SQLJ, you
    can customize the static SQL for that
    database at deployment-time.
   you are working with a database that contains
    compiled SQL. You will want to use SQLJ
    because you cannot compile SQL statements
    in a JDBC program.
Use JDBC to write your
program when
   your program uses dynamic SQL. For
    example, you have a program that builds
    queries on-the-fly or has an interactive
   you do not want to have a SQLJ layer during
    deployment or development. For example,
    you might want to download only the JDBC
    Thin driver and not the SQLJ runtime libraries
    to minimize download time over a slow link.
SQLJ static and non-static SQL
      The standard covers only static SQL operations
        those that are predefined and do not change in real-time
         as a user runs the application
        of course the data values that are transmitted can change
      Oracle SQLJ offers extensions to support dynamic SQL
          those that are not predefined, where the operations
           themselves can change in real-time.

      It is possible to use dynamic SQL operations through
       JDBC code or PL/SQL code within a SQLJ application.

      Typical applications contain much more static SQL than
       dynamic SQL.
Java and SQLJ versus PL/SQL I
    Java and PL/SQL are complementary.
    Suited for different kinds of applications.

    PL/SQL is better for SQL-intensive applications.
      Optimized for SQL, and so SQL operations are faster
       in PL/SQL than in Java.
      Uses SQL datatypes directly, while Java applications
       must convert between SQL datatypes and Java
    Java, is better for logic-intensive applications.
      Superior programming model.
      Java's more general type system is better suited than
       PL/SQL for component-oriented applications.
Interoperability: SQLJ and PL/SQL
     PL/SQL programs
       transparently call Java stored procedures, enabling
        you to build component-based Enterprise JavaBeans
        and CORBA applications.
       have transparent access to a wide variety of existing
        Java class libraries through trivial PL/SQL call

     Java programs
       call PL/SQL stored procedures and anonymous blocks
        through JDBC or SQLJ.
       SQLJ provides syntax for calling stored procedures
        and functions from within a SQLJ statement, and also
        supports embedded PL/SQL anonymous blocks within
        a SQLJ statement.
ReadEntry method (for completeness)
   // Method: readEntry
   // Purpose: to read a string from the user and return it
   // Input:   The prompt string
   // Output: User entry

   static String readEntry (String prompt)
        StringBuffer buffer = new StringBuffer ();
        System.out.print (prompt);
        System.out.flush ();
        int c = ();
        while (c != '\n' && c != -1){
      buffer.append ((char)c);
      c = ();
        return buffer.toString ().trim ();
      catch (IOException e){
        return "";
Java Servlets
    Core Servlets & JSP book:
    More Servlets & JSP book:
    Servlet and JSP Training Courses:
   Java servlets
   Advantages of servlets
   Servlet structure
   Servlet examples
   Handling the client request
     FormData
     HTTP request headers
               A Servlet’s Job
   Read explicit data sent by client (form data)
   Read implicit data sent by client
    (request headers)
   Generate the results
   Send the explicit data back to client (HTML)
   Send the implicit data to client
    (status codes and response headers)
Why Build Web Pages Dynamically?
   The Web page is based on data submitted by the
     E.g., results page from search engines and order-
      confirmation pages at on-line stores
   The Web page is derived from data that changes
     E.g.,   a weather report or news headlines page
   The Web page uses information from databases
    or other server-side sources
     E.g., an e-commerce site could use a servlet to
      build a Web page that lists the current price and
      availability of each item that is for sale.
The Advantages of Servlets Over
“Traditional” CGI
   Efficient
     Threads  instead of OS processes, one servlet copy,
   Convenient
     Lots   of high-level utilities
   Powerful
     Sharing    data, pooling, persistence
   Portable
     Run    on virtually all operating systems and servers
   Secure
     No   shell escapes, no buffer overflows
   Inexpensive
     There     are plenty of free and low-cost servers.
               Simple Servlet Template
import javax.servlet.*;
import javax.servlet.http.*;

public class ServletTemplate extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {

        // Use "request" to read incoming HTTP headers
        // (e.g. cookies) and HTML form data (query data)

      // Use "response" to specify the HTTP response
      // code and headers (e.g. the content type,

        PrintWriter out = response.getWriter();
        // Use "out" to send content to browser
A Simple Servlet That Generates Plain Text
 import javax.servlet.*;
 import javax.servlet.http.*;

 public class HelloWorld extends HttpServlet {
   public void doGet(HttpServletRequest request,
                     HttpServletResponse response)
       throws ServletException, IOException {
     PrintWriter out = response.getWriter();
     out.println("Hello World");
A Servlet That Generates HTML
 public class HelloWWW extends HttpServlet {
   public void doGet(HttpServletRequest request,
                      HttpServletResponse response)
       throws ServletException, IOException {
     PrintWriter out = response.getWriter();
     String docType =
       "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " +
     out.println(docType +
                 "<HTML>\n" +
                 "<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n"
                 "<BODY>\n" +
                 "<H1>Hello WWW</H1>\n" +
                The Servlet Life Cycle
   init
          Executed once when the servlet is first loaded.
           Not called for each request.
   service
          Called in a new thread by server for each request.
           Dispatches to doGet, doPost, etc.
           Do not override this method!
   doGet, doPost, doXxx
      Handles GET, POST, etc. requests.
      Override these to provide desired behavior.

   destroy
          Called when server deletes servlet instance.
           Not called after each request.
Handling the Client Request:
Form Data
     Form data
     Processing form data
     Reading request parameters
     Filtering HTML-specific characters
                The Role of Form Data
   Example URL at online travel agent
     http://host/path?user=Marty+Hall&origin=bwi&dest=lax
     Names come from HTML author;
      values usually come from end user
   Parsing form (query) data in traditional CGI
     Read the data one way (QUERY_STRING) for GET requests,
      another way (standard input) for POST requests
     Chop pairs at ampersands, then separate parameter names
      (left of the equal signs) from parameter values (right of the
      equal signs)
     URL decode values (e.g., "%7E" becomes "~")
     Need special cases for omitted values
      (param1=val1&param2=&param3=val3) and repeated
      parameters (param1=val1&param2=val2&param1=val3)
     Creating Form Data:
     HTML Forms
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HEAD><TITLE>A Sample Form Using GET</TITLE></HEAD>
<H2 ALIGN="CENTER">A Sample Form Using GET</H2>

<FORM ACTION="http://localhost:8088/SomeProgram">
  First name:
  <INPUT TYPE="TEXT" NAME="firstName" VALUE="Joe"><BR>
  Last name:
  <INPUT TYPE="TEXT" NAME="lastName" VALUE="Hacker"><P>
  <INPUT TYPE="SUBMIT"> <!-- Press this to submit form -->

   See CSAJSP Chapter 16 for details on forms
HTML Form: Initial Result
    Reading Form Data In Servlets
   request.getParameter("name")
     Returns URL-decoded value of first occurrence of name in
      query string
     Works identically for GET and POST requests
     Returns null if no such parameter is in query

   request.getParameterValues("name")
     Returns an array of the URL-decoded values of all
      occurrences of name in query string
     Returns a one-element array if param not repeated
     Returns null if no such parameter is in query

   request.getParameterNames()
       Returns Enumeration of request params
An HTML Form With Three
<FORM ACTION="/servlet/coreservlets.ThreeParams">
  First Parameter: <INPUT TYPE="TEXT" NAME="param1"><BR>
  Second Parameter: <INPUT TYPE="TEXT" NAME="param2"><BR>
  Third Parameter: <INPUT TYPE="TEXT" NAME="param3"><BR>
Reading the Three Parameters
public class ThreeParams extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    String title = "Reading Three Request Parameters";
    out.println(ServletUtilities.headWithTitle(title) +
                "<BODY BGCOLOR=\"#FDF5E6\">\n" +
                "<H1 ALIGN=CENTER>" + title + "</H1>\n"   +
                "<UL>\n" +
                " <LI><B>param1</B>: "
                + request.getParameter("param1") + "\n"   +
                " <LI><B>param2</B>: "
                + request.getParameter("param2") + "\n"   +
                " <LI><B>param3</B>: "
                + request.getParameter("param3") + "\n"   +
                "</UL>\n" +
                "</BODY></HTML>"); }}
Reading Three Parameters:
Filtering Strings for HTML-Specific
   You cannot safely insert arbitrary strings into servlet output
     < and > can cause problems anywhere
     & and " can cause problems inside of HTML attributes
   You sometimes cannot manually translate
     The string is derived from a program excerpt or another
      source where it is already in some standard format
     The string is derived from HTML form data
   Failing to filter special characters from form data makes you
    vulnerable to cross-site scripting attack
Java Collection Framework
           Including API, etc.
Java Collection Framework’s
      The Java Collection Framework helps
        Reduce  programming effort
        Reuse software
        Increase performance
        Make APIs easier to learn, design, and
        Increase interoperability between unrelated
Project Goals
   Small API
     Number  of interfaces
     Number of methods per interface
     Low "conceptual weight"

   Builds on existing Java collections
    (Vector, Hashtable)
   Interconvertible with Java arrays
    Java Collection Framework
   What is a collection (lower-case c!)?
     An   object that groups multiple elements into one unit
        Also   called a container (again, lower-case c!)
   Collection framework consists of
     Interfaces
        Abstract   data type
     Implementations
        Reusable    data structures
     Algorithms
        Reusable    functionality
    The Core Collection
    Framework Interfaces
   Collection
     Generic   Group of elements (the grand-daddy)
   Set
     No   duplicate elements (descendant of Collection)
   List
     Ordered   collection (descendant of Collection)
   Map
     Maps   keys to elements
   SortedSet, SortedMap
     Sorted   ordering of elements (Descended from above)
Core Collection Framework
Interface Hierarchy
Overview: Core Interfaces

       Collection
       Set
       List
       Map
       SortedSet
       SortedMap
Overview: Utilities (Interfaces and

       Utility Interfaces
         Comparator
         Comparable
         Iterator

       Utility Classes
         Collections
         Arrays
         They   provide many static methods
Collections Classes’ Useful
static Methods

     Collections class
       static   methods:
             – sort(List)
             – binarySearch(List, Object)
             – reverse(List)
             – shuffle(List)
             – fill(List, Object)
             – copy(List dest, List src)
             – min(Collection)
             – max(Collection)
             – synchronizedX, unmodifiableX factory methods
Arrays Classes’ Useful static

    Arrays helper class
      static   methods that act on Java arrays:
         sort()

         binarySearch()

         equals()

         fill()

         asList()    – returns an ArrayList composed of
         this array's contents
               Interface-Based Design
1.   interface List {…}
2.   class LinkedList implements List {…}
3.   List l = new LinkedList();
4.   l.add( new Date() );
5.   Date d = (Date)l.get(0);
        The Collection Interface
   Designed to group together any bunch of
    (homogenous) objects
     Its   major methods:
               – int size();
               – boolean isEmpty();
               – boolean contains(Object);
               – Iterator iterator();
               – Object[] toArray();
               – boolean add(Object);
               – boolean remove(Object);
               – void clear();
Collection Interface Implementations

   General implementations
       Primary public implementation
          Interface List – implemented as ArrayList, LinkedList
          Interface Set – implemented as TreeSet, HashSet Classes

          Interface Map – implemented as TreeMap, HashMap Classes

   Wrapper implementations
       Combined with other interfaces; e.g.,
            synchronized ArrayList or unmodifiable HashMap
Collection Interface Methods
    boolean add(Object o)
      Add   specified element
    boolean contains(Object o)
      True   if collection contains specified element
    boolean remove(Object o)
      Removes     specified element from collection
    boolean          equals(Object o)
      Compares     object with collection for equality
    Iterator iterator()
      Returns   an iterator over the elements in collection
Collection Interface Methods (2)
    boolean addAll(Collection c)
      Adds   all elements in specified collection
    boolean containsAll(Collection c)
      True   if collection contains all elements in collection
    boolean removeAll(Collection c)
      Removes     all elements in specified collection
    boolean           retainAll(Collection c)
      Retains only elements contained in specified
Collection Interface Methods (3)
    void clear()
        Removes all elements from collection
    boolean isEmpty()
        True if collection contains no elements
    int size()
        Returns number of elements in collection
    Object[] toArray()
        Returns array containing all elements in collection
    void shuffle(List list, Random rnd)
        Randomly permute list using rnd
    void sort(List list, Comparator c)
        Sorts list into ascending order
    sort() is done according to Comparator ordering of
                    Iterator Interface
   Iterator
     Common     interface for all Collection Framework
        Used   to examine all elements in collection
   Properties
     Order of elements is unspecified (may change)
     Can remove current element during iteration
     Works for any collection
Iterator Interface
   Interface
    public interface Iterator {
        boolean hasNext();
        Object next();
        void remove(); // optional, called once per next()
     Example   usage
       Iterator i = myCollection.iterator();
       while (i.hasNext()) {
              // HAVE to typecast generic Object
              // back to your specific object
              myCollectionElem x = (myCollectionElem);
                     Abstract Data Types
   Algorithms + Data Structures = Programs
   Standard and Well-understood
   Efficient
     Examples
        Stack,   queue, linked list
              Interface-based design
   Separate interface from implementation
   Built in to Java language
   Polymorphism
          • List l = new LinkedList();
     Calling l.add()   invokes method of class
   interface Set extends Collection interface
   An unordered collection of objects
   No duplicate elements
   Also inherits all the methods of the Collection
       Semantics are different, so different interface needed
        for design
   Implemented by classes:
       HashSet, TreeSet
Set Implementation
   HashSet
    a   Set backed by a hash table
   TreeSet
    A balanced binary tree
       Imposes   an ordering on its elements
   interface List extends
    Collection interface
   An ordered collection of objects
   Duplicates allowed
List Details
   Major additional methods:
          • Object get(int);
          • Object set(int, Object);
          • int indexOf(Object);
          • int lastIndexOf(Object);
          • void add(int, Object);
          • Object remove(int);
          • List subList(int, int);
          • add() inserts and remove() deletes
   Implemented by classes:
     ArrayList,    LinkedList, Vector
                      List Implementations
   ArrayList
    a   resizable-array implementation like Vector
        unsynchronized,     and without legacy methods
   LinkedList
    a doubly-linked list implementation
     May provide better performance than ArrayList
        if   elements frequently inserted/deleted within the List
     For     queues and double-ended queues (deques)
   Vector
    a synchronized resizable-array implementation of a
     List with additional "legacy" methods.
   interface Map (does not extend Collection
   An object that maps keys to values
   Each key can have at most one value
   Replaces java.util.Dictionary interface
   Ordering may be provided by implementation
    class, but not guaranteed
        Map Details
   Major methods:
          • int size();
          • boolean isEmpty();
          • boolean containsKey(Object);
          • boolean containsValue(Object);
          • Object get(Object);
          • Object put(Object, Object);
          • Object remove(Object);
          • void putAll(Map);
          • void clear();
   Implemented by classes:
     HashMap,Hashtable, WeakHashMap,
    Accessing all members of Map
   Methods
            • Set keySet();
            • Collection values();
            • Set entrySet();
   Map.Entry
     Object   that contains a key-value pair
        getKey(),    getValue()
   Thread safety
     The   Collections returned are backed by the map
        When    the map changes, the Collection changes
     Behavior    can easily become undefined
        Be   very careful and read the docs closely
                Map Implementations
   HashMap
    A  hash table implementation of Map
     Like Hashtable, but supports null keys & values

   TreeMap
    A  balanced binary tree implementation
     Imposes an ordering on its elements
   Hashtable
     Synchronized   hash table implementation of Map
     interface, with additional "legacy" methods.
   WeakHashMap
     Special-purpose  implementation of Map interface
      storing only weak references to its keys
     Allows key-value pairs to be garbage-collected
      when the key is no longer referenced outside of the
     Usefulfor implementing "registry-like" data
     structures, where the utility of an entry vanishes
     when its key is no longer reachable by any thread.
   Represents a loop
   Created by
   Similar to Enumeration
     Improved   method names
       Allows a remove() operation on
        the current item
Iterator Methods
   boolean hasNext()
     Returnstrue if the iteration has
     more elements
   Object next()
     Returns   next element in the iteration
   void remove()
     Removes  the current element from
     the underlying collection
   interface ListIterator extends
    Iterator interface
   Created by List.listIterator()
   Adds methods to
       traverse the List in either direction
            modify the List during iteration
   Methods added:
               • hasPrevious(), previous()
               • nextIndex(), previousIndex()
               • set(Object), add(Object)
   Collections.sort() static method of
    helper class
   SortedSet, SortedMap interfaces
     Collections that keep their elements
     Iterators are guaranteed to traverse in
      sorted order
   Ordered Collection Implementations
       TreeSet, TreeMap
                Sorting (cont.)
   Comparable interface
     Must be implemented by all elements in
     Must be implemented by all keys in SortedMap
     Method: int compareTo(Object o)
     Defines "natural order" for that object class
   Comparator interface
     Definesa function that compares two objects
     Can design custom ordering scheme
     Method: int compare(Object o1, Object o2)
Sorting (cont.)
   Total vs. Partial Ordering
     Technical, changes behavior per
      object class
   Sorting Arrays
     Use Arrays.sort(Object[])
     Equivalent   methods for all primitive
        Arrays.sort(int[]),      etc.
            Unsupported Operations
   An implementation class may elect not to
    support a particular method of the interface
   UnsupportedOperationException is a
    runtime (unchecked) exception
   Modifiable/Unmodifiable
       Modifiable: Collections that support modification operations,
        e.g., add(), remove(), clear()
       Unmodifiable: Collections that do not support any
        modification operations
   Mutable/Immutable
       Immutable: Collections that guarantee that no change in the
        Collection will ever be observable via "query" operations,
        e.g., such as iterator(), size(), contains()
       Mutable: Collections that are not immutable
              More Changes
   Fixed-size/Variable-size
     Liststhat guarantee that their size will remain
      constant even though the elements may
      change are referred to as fixed-size.
        Liststhat are not fixed-size are referred to as
Thread safety
   Collections, by default, are NOT
   Design decision for performance
    and "conceptual weight"
   Solutions:
     Encapsulated     Collections
     Synchronized Collections
     Unmodifiable Collections
     Fail-fast iterators
Thread safety

               In general, if the only access to a
                Collection is through a thread-safe
                object, then that Collection is safe
Thread safety

               Wrapper implementations that
                synchronize all relevant methods
               Factory methods inside the
                Collections class
               Example:
                      • List list =
Thread safety

               If an object can't be modified, it is
                thread-safe by definition
               Factory methods inside the
                Collections class
               Example:
                       • List list =
Thread safety

                Fail-fast Iterators
                If collection is modified during the
                 life of an iterator, then that iterator
                 fails immediately
                Rather than risking arbitrary, non-
                 deterministic behavior at an
                 undetermined time in the future
                Exception: the iterator's own add()
                 and remove() methods work fine
Other cool stuff
   Singleton Set
   nCopies
   Arrays.asList
   Other Collections Frameworks like
    Doug Lea, JGL, etc.
Introduction To Multithreading
   JavaTech: Introduction to Scientific and Technical
    Computing with Java
   How to think like a computer scientist
   Bruce Eckel, Thinking in Java
   Java Tutorial at
   Introduction to Programming Using Java
   Imagine Joe, Bob, Jane, Sandy, and Billy
    are all in a room
   They‟re all people and each of them can
    be classified as a person
   Thus, we might say that their type, or
    class, is Person
   Just like int x; tells us that x is a
    variable of type int, we can say that
    Joe is a variable of type Person
   An object is nothing more than a specific
    instance of a class
How do we build
   Start off with a UML diagram
   List the characteristics/attributes of
    members of that class
   List the behaviours of members of
    that class
Person class
   A Person can have arms, legs,
    eyes, hair, hair colour, etc.
   A Person can jump up and down,
    move forward, move backward,
    eat, and sleep
   A Person can speak with other
    people and ask them to move or
    eat or sleep, etc.
Constructing a person…
   UML immediately lets you setup
    the code: Person {

Fix/Expand previous
four slides

To top