You are on page 1of 268

Object Oriented Programming

Design Principles
Objects
It is defined as something that has state, behavior and identity. We model objects according to the real-world problem that our program is supposed to solve. Each object has characteristics that describe both what it contains and what is does. Student object must be capable of performing basic operation such as Accept-Information, Process-Marks, etc. First identify objects that make up our system. Determine each objects purpose.
Prasad S.Halgaonkar 2

Classes
It describes the characteristics shared by all objects of the same type. We can define a class car that describes all the characteristics of car. These properties are used by car object. Class contains the following:
Descriptions of the actions an object can perform Definition of the structure of object

Prasad S.Halgaonkar

Message
It is a request transferred from one object to another so that the receiving object produces some desired result. Three categories:
Unary msg has no parameter. Has 2 parts: the object to which they are to be sent and the name of the method in that receiving object. Binary msg have 1 parameter, an object, which is passed to the specified method of the specified receiver object. E.g. 5 * 4 (5 is receiving object, to which is sent the msg {* 4}) Keyword msg specifies keywords to organize the correspondence between the actual parameters in the msg and the formal parameters in the method.
Prasad S.Halgaonkar 4

Methods
It consist of the operations that an object performs when it receives a message. There is one-to-one correspondence between msgs and the methods is carried out when a given msg is received by an object of a particular class.

Prasad S.Halgaonkar

Implementation of OOP
Three OOP Principles
Encapsulation
It is a mechanism that binds code & data it manipulates and keep both safe from outside world. In Java, basic encapsulation is class. Class defines the structure and behavior (data and code) that will be shared by set of objects. Objects are instance of class.

Prasad S.Halgaonkar

Inheritance
It is a process by which one object acquires the properties of another object. An object need only define those qualities that make it unique in the class. It can inherit its general attributes from its parent.

Polymorphism
Greek = many forms. It allows one interface to be used for a general class of actions. Its called as one interface, multiple methods i.e. it is possible to design a generic interface to a group of related activities. Reduces complexity.
Prasad S.Halgaonkar 7

OOP with Java


Program Structure
class Example { public static void main(String arg [ ]) { System.out.println(This is TE Comp); } }

Prasad S.Halgaonkar

1. Enter the program


The name given to source file is very important. In Java, source file is called as compilation unit. It is text file that contains one or more class definitions. Java compiler requires that source file use the java filename extension.

2. Compile the program



C:\> javac Example.java Compiler creates a file called Examples.class that contains the byte code version of the program, Use Java Interpreter to run the program
C:\> java Example

Output will be:This is TE Comp


Prasad S.Halgaonkar 9

Class Declaration
It defines a new data type. Once defined, this new type can be used to create objects of that type. Class definition is as follows:
class classname { type instance-virables1;.. Type instance-variablesN; type methodname1(parameter-list){//body method} .type methodnameN(parameter-list){//body method} }
Prasad S.Halgaonkar 10

Data or variables defined within a class are called instance variables coz each object of a class contains its own copy of these variables. The data of one object is separate and unique from the data for another. The code is contained within methods. Collectively, methods & variables defined within the class is called members of the class.

Prasad S.Halgaonkar

11

Object Declaration
Obtaining objects of a class is a two-step procedure
Declare variable of the class type1, it is a variable that can refer to an object. Acquire an actual, physical copy of the object and assign it to that variable, do this by using the new operator.
Box mybox; // declare reference to object mybox = new Box(); // allocate a Box object
Prasad S.Halgaonkar 12

Packages
Package allows u to create a class named list, which u can store in your own package. No concern whether it will collide with some other class named list. Packages are stored in hierarchical manner & are explicitly imported. U can define classes inside a package that is not accessible to code outside the package.
Prasad S.Halgaonkar 13

To create package include a package command as the first statement in source file. The package statement defines a name space in which classes are stored. If u omit package statement, then class names are put into the default package, which has no name. package Mypackage; Java uses file system directories to store packages.
Prasad S.Halgaonkar 14

Case is significant. Directory name should match the package name exactly. Java includes the import statement to bring certain classes, or entire packages, into visibility. import pkg1[pkg2].(classname/*) When package is imported, only those items declared as public will be available to nonsubclasses in the imported code.
Prasad S.Halgaonkar 15

Interface
before writing a class definition, determine the interface
the set of services we offer to clients

similarly, if defining data structures, we should first determine the interface


stacks support a constructor, push, pop, size, isEmpty, and top queues offer a constructor, enqueue, dequeue, size, isEmpty and front

data structures people refer to the interface as the


abstract data type
16 Prasad S.Halgaonkar

Data Abstraction
if the interface remains the same, clients don't need to be changed, even if the implementation behind the interface changes
public class Time { private int timeInSecs;
//public methods } //same public methods //but with different //bodies }
17 Prasad S.Halgaonkar

public class Time { private int hours; private int minutes private int secs;

Java Interfaces
Java allows us to take this one stage further, by formally recording the interface as a Java interface a java interface is just a collection of abstract methods (i.e. we state the signatures, but not the bodies)
states that this is an interface, not a class note no bodies for the methods

public interface MyStack { public int size(); public boolean isEmpty(); public Object top(); public void push(Object elt); public Object pop(); }
Prasad S.Halgaonkar

18

interfaces vs classes
a class definition can contain instance/class variables and instance/class methods, including both the signature and the body a java interface contains only the signatures of public instance methods (and named constants) a java interface acts like a specification
it says what it means to be e.g. a stack to be a stack, an object must offer at least those methods in its public interface
19 Prasad S.Halgaonkar

using Java interfaces


Java allows us to tell the compiler that a class will implement an interface regard it as a contract stating that you will meet the specification

any class that implements an interface must provide implementations of the public methods (or it must be abstract, and its subclasses provide them) the compiler will check, and if the bodies are not provided, it won't compile
20 Prasad S.Halgaonkar

Example
import java.util.ArrayList;

public class ALStack<E> implements MyStack { private ArrayList<E> al;


promises that we public ALStack() { al = new ArrayList<E>(); will provide bodies for all the MyStack methods }

public int size() { return al.size(); } //and versions of isEmpty, push, pop and top, as //in the previous lecture }
21 Prasad S.Halgaonkar

Example (cont)
public class ArrayStack implements MyStack { private int capacity; private Object[] s; private int top = -1; public ArrayStack(int reqdCapacity) { capacity = reqdCapacity; s = new Object[capacity]; } public int size() { return top+1; } //and versions of isEmpty, push, pop and top ... }
22 Prasad S.Halgaonkar

More Polymorphism
Polymorphism:
a variable of a superclass type may refer to objects of that class or of its subclasses a variable of Java interface type may refer to objects of any class that implements the interface
MyStack s; s = new ArrayStack(20); s = new ALStack<Book>();

Dynamic method binding: decide at run-time which method to run, based on the referenced object
s.push(new Book());

23

Prasad S.Halgaonkar

What's the point?


using Java interfaces polymorphically gives you client code that is much easier to modify how much effort would be involved to change from an ArrayStack to an ALStack if we hadn't used an interface? In program design and development, you will probably frequently change the data structures a program uses, so interfaces gives a significant improvement in maintainability
24 Prasad S.Halgaonkar

Example: client not using interface


public void method1() { ArrayStack s = new ArrayStack(10); s.push(new Cow()); method2(s); method3(s); }

public void method2(ArrayStack st) { System.out.println(st.top()); }


public void method3(ArrayStack st) { st.push(new Pig()); }
25 Prasad S.Halgaonkar

Example: client using interface


public void method1() { MyStack s = new ArrayStack(10); s.push(new Cow()); method2(s); method3(s); }

only 1 thing to change

public void method2(MyStack st) { System.out.println(st.top()); }


public void method3(MyStack st) { st.push(new Pig()); }
26 Prasad S.Halgaonkar

Summary (Interface)
An interface is like an abstract class - it specifies what its methods should look like, but gives no body if a class implements an interface, it is equivalent to signing a contract saying that it will provide a body for the specified method - Java will not compile the program unless we provide the method definition we can refer to an object as though it were an object of the interface, and invoke the interface methods
27 Prasad S.Halgaonkar

Exception Handling in Java

Introduction
Users have high expectations for the code we produce. Users will use our programs in unexpected ways. Due to design errors or coding errors, our programs may fail in unexpected ways during execution

Prasad S.Halgaonkar

29

Introduction
It is our responsibility to produce quality code that does not fail unexpectedly. Consequently, we must design error handling into our programs.

Prasad S.Halgaonkar

30

Errors and Error Handling


An Error is any unexpected result obtained from a program during execution. Unhandled errors may manifest themselves as incorrect results or behavior, or as abnormal program termination. Errors should be handled by the programmer, to prevent them from reaching the user.

Prasad S.Halgaonkar

31

Errors and Error Handling


Some typical causes of errors:
Memory errors (i.e. memory incorrectly allocated, memory leaks, null pointer) File system errors (i.e. disk is full, disk has been removed) Network errors (i.e. network is down, URL does not exist) Calculation errors (i.e. divide by 0)

Prasad S.Halgaonkar

32

Errors and Error Handling


More typical causes of errors:
Array errors (i.e. accessing element 1) Conversion errors (i.e. convert q to a number)

Prasad S.Halgaonkar

33

Errors and Error Handling


Traditional Error Handling
1. Every method returns a value (flag) indicating either success, failure, or some error condition. The calling method checks the return flag and takes appropriate action. Downside: programmer must remember to always check the return value and take appropriate action. This requires much code (methods are harder to read) and something may get overlooked.

Prasad S.Halgaonkar

34

Errors and Error Handling


Traditional Error Handling
Where used: traditional programming languages (i.e. C) use this method for almost all library functions (i.e. fopen() returns a valid file or else null)

Prasad S.Halgaonkar

35

Errors and Error Handling


Traditional Error Handling
2. Create a global error handling routine, and use some form of jump instruction to call this routine when an error occurs. Downside: jump instruction (GoTo) are considered bad programming practice and are discouraged. Once you jump to the error routine, you cannot return to the point of origin and so must (probably) exit the program.

Prasad S.Halgaonkar

36

Errors and Error Handling


Traditional Error Handling
Where used: many older programming texts (C, FORTRAN) recommended this method to programmers. Those who use this method will frequently adapt it to new languages (C++, Java).

Prasad S.Halgaonkar

37

Errors and Error Handling


Exceptions a better error handling
Exceptions are a mechanism that provides the best of both worlds. Exceptions act similar to method return flags in that any method may raise and exception should it encounter an error. Exceptions act like global error methods in that the exception mechanism is built into Java; exceptions are handled at many levels in a program, locally and/or globally.

Prasad S.Halgaonkar

38

Exceptions
What are they?
An exception is a representation of an error condition or a situation that is not the expected result of a method. Exceptions are built into the Java language and are available to all program code. Exceptions isolate the code that deals with the error condition from regular program logic.

Prasad S.Halgaonkar

39

Exceptions
How are they used?
Exceptions fall into two categories:
Checked Exceptions Unchecked Exceptions

Checked exceptions are inherited from the core Java class Exception. They represent exceptions that are frequently considered non fatal to program execution Checked exceptions must be handled in your code, or passed to parent classes for handling.

Prasad S.Halgaonkar

40

Exceptions
How are they used?
Unchecked exceptions represent error conditions that are considered fatal to program execution. You do not have to do anything with an unchecked exception. Your program will terminate with an appropriate error message.

Prasad S.Halgaonkar

41

Exceptions
Examples:
Checked exceptions include errors such as array index out of bounds, file not found and number format conversion. Unchecked exceptions include errors such as null pointer.

Prasad S.Halgaonkar

42

Exceptions
How do you handle exceptions?
Exception handling is accomplished through the try catch mechanism, or by a throws clause in the method declaration. For any code that throws a checked exception, you can decide to handle the exception yourself, or pass the exception up the chain (to a parent class).

Prasad S.Halgaonkar

43

Exceptions
How do you handle exceptions?
To handle the exception, you write a try-catch block. To pass the exception up the chain, you declare a throws clause in your method or class declaration. If the method contains code that may cause a checked exception, you MUST handle the exception OR pass the exception to the parent class (remember, every class has Object as the ultimate parent)

Prasad S.Halgaonkar

44

Coding Exceptions
Try-Catch Mechanism
Wherever your code may trigger an exception, the normal code logic is placed inside a block of code starting with the try keyword: After the try block, the code to handle the exception should it arise is placed in a block of code starting with the catch keyword.

Prasad S.Halgaonkar

45

Coding Exceptions
Try-Catch Mechanism
You may also write an optional finally block. This block contains code that is ALWAYS executed, either after the try block code, or after the catch block code. Finally blocks can be used for operations that must happen no matter what (i.e. cleanup operations such as closing a file)

Prasad S.Halgaonkar

46

Coding Exceptions
Example
try { normal program code } catch(Exception e) { exception handling code }

Prasad S.Halgaonkar

47

Coding Exceptions
Passing the exception
In any method that might throw an exception, you may declare the method as throws that exception, and thus avoid handling the exception yourself Example
public void myMethod throws IOException { normal code with some I/O }

Prasad S.Halgaonkar

48

Coding Exceptions
Types of Exceptions
All checked exceptions have class Exception as the parent class. You can use the actual exception class or the parent class when referring to an exception

Prasad S.Halgaonkar

49

Coding Exceptions
Types of Exceptions
Examples:
public void myMethod throws Exception { public void myMethod throws IOException { try { } catch (Exception e) { } try { } catch (IOException ioe) { }

Prasad S.Halgaonkar

50

Code Examples
1. Demonstration of an unchecked exception (NullPointerException) 2. Demonstration of checked exceptions:
Passing a DivideByZeroException Handling a DivideByZeroException

Prasad S.Halgaonkar

51

Summary (Exception handling)


Exceptions are a powerful error handling mechanism. Exceptions in Java are built into the language. Exceptions can be handled by the programmer (try-catch), or handled by the Java environment (throws).

Prasad S.Halgaonkar

52

Simple Java I/O


General Principles

Streams
All modern I/O is stream-based A stream is a connection to a source of data or to a destination for data (sometimes both) An input stream may be associated with the keyboard An input stream or an output stream may be associated with a file Different streams have different characteristics:
A file has a definite length, and therefore an end Keyboard input has no specific end
Prasad S.Halgaonkar 54

How to do I/O
import java.io.*; Open the stream Use the stream (read, write, or both) Close the stream

Prasad S.Halgaonkar

55

open use close

Why Java I/O is hard

Java I/O is very powerful, with an overwhelming number of options Any given kind of I/O is not particularly difficult The trick is to find your way through the maze of possibilities

Prasad S.Halgaonkar

56

open use close

Opening a stream

There is data external to your program that you want to get, or you want to put data somewhere outside your program When you open a stream, you are making a connection to that external place Once the connection is made, you forget about the external place and just use the stream
Prasad S.Halgaonkar 57

open use close

Example of opening a stream


FileReader fileReader = new FileReader(fileName);

A FileReader is used to connect to a file that will be used for input:

The fileName specifies where the (external) file is to be found You never use fileName again; instead, you use fileReader
Prasad S.Halgaonkar 58

open use close

Using a stream

Some streams can be used only for input, others only for output, others for both Using a stream means doing input from it or output to it But its not usually that simple--you need to manipulate the data in some way as it comes in or goes out

Prasad S.Halgaonkar

59

open use close

Example of using a stream

int ch; ch = fileReader.read( ); The fileReader.read() method reads one character and returns it as an integer, or -1 if there are no more characters to read The meaning of the integer depends on the file encoding (ASCII, Unicode, other)
Prasad S.Halgaonkar 60

open use close

Manipulating the input data

Reading characters as integers isnt usually what you want to do A BufferedReader will convert integers to characters; it can also read whole lines The constructor for BufferedReader takes a FileReader parameter:
BufferedReader bufferedReader = new BufferedReader(fileReader);
Prasad S.Halgaonkar 61

open use close

Reading lines

String s; s = bufferedReader.readLine( ); A BufferedReader will return null if there is nothing more to read

Prasad S.Halgaonkar

62

open use close

Closing

A stream is an expensive resource There is a limit on the number of streams that you can have open at one time You should not have more than one stream open on the same file You must close a stream before you can open it again Always close your streams!
Prasad S.Halgaonkar 63

Simple Java I/O


LineReader and LineWriter

Text files
Text (.txt) files are the simplest kind of files
text files can be used by many different programs

Formatted text files (such as .doc files) also contain binary formatting information Only programs that know the secret code can make sense formatted text files Compilers, in general, work only with text
Prasad S.Halgaonkar 65

My LineReader class
class LineReader { BufferedReader bufferedReader;
LineReader(String fileName) {...} String readLine( ) {...}

void close( ) {...}


}
Prasad S.Halgaonkar 66

Basics of the LineReader constructor


Create a FileReader for the named file:
FileReader fileReader = new FileReader(fileName);

Use it as input to a BufferedReader:


BufferedReader bufferedReader = new BufferedReader(fileReader);

Use the BufferedReader; but first, we need to catch possible Exceptions


Prasad S.Halgaonkar 67

The full LineReader constructor


LineReader(String fileName) { FileReader fileReader = null; try { fileReader = new FileReader(fileName); } catch (FileNotFoundException e) { System.err.println ("LineReader can't find input file: " + fileName); e.printStackTrace( ); } bufferedReader = new BufferedReader(fileReader); } Prasad S.Halgaonkar

68

readLine
String readLine( ) { try { return bufferedReader.readLine( ); } catch(IOException e) { e.printStackTrace( ); } return null; }
Prasad S.Halgaonkar 69

close
void close() { try { bufferedReader.close( ); } catch(IOException e) { } }

Prasad S.Halgaonkar

70

How did I figure that out?


I wanted to read lines from a file I found a readLine method in the BufferedReader class The constructor for BufferedReader takes a Reader as an argument An InputStreamReader is a kind of Reader A FileReader is a kind of InputStreamReader
Prasad S.Halgaonkar 71

The LineWriter class


class LineWriter { PrintWriter printWriter;

LineWriter(String fileName) {...}


void writeLine(String line) {...}

void close( ) {...}


}
Prasad S.Halgaonkar 72

The constructor for LineWriter


LineWriter(String fileName) { try { printWriter = new PrintWriter( new FileOutputStream(fileName), true); } catch(Exception e) { System.err.println("LineWriter can't " + "use output file: " + fileName); } } Prasad S.Halgaonkar

73

Flushing the buffer


When you put information into a buffered output stream, it goes into a buffer The buffer may not be written out right away If your program crashes, you may not know how far it got before it crashed Flushing the buffer is forcing the information to be written out
Prasad S.Halgaonkar 74

PrintWriter
Buffers are automatically flushed when the program ends normally Usually it is your responsibility to flush buffers if the program does not end normally PrintWriter can do the flushing for you
public PrintWriter(OutputStream out, boolean autoFlush)

Prasad S.Halgaonkar

75

writeLine
void writeLine(String line) { printWriter.println(line); }

Prasad S.Halgaonkar

76

close
void close( ) { printWriter.flush( ); try { printWriter.close( ); } catch(Exception e) { } }

Prasad S.Halgaonkar

77

Java Systems

Basics of a Typical Java Environment

Consist of environment, language, Java Applications Programming Interface (API), Class libraries

Java programs have five phases


Edit
Use an editor to type Java program vi or emacs, notepad, Jbuilder, Visual J++ .java extension

Compile
Translates program into bytecodes, understood by Java interpreter javac command: javac myProgram.java Creates .class file, containing bytecodes (myProgram.class)
Prasad S.Halgaonkar 78

Basics of a Typical Java Environment (II)

Java programs have five phases (continued)


Loading
Class loader transfers .class file into memory
Applications - run on user's machine Applets - loaded into Web browser, temporary

Classes loaded and executed by interpreter with java command java Welcome HTML documents can refer to Java Applets, which are loaded into web browsers. To load, appletviewer Welcome.html
appletviewer is a minimal browser, can only interpret applets
Prasad S.Halgaonkar 79

Basics of a Typical Java Environment (II)

Java programs have five phases (continued)


Verify
Bytecode verifier makes sure bytecodes are valid and do not violate security Java must be secure - Java programs transferred over networks, possible to damage files (viruses)

Execute
Computer (controlled by CPU) interprets program one bytecode at a time Performs actions specified in program

Program may not work on first try


Make changes in edit phase and repeat

Prasad S.Halgaonkar

80

Phase 1

Editor

Disk

Program is created in the editor and stored on disk. Compiler creates bytecodes and stores them on disk.

Phase 2

Compiler

Disk Primary Memory

Phase 3

Class Loader Class loader puts bytecodes in memory. . . . . . . Primary Memory Bytecode verifier confirms that all bytecodes are valid and do not violate Javas security restrictions.

Disk

Phase 4

Bytecode Verifier

Phase 5

Interpreter

. . . . . . Primary Memory

Prasad S.Halgaonkar

. . . . . .

Interpreter reads bytecodes and translates them into a language that the computer can understand, possibly storing data values as the program executes. 81

General Notes about Java and This Book

Java
Powerful language Programming
Clarity - Keep it Simple Portability - Java portable, but it is an elusive goal

Performance
Interpreted programs run slower than compiled ones
Compiling has delayed execution, interpreting executes immediately

Can compile Java programs into machine code


Runs faster, comparable to C / C++

Prasad S.Halgaonkar

82

General Notes about Java and This Book (II)

Just-in-time compiler
Midway between compiling and interpreting
As interpreter runs, compiles code and executes it Not as efficient as full compilers
Being developed for Java

Integrated Development Environment (IDE)


Tools to support software development Several Java IDE's are as powerful as C / C++ IDE's

Prasad S.Halgaonkar

83

A Simple Program: Printing a Line of Text

Application
Program that runs using Java interpreter (discussed later) 1 // Fig. 24.2: Welcome1.java
2 // A first program in Java 3 4 public class Welcome1 { 5 public static void main( String args[] ) 6 { 7 System.out.println( "Welcome to Java 8 } Programming!" ); 9 }

Comments
Java uses C-style // (preferred by Java programmers) Prasad Can also use /* ... S.Halgaonkar */
84

A Simple Program: Printing a Line of Text (II)


public class Welcome1 {

Begins class definition Every Java program has a user-defined class Use keyword (reserved word) class followed by ClassName
Name format - MyClassName Identifier - letters, digits, underscores, dollar signs, does not begin with a digit, contains no spaces Java case sensitive

When saving a file, class name must be part of file name


Save file as Welcome1.java

Prasad S.Halgaonkar

85

A Simple Program: Printing a Line of Text (III)

Braces
Body - delineated by left and right braces
Class definitions public static void main( String args[] )
Part of every Java application
Program begins executing at main Must be defined in every Java application

main is a method (a function) void means method returns nothing


Many methods can return information

Braces used for method body For now, mimic main's first line
Prasad S.Halgaonkar 86

A Simple Program: Printing a Line of Text (IV)


System.out.println( "Welcome to Java Programming!" );

Prints string
String - called character string, message string, string literal Characters between quotes a generic string

System.out - standard output object


Displays information in command window

Method System.out.println
Prints a line of text in command window When finished, positions cursor on next line

Method System.out.print
As above, except cursor stays on line \n - newline

Statements must end with ;


Prasad S.Halgaonkar 87

A Simple Program: Printing a Line of Text (V)

Executing the program


javac Welcome1
Creates Welcome1.class (containing bytecodes)

java Welcome1
Interprets bytecodes in Welcome1.class (.class left out in java command) Automatically calls main

Output types
Command window Dialog box / Windows
Prasad S.Halgaonkar 88

A Simple Program: Printing a Line of Text (VI)

Packages
Predefined, related classes grouped by directories on disk
All in directory java or javax, or subdirectories

Referred to collectively as the Java class library or the Java applications programming interface (Java API) import - locates classes needed to compile program

Class JOptionPane
Defined in package called javax.swing
Contains classes used for a graphical user interface (GUI)
Facilitates data entry and data output

import javax.swing.JOptionPane;
Prasad S.Halgaonkar 89

A Simple Program: Printing a Line of Text (VII)


Class JOptionPane

Contains methods that display a dialog box


static method showMessageDialog First argument - null (more Chapter 29) Second argument - string to display

static methods

Called using dot operator (.) then method name

exit - method of class System

JOptionPane.showMessageDialog(arguments); Terminates application, required in programs with GUIs System.exit( 0 ); 0 - normal exit non-zero - signals that error occurred Automatically imported in every Java program

Class System in package java.lang

Prasad S.Halgaonkar

90

1 // Fig. 24.4: Welcome2.java 2 // Printing multiple lines in a dialog box 3 import javax.swing.JOptionPane; // import class JOptionPane 4 5 public class Welcome2 { 6 public static void main( String args[] ) 7 { 8 JOptionPane.showMessageDialog( 9 null, "Welcome\nto\nJava\nProgramming!" ); 10 11 System.exit( 0 ); // terminate the program 12 } 13}

Outline
1. import statement 2. Define class

3. main
4. JOptionPane.showMe ssageDialog 5. System.exit Program Output

2000 Prentice

Hall, Inc. All rights

Another Java Application: Adding Integers


Variables
Locations in memory that hold data Must be declared with name and data type before use
Primitive data types (keywords): boolean, char, byte, short, int, long, float, double (details in Chapter 25) String (java.lang) - hold strings: "Hi" "37" int - holds integers: -1, 0, 15

Name format - first letter lowercase, new word capitalized


myVariable, myOtherVariable

Declarations: specify name and type


Can have multiple variables per declaration int myInt, myInt2, myInt3; String myString, myString2;
Prasad S.Halgaonkar 92

Another Java Application: Adding Integers (II)

Method showInputDialog
Of class JOptionPane Displays prompt (gets user input)
Argument - Text to display in prompt

Java does not have a simple form of input


Nothing analogous to System.out.print

Returns what user input


Assign input to a variable using assignment operator =
myString = JOptionPane.showInputDialog( "Enter an integer" );

= has two operands (binary operator)


Expression on right evaluated, assigned to variable on left

Prasad S.Halgaonkar

93

Another Java Application: Adding Integers (III)


Integer.parseInt
static method of class Integer Input from showInputDialog a String

The + operator

Want to convert it into an integer parseInt takes a String, returns an integer myInt = Integer.parseInt( myString ); Note assignment operator

String concatenation - "adding" strings


"Hello" + " there " same as "Hello there"

Print variables

Used for addition, as in C / C ++:


sum = int1 + int2;

"myInt has a value of: " + myInt

Prasad S.Halgaonkar

94

Another Java Application: Adding Integers (III)

showOptionDialog
Another version First argument: null Second: message to display Third: string to display in title bar Fourth: type of message to display
JOptionPane.PLAIN_MESSAGE

Prasad S.Halgaonkar

95

1 2 3

// Fig. 24.6: Addition.java // An addition program

Outline
1. import 2. main

4 import javax.swing.JOptionPane; // import class JOptionPane 5 6 public class Addition { 7 public static void main( String args[] ) 8 { 9 String firstNumber, // first string entered by user 10 secondNumber; // second string entered by user 11 12 13 14 15 16 17 18 19 20 21 22 23 int number1, number2, sum; // first number to add // second number to add // sum of number1 and number2

2.1 Declare variables


2.2 showInputDialog 2.3 Assign input to firstNumber 2.4 Repeat for secondNumber 2.5 Convert Strings to ints 2.6 Sum the numbers

// read in first number from user as a string firstNumber = JOptionPane.showInputDialog( "Enter first integer" ); // read in second number from user as a string secondNumber = JOptionPane.showInputDialog( "Enter second integer" ); // convert numbers from type String to type int

24 25 26 27 28 29 30

number1 = Integer.parseInt( firstNumber ); number2 = Integer.parseInt( secondNumber );


// add the numbers sum = number1 + number2; // display the results 2000 Prentice Hall, Inc. All rights

31 32 33 34 35 36 37 } }

JOptionPane.showMessageDialog( null, "The sum is " + sum, "Results", JOptionPane.PLAIN_MESSAGE );

Outline

System.exit( 0 );

// terminate the program

2.7 Use showMessageDialog to display results

Program Output

2000 Prentice

Hall, Inc. All rights

Sample Applets from the Java 2 Software Development Kit

Applet
Program that runs in
appletviewer (test utility for applets) Web browser (IE, Communicator)

Executes when HTML document containing applet is opened

Sample Applets
Provided in Java 2 Software Development Kit (J2SDK) Source code included (.java files) Located in demo directory of J2SDK install
Prasad S.Halgaonkar 98

Sample Applets from the Java 2 Software Development Kit

Running applets
In command prompt, change to subdirectory of applet cd directoryName There will be an HTML file used to execute applet type appletviewer example1.html Applet will run, Reload and Quit commands under Applet menu

Example applets
Tic-Tac-Toe Drawing programs Animations
Prasad S.Halgaonkar 99

A Simple Java Applet: Drawing a String


Create our own applet
Print "Welcome to Java Programming!" import javax.swing.JApplet
Needed for all applets

import java.awt.Graphics
Allows program to draw graphics (lines, ovals, text) on an applet

Like applications, applets have at least one class definition

Rarely create applets from scratch


Use pieces of class existing definitions
public class WelcomeApplet extends JApplet { extends ClassName - class to inherit from
In this case, inherit from class JApplet

Prasad S.Halgaonkar

100

A Simple Java Applet: Drawing a String (II)

Inheritance
JApplet is superclass (base class) WelcomeApplet is subclass (derived class) Derived class inherits data and methods of base class
Can add new features to derived class

Benefits
Someone else has already defined what an applet is
Applets require over 200 methods to be defined! By using inheritance, all those methods are now ours

We do not need to know all the details of JApplet


Prasad S.Halgaonkar 101

A Simple Java Applet: Drawing a String (III)

Classes
Templates/blueprints create or instantiate objects
Objects - locations in memory to store data Implies that data and methods associated with object

Methods
paint, init, and start called automatically for all applets
Get "free" version when you inherit from JApplet By default, have empty bodies Must override them and define yourself
Prasad S.Halgaonkar 102

A Simple Java Applet: Drawing a String (IV)

Method paint
Used to draw graphics, define: public void paint( Graphics g )
Takes a Graphics object g as a parameter For now, all method definitions begin with public

Call methods of object g to draw on applet


drawString("String to draw", x, y); Draws "String to draw" at location (x,y)
Coordinates specify bottom left corner of string (0, 0) is upper left corner of screen Measured in pixels (picture elements)
Prasad S.Halgaonkar 103

A Simple Java Applet: Drawing a String (IV)

Create the HTML file (.html or .htm)


Many HTML codes (tags) come in pairs
<myTag> ... </myTag>

Create <HTML> tags with <applet> tags inside appletviewer only understands <applet> tags
Minimal browser Specify complied .class file, width, and height of applet (in pixels)
<applet code = "WelcomeApplet.class" width = 300 height = 30>

Close tag with </applet>

Running the applet

appletviewer WelcomeApplet.html

Prasad S.Halgaonkar

104

1 2 3 4 5 6 7 8 9

// Fig. 24.13: WelcomeApplet.java // A first applet in Java import javax.swing.JApplet; import java.awt.Graphics; // import class JApplet // import class Graphics

Outline
1. import 2. Define class (extends JApplet)

public class WelcomeApplet extends JApplet { public void paint( Graphics g ) { g.drawString( "Welcome to Java Programming!", 25, 25 );

2.1 Override paint


2.2 g.drawString

10
11 }

1 2 3 4

<html> <applet code="WelcomeApplet.class" width=300 height=30> </applet> </html> </html>

--------------HTML file

Output

2000 Prentice

Hall, Inc. All rights

Two More Simple Applets: Drawing Strings and Lines

Other methods of class Graphics


No concept of lines of text, as in System.out.println when drawing graphics To print multiple lines, use multiple drawString calls drawLine( x1, y2, x2, y2 ) ;
Draws a line from ( x1, y1 ) to ( x2, y2 )

Prasad S.Halgaonkar

106

Outline
1 2 3 4 5 6 7 8 9 10 11 12 13 } // Fig. 24.17: WelcomeLines.java // Displaying text and lines import javax.swing.JApplet; // import class JApplet import java.awt.Graphics; // import class Graphics public class WelcomeLines extends JApplet { public void paint( Graphics g ) { g.drawLine( 15, 10, 210, 10 ); g.drawLine( 15, 30, 210, 30 ); g.drawString( "Welcome to Java Programming!", 25, 25 ); }

1. import 2. Define class (extends JApplet) 2.1 Override paint

Program Output

2000 Prentice

Hall, Inc. All rights

Another Java Applet: Adding Integers

Next applet mimics program to add two integers


This time, use floating point numbers
Can have decimal point, 6.7602 float - single precision floating point number (7 significant digits) double - approximately double precision floating point number (15 significant digits)
Uses more memory

Use showInputDialog to get input, as before Use Double.parseDouble( String)


Converts a String to a double

Prasad S.Halgaonkar

108

Another Java Applet: Adding Integers (II)


import statements
Not necessary if specify full class name every time needed public void paint( java.awt.Graphics g) * - indicates all classes in package should be available
import java.swing.*;
Recall that this contains JApplet and JOptionPane

Does not import subdirectories

Instance variables
Variables declared in body of a class (not in a method)
Each object of class gets its own copy Can be used inside any method of the class

Before, variables declared in main


Local variables, known only in body of method defined
Prasad S.Halgaonkar 109

Another Java Applet: Adding Integers (III)


Instance variables
Have default values
Local variables do not, and require initialization before use Good practice to initialize instance variables anyway

Method init
Called automatically in all applets Commonly used to initialize variables public void init()

References
Identifiers (such as myString) refer to objects
Contain locations in memory

References used to call methods, i.e. g.drawString


Prasad S.Halgaonkar 110

Another Java Applet: Adding Integers (III)


Variables vs. Objects
Variables
Defined by a primitive data type char, byte, short, int, long, float, double, boolean Store one value at a time Variable myInt

Objects defined in classes


Can contain primitive (built-in) data types Can contain methods Graphics object g

If data type a class name, then identifier is a reference


Otherwise, identifier is a variable
Prasad S.Halgaonkar 111

Another Java Applet: Adding Integers (IV)

Other methods of class Graphics


drawRect( x1, y1, x2, y2 ); Draws a rectangle with upper-left corner ( x1, y1 ), and lower right corner (x2, y2 )

Prasad S.Halgaonkar

112

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30

// Fig. 24.19: AdditionApplet.java // Adding two floating-point numbers import java.awt.Graphics; // import class Graphics import javax.swing.*; // import package javax.swing public class AdditionApplet extends JApplet { double sum; // sum of the values entered by the user public void init() { String firstNumber, secondNumber; double number1, number2;

Outline
1. import (note *) 2. Define class (extends JApplet)

// // // //

first string entered by user second string entered by user first number to add second number to add

2.1 init 2.2 Declare variables

// read in first number from user firstNumber = JOptionPane.showInputDialog( "Enter first floating-point value" ); // read in second number from user secondNumber = JOptionPane.showInputDialog( "Enter second floating-point value" ); // convert numbers from type String to type double number1 = Double.parseDouble( firstNumber ); number2 = Double.parseDouble( secondNumber ); // add the numbers 2000 Prentice Hall, Inc. All rights

2.3 Input
2.4 Convert String to double

Outline
2.5 sum numbers 2.6 paint
31
32 33 34 35 36 public void paint( Graphics g ) { // draw the results with g.drawString }

sum = number1 + number2;

2.7 drawRect 2.8 drawString -------------HTML file

37
38 39 40 } }

g.drawRect( 15, 10, 270, 20 );


g.drawString( "The sum is " + sum, 25, 25 );

<html>

2 <applet code="AdditionApplet.class" width=300 height=50>


3 </applet> 4 </html> </html> 2000 Prentice

Hall, Inc. All rights

Outline

Program Output

2000 Prentice

Hall, Inc. All rights

Threads

Java Threads
A thread is not an object A thread is a flow of control A thread is a series of executed statements A thread is a nested sequence of method calls

Prasad S.Halgaonkar

117

The Thread Object


A thread is not an object A Thread is an object void start()
Creates a new thread and makes it runnable

void run()
The new thread begins its life inside this method

Prasad S.Halgaonkar

118

Thread Creation Diagram


Object A Object BThread (extends Thread)

BThread() { } Thread t = new BThread(); t.start(); doMoreStuff(); void run() { doSomething(); }


Prasad S.Halgaonkar 119

void start() { // create thread }

Thread Creation Diagram


Object A Object BThread (extends Thread)

BThread() { } Thread t = new BThread(); t.start(); doMoreStuff(); void run() { doSomething(); }


Prasad S.Halgaonkar 120

void start() { // create thread }

Thread Creation Diagram


Object A Object BThread (extends Thread)

BThread() { } Thread t = new BThread(); t.start(); doMoreStuff(); void run() { doSomething(); }


Prasad S.Halgaonkar 121

void start() { // create thread }

Thread Creation Diagram


Object A Object BThread (extends Thread)

BThread() { } Thread t = new BThread(); t.start(); doMoreStuff(); void run() { doSomething(); }


Prasad S.Halgaonkar 122

void start() { // create thread }

Thread Creation Diagram


Object A Object BThread (extends Thread)

BThread() { } Thread t = new BThread(); t.start(); doMoreStuff(); void run() { doSomething(); }


Prasad S.Halgaonkar 123

void start() { // create thread }

Thread Creation Diagram


Object A Object BThread (extends Thread)

BThread() { } Thread t = new BThread(); t.start(); doMoreStuff(); void run() { doSomething(); }


Prasad S.Halgaonkar 124

void start() { // create thread }

Thread Creation Diagram


Object A Object BThread (extends Thread)

BThread() { } Thread t = new BThread(); t.start(); doMoreStuff(); void run() { doSomething(); }


Prasad S.Halgaonkar 125

void start() { // create thread }

Thread Creation Diagram


Object A Object BThread (extends Thread)

BThread() { } Thread t = new BThread(); t.start(); doMoreStuff(); void run() { doSomething(); }


Prasad S.Halgaonkar 126

void start() { // create thread }

Thread Creation Diagram


Object A Object BThread (extends Thread)

BThread() { } Thread t = new BThread(); t.start(); doMoreStuff(); void run() { doSomething(); }


Prasad S.Halgaonkar 127

void start() { // create thread }

Runnable Interface
A helper to the thread object The Thread objects run() method calls the Runnable objects run() method Allows threads to run inside any object, regardless of inheritance

Prasad S.Halgaonkar

128

Runnable Example
Talker talker = new Talker(); Thread t = new Thread(talker); t.Start(); --class Talker implements Runnable { public void run() { while (true) { System.out.println(yakitty yak); } } }
Prasad S.Halgaonkar 129

Thread Lifecycle
Active sleep(500) wake up
suspend() resume()

JVM
Born start()

Runnable
stop() stop()
notify wait

Blocked

block on I/O Dead I/O available


Prasad S.Halgaonkar 130

Blocking Threads
When reading from a stream, if input is not available, the thread will block Thread is suspended (blocked) until I/O is available Allows other threads to automatically activate When I/O available, thread wakes back up again
Becomes runnable Not to be confused with the Runnable interface

Prasad S.Halgaonkar

131

Thread Scheduling
In general, the runnable thread with the highest priority is active (running) Java is priority-preemptive
If a high-priority thread wakes up, and a lowpriority thread is running Then the high-priority thread gets to run immediately

Allows on-demand processing


Efficient use of CPU
Prasad S.Halgaonkar 132

Thread Starvation
If a high priority thread never blocks Then all other threads will starve Must be clever about thread priority

Prasad S.Halgaonkar

133

Thread Priorities: General Strategies


Threads that have more to do should get lower priority Counterintuitive Cut to head of line for short tasks Give your I/O-bound threads high priority
Wake up, immediately process data, go back to waiting for I/O
Prasad S.Halgaonkar 134

Race Conditions
Two threads are simultaneously modifying a single object Both threads race to store their value In the end, the last one there wins the race (Actually, both lose)

Prasad S.Halgaonkar

135

Thread Synchronization
Language keyword: synchronized

Takes out a monitor lock on an object


Exclusive lock for that thread

If lock is currently unavailable, thread will block

Prasad S.Halgaonkar

136

Thread Synchronization
Protects access to code, not to data
Make data members private
Synchronize accessor methods

Puts a force field around the locked object so no other threads can enter
Actually, it only blocks access to other synchronizing threads

Prasad S.Halgaonkar

137

Thread Deadlock
If two threads are competing for more than one lock Example: bank transfer between two accounts
Thread A has a lock on account 1 and wants to lock account 2 Thread B has a lock on account 2 and wants to lock account 1

Prasad S.Halgaonkar

138

Avoiding Deadlock
No universal solution

Ordered lock acquisition


Encapsulation (forcing directionality) Spawn new threads Check and back off Timeout

Minimize or remove synchronization


Prasad S.Halgaonkar 139

Wait and Notify


Allows two threads to cooperate

Based on a single shared lock object

Prasad S.Halgaonkar

140

Wait and Notify: Code


Consumer:
synchronized (lock) {
while (!resourceAvailable()) { lock.wait();

}
consumeResource(); }

Prasad S.Halgaonkar

141

Wait and Notify: Code


Producer:
produceResource();
synchronized (lock) { lock.notifyAll();

Prasad S.Halgaonkar

142

Wait/Notify Sequence
Lock Object

1. synchronized(lock){ 2. lock.wait(); 9. consumeResource(); 10. }

7. Reacquire lock 8. Return from wait()

3. produceResource() 4. synchronized(lock) 5. lock.notify(); 6.}

Consumer Thread

Producer Thread

Prasad S.Halgaonkar

143

Wait/Notify Sequence
Lock Object

1. synchronized(lock){ 2. lock.wait(); 9. consumeResource(); 10. }

7. Reacquire lock 8. Return from wait()

3. produceResource() 4. synchronized(lock) 5. lock.notify(); 6.}

Consumer Thread

Producer Thread

Prasad S.Halgaonkar

144

Wait/Notify Sequence
Lock Object

1. synchronized(lock){ 2. lock.wait(); 9. consumeResource(); 10. }

7. Reacquire lock 8. Return from wait()

3. produceResource() 4. synchronized(lock) 5. lock.notify(); 6.}

Consumer Thread

Producer Thread

Prasad S.Halgaonkar

145

Wait/Notify Sequence
Lock Object

1. synchronized(lock){ 2. lock.wait(); 9. consumeResource(); 10. }

7. Reacquire lock 8. Return from wait()

3. produceResource() 4. synchronized(lock) 5. lock.notify(); 6.}

Consumer Thread

Producer Thread

Prasad S.Halgaonkar

146

Wait/Notify Sequence
Lock Object

1. synchronized(lock){ 2. lock.wait(); 9. consumeResource(); 10. }

7. Reacquire lock 8. Return from wait()

3. produceResource() 4. synchronized(lock){ 5. lock.notify(); 6.}

Consumer Thread

Producer Thread

Prasad S.Halgaonkar

147

Wait/Notify Sequence
Lock Object

1. synchronized(lock){ 2. lock.wait(); 9. consumeResource(); 10. }

7. Reacquire lock 8. Return from wait()

3. produceResource() 4. synchronized(lock){ 5. lock.notify(); 6.}

Consumer Thread

Producer Thread

Prasad S.Halgaonkar

148

Wait/Notify Sequence
Lock Object

1. synchronized(lock){ 2. lock.wait(); 9. consumeResource(); 10. }

7. Reacquire lock 8. Return from wait()

3. produceResource() 4. synchronized(lock) 5. lock.notify(); 6.}

Consumer Thread

Producer Thread

Prasad S.Halgaonkar

149

Wait/Notify Sequence
Lock Object

1. synchronized(lock){ 2. lock.wait(); 9. consumeResource(); 10. }

7. Reacquire lock 8. Return from wait()

3. produceResource() 4. synchronized(lock) 5. lock.notify(); 6.}

Consumer Thread

Producer Thread

Prasad S.Halgaonkar

150

Wait/Notify Sequence
Lock Object

1. synchronized(lock){ 2. lock.wait(); 9. consumeResource(); 10. }

7. Reacquire lock 8. Return from wait()

3. produceResource() 4. synchronized(lock) 5. lock.notify(); 6.}

Consumer Thread

Producer Thread

Prasad S.Halgaonkar

151

Wait/Notify Sequence
Lock Object

1. synchronized(lock){ 2. lock.wait(); 9. consumeResource(); 10. }

7. Reacquire lock 8. Return from wait()

3. produceResource() 4. synchronized(lock) 5. lock.notify(); 6.}

Consumer Thread

Producer Thread

Prasad S.Halgaonkar

152

Wait/Notify Sequence
Lock Object

1. synchronized(lock){ 2. lock.wait(); 9. consumeResource(); 10. }

7. Reacquire lock 8. Return from wait()

3. produceResource() 4. synchronized(lock) 5. lock.notify(); 6.}

Consumer Thread

Producer Thread

Prasad S.Halgaonkar

153

Wait/Notify: Details
Often the lock object is the resource itself Sometimes the lock object is the producer thread itself

Prasad S.Halgaonkar

154

Wait/Notify: Details
Must loop on wait(), in case another thread grabs the resource...
After you are notified Before you acquire the lock and return from wait()

Use lock.notifyAll() if there may be more than one waiting thread

Prasad S.Halgaonkar

155

Multithreading in Java

Single-Threaded Development
Many programs written for class so far have been single-threaded. When you call a method, it only returns once its task is complete.

Prasad S.Halgaonkar

157

Thread Stalling
What happens when a method needs to wait for something before returning, such as user input or a network connection? (Recall accept() from last lecture) How can we handle other tasks while waiting to accept a new network connection?

Prasad S.Halgaonkar

158

Multithreading
Answer: Accept connections in a different thread. Java allows us to create new threads for handling concurrent tasks.

Prasad S.Halgaonkar

159

How?
Java provides two ways to create a new thread.
Extend the Thread class (java.lang.Thread) Implement the Runnable interface (java.lang.Runnable)

Prasad S.Halgaonkar

160

Javas Thread Class


When creating a new thread by extending the Thread class, you should override the run() method.
public class FooThread extends Thread { public FooThread() { // Initialize parameters } public void run() { // do something } }
Prasad S.Halgaonkar 161

Now What?
To start a new thread, use the inherited method start()
FooThread ft = new FooThread(); ft.start();

Prasad S.Halgaonkar

162

What happens in start()?


start() is responsible

for two things:

Instructing the JVM to create a new thread Call your Thread objects run() method in the new thread

You might think of run() as being similar to


main()

Prasad S.Halgaonkar

163

More about Thread.run()


Like main(), run() defines a starting point for the JVM. What happens when the run() method exits?
The thread ends.

Prasad S.Halgaonkar

164

Another method - Runnable


A thread can also be created by implementing the Runnable interface instead of extending the Thread class.
public class FooRunnable implements Runnable { public FooRunnable() { } public void run() { // do something } }

Prasad S.Halgaonkar

165

Starting a Runnable
Pass an object that implements Runnable to the constructor of a Thread object, then start the thread as before.
FooRunnable fr = new FooRunnable(); new Thread(fr).start()

Prasad S.Halgaonkar

166

Multithreading Pros and Cons


Pro: Multiple threads run concurrently on the system
Multiple tasks can be handled at once. Processing can be done in the background so as not to interrupt the user.

Con: Multiple threads run concurrently on the system


No more guarantees as to what has already happened, what objects have been initialized yet, etc. Code now has to be thread-safe or synchronized Debugging becomes much harder.

Prasad S.Halgaonkar

167

Tips for Writing Thread-safe Code


Limit a threads access to common variables Track changes to instance variables through get/set methods When two or more threads are accessing a collection, make sure the collection being used is synchronized (i.e. using Vector instead of ArrayList)

Prasad S.Halgaonkar

168

How do I stop it??


Methods used to directly stop or suspend threads have been depreciated in the Java API, as they could cause synchronization issues. The threads run() method must return for the thread to stop.

Prasad S.Halgaonkar

169

Interesting Facts
In many of your Swing programs, main() has consisted of creating a new JFrame object and calling show() on it show() actually starts a new thread that the GUI runs in and returns immediately main() then returns. Why doesnt your program end when main() does? Java applications only exit when all of their threads have stopped.
Prasad S.Halgaonkar 170

A Simpler Way
Multithreading can add a lot of complexity to a program. Sometimes you simply want some simple event to happen in the background at a given interval.

Prasad S.Halgaonkar

171

Socket Programming in Java

How to Open a Socket? -ClientSocket MyClient; MyClient = new Socket("Machine name", PortNumber);

How to Open a Socket? -Client Machine name is the machine you are trying to open a connection to(ex: ip address or workstation name), and PortNumber is the port (a number) on which the server you are trying to connect to is running. When selecting a port number, you should note that port numbers between 0 and 1,023 are reserved for privileged users (that is, super user or root).

How to Open a Socket? -Client These port numbers are reserved for standard services, such as email, FTP, and HTTP. When selecting a port number for your server, select one that is greater than 1,023!

How to Open a Socket? -Client With exception handling, the code look like following: Socket MyClient; try {
MyClient = new Socket("Machine name", PortNumber);

} catch (IOException e) { System.out.println(e); }

How to Open a Socket? -ServerServerSocket MyService; try {


MyServerice = new ServerSocket(PortNumber);

} catch (IOException e) { System.out.println(e); }

How to Open a Socket? -Server When implementing a server you also need to create a socket object from the ServerSocket in order to listen for and accept connections from clients. Socket clientSocket = null; try { serviceSocket = MyService.accept(); } catch (IOException e) { System.out.println(e); }

How Do I Create an Input Stream? -Client On the client side, you can use the DataInputStream class to create an input stream to receive response from the server:
DataInputStream input; try { input = new DataInputStream(MyClient.getInputStream()); } catch (IOException e) { System.out.println(e); }

How Do I Create an Input Stream? -Client The class DataInputStream allows you to read lines of text and Java primitive data types in a portable way. It has methods such as read, readChar, readInt, readDouble, and readLine,. Use whichever function you think suits your needs depending on the type of data that you receive from the server.

How Do I Create an Input Stream? -Server On the server side, you can use DataInputStream to receive input from the client
DataInputStream input; try { input = new DataInputStream(serviceSocket.getInputStream()); } catch (IOException e) { System.out.println(e); }

How do I Create an Output Stream? -Client On the client side, you can create an output stream to send information to the server socket using the class PrintStream or DataOutputStream of java.io:

How do I Create an Output Stream? -ClientPrintStream output; try {


output = new PrintStream(MyClient.getOutputStream());

catch (IOException e) { System.out.println(e); }

How do I Create an Output Stream? -Client The class PrintStream has methods for displaying textual representation of Java primitive data types. you may use the DataOutputStream

How do I Create an Output Stream? -ClientDataOutputStream output;

try {
output = new DataOutputStream(MyClient.getOutputStream());

} catch (IOException e) { System.out.println(e); }

How do I Create an Output Stream? -Client The class DataOutputStream allows you to write Java primitive data types; many of its methods write a single Java primitive type to the output stream. The method writeBytes is a useful one.

How do I Create an Output Stream? -Server On the server side, you can use the class PrintStream to send information to the client. PrintStream output; try { output = new PrintStream(serviceSocket.getOutputStream()); } catch (IOException e) { System.out.println(e); }

How do I Create an Output Stream? -Server You can use the class DataOutputStream as mentioned DataOutputStream output; try { output = new DataOutputStream(serviceSocket.getOutputStream() ); } catch (IOException e) { System.out.println(e); }

How Do I Close Sockets? -Client You should always close the output and input stream before you close the socket. try { output.close(); input.close(); MyClient.close(); } catch (IOException e) { System.out.println(e); }

How Do I Close Sockets? -Servertry { output.close(); input.close(); serviceSocket.close(); MyService.close(); } catch (IOException e) { System.out.println(e); }

Examples -Client When programming a client, you must follow these four steps:

1.Open a socket. 2.Open an input and output stream to the Socket. 3.Read from and write to the socket according to the server's protocol. 4.Clean up.
These steps are pretty much the same for all clients. The only step that varies is step three, since it depends on the server you are talking to.

JDBC and Database Programming in Java

Overview
RMI JDBC CORBA

java.net

TCP/IP

Network OS

Part I: Overview of Databases and Java

Databases in the Enterprise


All corporate data stored in DB SQL standardizes format (sort of)

Why Java?
Write once, run anywhere
Multiple client and server platforms

Object-relational mapping
databases optimized for searching/indexing objects optimized for engineering/flexibility

Network independence
Works across Internet Protocol

Database independence
Java can access any database vendor

Ease of administration
zero-install client

Database Architectures
Two-tier Three-tier N-tier

Two-Tier Architecture
Client connects directly to server e.g. HTTP, email Pro:
simple client-side scripting offloads work onto the client

Con:
fat client inflexible

Three-Tier Architecture
Application Server sits between client and database

Three-Tier Pros
flexible: can change one part without affecting others can connect to different databases without changing code specialization: presentation / business logic / data management can cache queries can implement proxies and firewalls

Three-Tier Cons
higher complexity higher maintenance lower network efficiency more parts to configure (and buy)

N-Tier Architecture
Design your application using as many tiers as you need Use Object-Oriented Design techniques Put the various components on whatever host makes sense Java allows N-Tier Architecture, especially with RMI and JDBC

Database Technologies
Hierarchical
obsolete (in a manner of speaking) any specialized file format can be called a hierarchical DB

Relational (aka SQL) (RDBMS)


row, column most popular

Object-relational DB (ORDBMS)
add inheritance, blobs to RDB NOT object-oriented -- object is mostly a marketing term

Object-oriented DB (OODB)
data stored as objects high-performance for OO data models

Relational Databases
invented by Dr. E.F.Codd data stored in records which live in tables maps row (record) to column (field) in a single table relation (as in relational) means row to column (not table to table)

Joining Tables
you can associate tables with one another allows data to nest allows arbitrarily complicated data structures not object-oriented

Join example
People
name homeaddress workaddress

Addresses
id street state zip

SQL
Structured Query Language Standardized syntax for querying (accessing) a relational database Supposedly database-independent Actually, there are important variations from DB to DB

SQL Syntax
INSERT INTO table ( field1, field2 ) VALUES ( value1, value2 ) inserts a new record into the named table UPDATE table SET ( field1 = value1, field2 = value2 ) WHERE condition changes an existing record or records DELETE FROM table WHERE condition removes all records that match condition SELECT field1, field2 FROM table WHERE condition retrieves all records that match condition

Transactions
Transaction = more than one statement which must all succeed (or all fail) together If one fails, the system must reverse all previous actions Also cant leave DB in inconsistent state halfway through a transaction COMMIT = complete transaction ROLLBACK = abort

Part II: JDBC Overview


JDBC Goals
SQL-Level 100% Pure Java Keep it simple High-performance Leverage existing database technology
why reinvent the wheel?

Use strong, static typing wherever possible Use multiple methods to express multiple functionality

JDBC Ancestry
X/OPEN

ODBC

JDBC

JDBC Architecture
Application JDBC Driver

Java code calls JDBC library JDBC loads a driver Driver talks to a particular database Can have more than one driver -> more than one database Ideal: can change database engines without changing any application code

JDBC Drivers
Type I: Bridge Type II: Native Type III: Middleware Type IV: Pure

JDBC Drivers (Fig.)


Type I Bridge

ODBC

ODBC Driver

JDBC

Type II Native

CLI (.lib)

Type III Middleware

Middleware Server

Type IV Pure

Type I Drivers
Use bridging technology Requires installation/configuration on client machines Not good for Web e.g. ODBC Bridge

Type II Drivers
Native API drivers Requires installation/configuration on client machines Used to leverage existing CLI libraries Usually not thread-safe Mostly obsolete now e.g. Intersolv Oracle Driver, WebLogic drivers

Type III Drivers


Calls middleware server, usually on database host Very flexible -- allows access to multiple databases using one driver Only need to download one driver But its another server application to install and maintain e.g. Symantec DBAnywhere

Type IV Drivers
100% Pure Java Use Java networking libraries to talk directly to database engines Only disadvantage: need to download a new driver for each database engine e.g. Oracle, mSQL

JDBC Limitations
No scrolling cursors No bookmarks

Related Technologies
ODBC
Requires configuration (odbc.ini)

RDO, ADO
Requires Win32

OODB
e.g. ObjectStore from ODI

JavaBlend
maps objects to tables transparently (more or less)

Part III: JDBC APIs java.sql


JDBC is implemented via classes in the java.sql package

Loading a Driver Directly


Driver d = new foo.bar.MyDriver(); Connection c = d.connect(...); Not recommended, use DriverManager instead Useful if you know you want a particular driver

DriverManager
DriverManager tries all the drivers Uses the first one that works When a driver class is first loaded, it registers itself with the DriverManager Therefore, to register a driver, just load it!

Registering a Driver
statically load driver
Class.forName(foo.bar.MyDriver); Connection c = DriverManager.getConnection(...);

or use the jdbc.drivers system property

JDBC Object Classes


DriverManager
Loads, chooses drivers

Driver
connects to actual database

Connection
a series of SQL statements to and from the DB

Statement
a single SQL statement

ResultSet
the records returned from a Statement

JDBC Class Usage


DriverManager

Driver

Connection

Statement

ResultSet

JDBC URLs
jdbc:subprotocol:source each driver has its own subprotocol each subprotocol has its own syntax for the source
jdbc:odbc:DataSource
e.g. jdbc:odbc:Northwind

jdbc:msql://host[:port]/database
e.g. jdbc:msql://foo.nowhere.com:4333/accounting

DriverManager
Connection getConnection (String url, String user, String password) Connects to given JDBC URL with given user name and password Throws java.sql.SQLException returns a Connection object

Connection
A Connection represents a session with a specific database. Within the context of a Connection, SQL statements are executed and results are returned. Can have multiple connections to a database NB: Some drivers dont support serialized connections Fortunately, most do (now) Also provides metadata -- information about the database, tables, and fields Also methods to deal with transactions

Obtaining a Connection
String url = "jdbc:odbc:Northwind"; try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection(url); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }

Connection Methods
Statement createStatement()
returns a new Statement object

PreparedStatement prepareStatement(String sql)


returns a new PreparedStatement object

CallableStatement prepareCall(String sql)


returns a new CallableStatement object

Why all these different kinds of statements? Optimization.

Statement
A Statement object is used for executing a static SQL statement and obtaining the results produced by it.

Statement Methods
ResultSet executeQuery(String)
Execute a SQL statement that returns a single ResultSet.

int executeUpdate(String)
Execute a SQL INSERT, UPDATE or DELETE statement. Returns the number of rows changed.

boolean execute(String)
Execute a SQL statement that may return multiple results.

Why all these different kinds of queries? Optimization.

ResultSet
A ResultSet provides access to a table of data generated by executing a Statement. Only one ResultSet per Statement can be open at once. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The 'next' method moves the cursor to the next row.
you cant rewind

ResultSet Methods
boolean next()
activates the next row the first call to next() activates the first row returns false if there are no more rows

void close()
disposes of the ResultSet allows you to re-use the Statement that created it automatically called by most Statement methods

ResultSet Methods
Type getType(int columnIndex)
returns the given field as the given type fields indexed starting at 1 (not 0)

Type getType(String columnName)


same, but uses name of field less efficient

int findColumn(String columnName)


looks up column index given column name

ResultSet Methods
String getString(int columnIndex) boolean getBoolean(int columnIndex) byte getByte(int columnIndex) short getShort(int columnIndex) int getInt(int columnIndex) long getLong(int columnIndex) float getFloat(int columnIndex) double getDouble(int columnIndex) Date getDate(int columnIndex) Time getTime(int columnIndex) Timestamp getTimestamp(int columnIndex)

ResultSet Methods
String getString(String columnName) boolean getBoolean(String columnName) byte getByte(String columnName) short getShort(String columnName) int getInt(String columnName) long getLong(String columnName) float getFloat(String columnName) double getDouble(String columnName) Date getDate(String columnName) Time getTime(String columnName) Timestamp getTimestamp(String columnName)

isNull
In SQL, NULL means the field is empty Not the same as 0 or In JDBC, you must explicitly ask if a field is null by calling ResultSet.isNull(column)

Sample Database
Employee ID 1 2 3 4 5 Last Name Davolio Fuller Leverling Peacock Buchanan First Name Nancy Andrew Janet Margaret Steven

SELECT Example
Connection con = DriverManager.getConnection(url, "alex", "8675309"); Statement st = con.createStatement(); ResultSet results = st.executeQuery("SELECT EmployeeID, LastName, FirstName FROM Employees");

SELECT Example (Cont.)


while (results.next()) { int id = results.getInt(1); String last = results.getString(2); String first = results.getString(3); System.out.println("" + id + ": " + first + " " + last); } st.close(); con.close();

Mapping Java Types to SQL Types


SQL type CHAR, VARCHAR, LONGVARCHAR NUMERIC, DECIMAL BIT TINYINT SMALLINT INTEGER BIGINT REAL FLOAT, DOUBLE BINARY, VARBINARY, LONGVARBINARY DATE TIME TIMESTAMP Java Type String java.math.BigDecimal boolean byte short int long float double byte[] java.sql.Date java.sql.Time java.sql.Timestamp

Database Time
Times in SQL are notoriously unstandard Java defines three classes to help java.sql.Date
year, month, day

java.sql.Time
hours, minutes, seconds

java.sql.Timestamp
year, month, day, hours, minutes, seconds, nanoseconds usually use this one

Modifying the Database


use executeUpdate if the SQL contains INSERT or UPDATE Why isnt it smart enough to parse the SQL? Optimization. executeUpdate returns the number of rows modified executeUpdate also used for CREATE TABLE etc. (DDL)

Transaction Management
Transactions are not explicitly opened and closed Instead, the connection has a state called AutoCommit mode if AutoCommit is true, then every statement is automatically committed default case: true

setAutoCommit
Connection.setAutoCommit(boolean) if AutoCommit is false, then every statement is added to an ongoing transaction you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback()

Connection Managers
Hint: for a large threaded database server, create a Connection Manager object It is responsible for maintaining a certain number of open connections to the database When your applications need a connection, they ask for one from the CMs pool Why? Because opening and closing connections takes a long time Warning: the CM should always setAutoCommit(false) when a connection is returned

Optimized Statements
Prepared Statements
SQL calls you make again and again allows driver to optimize (compile) queries created with Connection.prepareStatement()

Stored Procedures
written in DB-specific language stored inside database accesed with Connection.prepareCall()

JDBC Class Diagram

Metadata
Connection:
DatabaseMetaData getMetaData()

ResultSet:
ResultSetMetaData getMetaData()

JAVA vs. C++ Main Differences

JAVA vs C++
Java is (an interpreted) write once, run anywhere language.
The biggest potential stumbling block is speed: interpreted Java runs in the range of 20 times slower than C. But: nothing prevents the Java language from being compiled and there are just-in-time (JIT) compilers that offer significant speed-ups. Write once, run everywhere does (nearly) NEVER work with C++, but does (nearly) ALWAYS work with JAVA.

JAVA vs C++
You don't have separated HEADER-files defining classproperties
You can define elements only within a class. All method definitions are also defined in the body of the class. Thus, in C++ it would look like all the functions are inlined (but theyre not). File- and classname must be identical in JAVA Instead of C++ #include you use the import keyword.
For example: import java.awt.*;.
#include does not directly map to import, but it has a similar feel to it

JAVA vs C++
Instead of controlling blocks of declarations like C++ does, the access specifiers (public, private, and protected) are placed on each definition for each member of a class
Without an explicit access specifier, an element defaults to "friendly," which means that it is accessible to other elements in the same package (which is a collection of classes being friends)
The class, and each method within the class, has an access specifier to determine whether its visible outside the file.

JAVA vs C++
Everything must be in a class.
There are no global functions or global data. If you want the equivalent of globals, make static methods and static data within a class.
There are no structs or enumerations or unions, only classes. Class definitions are roughly the same form in Java as in C++, but theres no closing semicolon.

JAVA vs C++
Java has no preprocessor.
If you want to use classes in another library, you say import and the name of the library.
There are no preprocessor-like macros. There is no conditional compiling (#ifdef)

All the primitive types in Java have specified sizes that are machine independent for portability.
On some systems this leads to non-optimized performance The char type uses the international 16-bit Unicode character set, so it can automatically represent most national characters.

JAVA vs C++

Type-checking and type requirements are much tighter in Java.


For example:
1. Conditional expressions can be only boolean, not integral.

2. The result of an expression like X + Y must be used; you cant just say "X + Y" for the side effect.

JAVA vs C++
There are Strings in JAVA
Strings are represented by the String-class, they arent only some renamed pointers

Static quoted strings are automatically converted into String objects.


There is no independent static character array string like there is in C and C++.

JAVA vs C++
There are no Java pointers in the sense of C and C++
Theres nothing more to say, except that it is a bit confusing, that a pointerless language like JAVA has a null-pointer error-message...

JAVA vs C++
Although they look similar, arrays have a very different structure and behavior in Java than they do in C++.
Theres a read-only length member that tells you how big the array is,

and run-time checking throws an exception if you go out of bounds. All arrays are created on the heap, and you can assign one array to another (the array handle is simply copied).

JAVA vs C++
There is a garbage collection in JAVA
Garbage collection means memory leaks are much harder to cause in Java, but not impossible. (If you make native method calls that allocate storage, these are typically not tracked by the garbage collector.) The garbage collector is a huge improvement over C++, and makes a lot of programming problems simply vanish. It might make Java unsuitable for solving a small subset of problems that cannot tolerate a garbage collector, but the advantage of a garbage collector seems to greatly outweigh this potential drawback.

JAVA vs C++
There are no destructors in Java.
There's no need because of garbage collection.

JAVA vs C++
Java uses a singly-rooted hierarchy, so all objects are ultimately inherited from the root class Object.
The inheritance of properties of different classes is handled by interfaces. Java provides the interface keyword, which creates the equivalent of an abstract base class filled with abstract methods and with no data members. This makes a clear distinction between something designed to be just an interface and an extension of existing functionality via the extends keyword. Its worth noting that the abstract keyword produces a similar effect in that you cant create an object of that class.

JAVA vs C++
Java has method overloading, but no operator overloading. Java has both kinds of comments like C++ does. Theres no goto in Java.
The one unconditional jump mechanism is the break label or continue label, which is used to jump out of the middle of multiply-nested loops.

Java has built-in support for comment documentation


so the source code file can also contain its own documentation, which is stripped out and reformatted into HTML via a separate program. This is a boon for documentation maintenance and use.

JAVA vs C++
Java contains standard libraries for GUIs
Simple, robust and effective way of creating user-interfaces

Graphical output as part of the language

JAVA vs C++
Java contains standard libraries for solving specific tasks. C++ relies on non-standard third-party libraries.
These tasks include:
Networking, Database Connection (via JDBC) Distributed Objects (via RMI and CORBA) Compression, Commerce Whatever you want: VoIP, Video-Telephony, MIDI, Games,...

The availability and standard nature of these libraries allow for more rapid application development.

JAVA vs C++
Generally, Java is more robust, via:
Object handles initialized to null (a keyword).Handles are always checked and exceptions are thrown for failures All array accesses are checked for bounds violations Automatic garbage collection prevents memory leaks

Clean, relatively fool-proof exception handling


Simple language support for multithreading Bytecode verification of network applets

Standard GUI

JAVA vs C++

...and its FREE !