You are on page 1of 118

Java Language

Abdulmalik S. Al-Gahmi October 4, 2001

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 Java environment and how it works. Write java programs. Create packages and document them Create classes and interfaces. Create and manage a hierarchy of classes and interfaces Create objects out of classes. Use Java I/O capabilities. Connect to a database using JDBC Use Java API

Course Organization

Part 1: OOP Model Part 2: Java Basics Part 3: Java implementation of OOP Model Part 4: Java OOP Design Issues Part 5: Introduction to Java API
Java I/O Java JDBC

Part 6: Advanced Java Features


Treads Exception Handling

Part 1

OOP Model

Introduction To OOP

Philosophy:
Abstraction Growth:
Machine Language Assembly Language Non-procedural Languages (BASIC) Procedural Languages (C, Pascal) OOP languages (C++, Java)

OOP model is to eliminate the mapping from the problem space to solution space as possible.

Objects

Objects can be described in terms of:


Their attributes Their behaviors

Objects attributes and behaviors are encapsulated together 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. 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 Interfaces
An object has to have an interface. The interface will

Provide a way to let other objects to communicate with it. Hide the details of the object implementation.

An example: Light bulb:


Light On() Off() Brighten() Dim()

OOP Big Goals (1)

Implementation Hiding
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.)

The goal of the class creator is to build a class that exposes only whats necessary to the client programmer and keeps everything else hidden. Two reasons for controlling the access:
To keep client programmers hands off portions they shouldnt touch. To allow the library designer to change the internal workings of the class without worrying about how it will affect the client programmer.

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 design. OOP provides ways for reuse:
Composition: Inheritance(Reusing the interface)

OOP differentiates between:


is-a Relationship ( Inheritance) has-a Relationship (Composition)

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:
Bird Move() Goose Move() Penguin Move()

Part 2

Java Basics

History of C++
First there was C. C initially became widely known as the development language of UNIX OS. C++ evolved as an extension to C. It mainly provides the capabilities of Object-Oriented Programming to C world. C++ is a hybrid language. Both C-like style and object-oriented style can be developed using it.

History of Java

Java first was developed in 1991 by James Gosling at Sun Microsystems to be used with interactive TV technology which had failed to find a market. When The World-Wide Web became popular in 1995 , Java came to life again. Java is now considered as the native language of the Internet. Java is a C/C++ based language. Java is a Full 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 language."

Java Environment
Draft .java file .class File Byte code on RAM Verified Byte code Editor Compiler Class Loader Byte code Verifier .java file .class File Byte code on RAM Verified Byte code

Interpreter

Executed machine code

Compiling/Running Java Programs

To compile your program, use command: c:\> javac MyProgramName.java

To run your program, use command: c:\> java MyProgramName

Program skeleton
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

//the skeleton of a java application package packagename; import packagename.ClassName; public class ProgramName { // Define program variables here. . . . // Define program methods here. . . . //Define the main method here.

Notes
Java

public static main(String args[])


{ // Main method body }//end of the main method.

is a case sensitive language Braces must occur on matching pairs Coding styles should be followed.

} //End of class HelloWorld

Comment Styles

Comments are used to clear the logic of the code and to increase the readability if it. 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 documentation.

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, \\, \.

Variables Definition

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 is an example of defining a variable: int number; String name;

Primitives Data types


Type boolean char byte short int long float double Size in bits 8 16 8 16 32 64 32 64 Values
true or false \u0000 - \uFFFF -128 - 127

-32,768 32,767
-2,147,483,648 - +2,147,483,647 -9,223,372,036,854,775,808 +9,223,372,036,854,775,807 -3.40292347E+38 - -+3.40292347E+38 -1.79769313486231570E+308 to +1.79769313486231570E+308

Arithmetic Operations
Operation
Addition

Operator

Java Expression

Subtraction
Multiplication

Division
Modulus

+ * / %

a + 8

b - 7
p * 10

c / 9
b % 6

Decision making operations


Operation
Equal to Not equal to Greater than Less than Greater than or equal Less than or equal

Operator

Java Expression
if (x == 1) if (y != 5) while (x > y) while (x < y) if (X >= y) if ( y <= z)

== != > < >= <=

Assignment Operators
Operator = += -= *= /= %= Expression c = 5; a += 10 ; a -= b; c *= 13; a /= b; b %= c ; Equivalent to c = 5 a = a + 10; a = a b; c = c * 13; a = a/b; b = b% c;

Increment /decrement operation


Operator expression
count++; ++count; --count; Count--;

Equivalent to
Count = count + 1; 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 operand If left operand of && is false, will not evaluate right operand

Precedence
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

Low

Java Key words


Keywords are words reserved for Java and cannot be used as identifiers or variable names
Ja va Keyw o rd s
abstract catch do final long private static throw void const boolean char double finally native super throws volatile goto break class else float new switch transient while byte continue extends for null return synchronized true case default false if interface package short this try

implements import

instanceof int

protected public

Keywords that are reserved but not used by Java

If if/else structures

if statement looks like: if (condition) { } Conditions are evaluated to either true or false

If/else statement looks like:

if (condition) { //do something. } else { //do something else. }

The switch Structure

switch statements
Useful to test a variable for different values switch ( value ){ case '1': actions case '2': actions default: actions } 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 ) statement

If multiple statements needed, enclose in braces Control variable only exists in body of for structure If loopContinuationTest is initially false, body not executed

Methods

Methods
Modularize a program All variables declared inside methods are local variables
Known only in method defined

Parameters
Communicate information between methods Local variables

Benefits
Divide and conquer
Manageable program development

Software reusability
Existing methods are building blocks for new programs Abstraction - hide internal details (library methods)

Avoids code repetition

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

Parameter-list: comma separated list, declares parameters.

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 same class square( 2 );

Dot operator - used with references to objects


g.drawLine( x1, y1, x2, y2 );

Dot operator - used with static methods of classes


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 Math.sqrt

Promotion rules
Specify how types can be converted without losing data 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

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 brace Local variables and parameters of methods
When nested blocks, need unique identifier names

If local variable has same name as instance variable


Instance variable "hidden"

Method scope
For labels (used with break and continue) Only visible in method 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 types Overloaded methods must have different parameters

Return type cannot distinguish method

Arrays

Array
Group of consecutive memory locations

Same name and type Static(Remain same size)

To refer to an element, specify

Array name Position number Format: arrayname[position number] First element at position 0

Every array knows its own length


c.length

Declaring/Allocating Arrays

Declaring arrays
Specify type, use new operator
Allocate number of elements Place brackets after name in declaration

Two steps:
int c[]; //declaration c = new int[ 12 ]; //allocation

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 Parameters

Passing arguments to methods


Call-by-value: pass copy of argument Call-by-reference: pass original argument
Improves performance, weakens security

In Java, you cannot choose how to pass arguments


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

Passing Arrays to Functions

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 } };

Java Applets

Java applets are programs that run on a java enabled browser. Java applets do not have main methods. To compile your program, use command: c:\> javac MyAppletName.java To run your program, use command: c:\> appletviewer my_html.html Applet Developint 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 make network connections except to the host that it came from. It cannot start any program on the host that's executing it. It cannot read certain system properties. Windows that an applet brings up look different than windows that an application brings up.

HTML Applet Tag


<HTML> < APPLET CODE = appletFile WIDTH = pixels HEIGHT = pixels > </APPLET> </HTML>

Part 3

Java Implementation of The OOP Model

Introduction

Java is a full object-oriented programming language. Java supports:


Classes Abstract Classes Inner 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. The class is the unit of Java programming.

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 directory If class in same package as another, import not required
Create a directory called classes inside directory c:\jdk1.2\jre\ Use the following command for compilation:
javac d c:\jdk1.2\jre\classes MyClasse.java

Follow these steps to create a package:

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)

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.

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 void.

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 rewriting 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.

Managing Inheritance (1)

Inheritance is a form of software reusability where


New classes created from existing ones Subclasses absorb super-classes attributes and behaviors, and add in their own.

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 protected. 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 superclass.

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 inheritance. To inherit from a class use keyword extends
class TwoDimensionalShape extends Shape { ... }

Inheritance does also apply to Java interfaces.

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 methods:
clone - equals/hashCode - finalize toString

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 collected. 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.

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 Class Members (2)

Protected:
Allows the class itself, subclasses, and all classes in the same package to access the members. 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 secrets. 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 public.

Controlling Access to Class Members (4)

Package
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 friends.

To summarize:

Specifier class subclass package world


private protected public package
X X X X

X X

X X 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:


Color.red, 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

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 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 System.exit(); 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 initialization. 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

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 re-use 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 methods 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 instantiated. 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.

Inner Classes

Inner classes are classes defined inside other classes. 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.

Java Interfaces (1)


An interface defines a protocol of behavior that can be implemented by any class anywhere in the class hierarchy. 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 commaseparated 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){} }

Part 4

Java OOP Design Issues

Java Programming Styles


(1)

Packages:
Package names are entirely in lower case. Package name should start with the web domain name reversed Examples:
package com.sun.java.lang; package edu.nmsu.is.us.sp;

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 RecordList.java

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 questions. 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 documentation. The result of the javadoc utility is HTML documentation that is the same as the Java standard API documentation in format.

PART 5

Java Essential API

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 APIs:
java.lang java.util java.security java.rmi java.io java.net java.beans java.sql

Java also has a huge collection of windowing classes called JFC(Java Foundation Classes) which include:
Swing collection Drag and drop collection Accessibility collection - AWT collection - look and feel 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 (either characters or bytes) on which they operate. Generally, the algorithms for sequentially reading and writing data are basically the same: Reading Writing

open a stream while more information read information close the stream

open a stream while more information write information 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. Following the standard I/O model, Java has System.in, 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. System.in must be wrapped as before you can read from it.

Standard I/o-Example
import java.io.*; public class StdInRead { public static void main(String[] args) throws IOException { System.err.print( "Enter Your input. Empty line to exit.\n"); BufferedReader in = new BufferedReader( new InputStreamReader(System.in)); 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 directories. It is an abstract representation of file and directory pathnames. 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 File An Example


import java.io.*; 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++) System.out.println(f[i]); } }

Reading / writing Files


import java.io.*; 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 FileWriter(outputFile); int c; while ((c = in.read()) != -1) out.write(c); in.close(); out.close(); }

Concatenating Files
import java.io.*; 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 = s.read()) != -1) System.out.write(c); s.close(); }

Object Serialization

Javas 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; Javas (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 OutputStream. To reverse the process, you wrap an InputStream inside an ObjectInputStream and call readObject( ).

Object Serialization
import java.io.*; 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()); } }

JDBC
(Introduction)

A great promise of Java has been the ability to build platformindependent client/server database applications. This has come to fruition with Java DataBase Connectivity (JDBC). JDBC is designed to be platform-independent, so you dont need to worry about the database youre using while youre programming JDBC, like many of the APIs in Java, is designed for simplicity. The method calls you make correspond to the logical operations youd 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 youre 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 located. 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:
try{ Class.forName("sun.jdbc.odbc.JdbcOd bcDriver"); } catch(SQLException exp){ System.err.println("Failed to connect"); }

If the statement above does not catch any exceptions it means that the driver is loading properly.

Getting JDBC To Work (2)

STEP 2: Configure the database


From Control Panel create a DSN for your data base 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:
try{ 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 properly.

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.next()) { System.out.println( r.getString(FIELD 1") + ", " + r.getString(FIELD 2) + . . .); }

Close the statement and result ser objects using:


s.close();

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 CREATE TABLE UPDATE ALTER INSERT

To update a database in JDBC we use method executeUpdate() instead of executeQuery() method in the statement

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 executeBatch().

Part 6

Advanced Java Features

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.

Introduction To Multithreading Programs

References
Detiel and Detiel, Java 2: How to program Bruce Eckel, Thanking in Java Java Tutorial at

http://java.sun.com/docs/books/tutorial/index.html

Cay S. Horstmann, Core Java 2 Vol. I

You might also like