CS2311-oops EEE
CS2311-oops EEE
creation of well-defined interface for an object, separate from its implementation e.g., Vector in Java e.g., key functionalities (init, add, delete, count, print) which can be called independently of knowing how an object is implemented
encapsulation
keeping implementation details private, i.e., inside the implementation hierarchy an object is defined in terms of other objects Composition => larger objects out of smaller ones Inheritance => properties of smaller objects are inherited by larger objects
polymorphism
use code transparently for all types of same class of object i.e., morph one object into another object within same hierarchy
Advantages
Can create new programs faster because we can reuse code Easier to create new data types Easier memory management Programs should be less bug-prone, as it uses a stricter syntax and type checking. `Data hiding', the usage of data by one program part while other program parts cannot access the data Will whiten your teeth
Disadvantages
disadvantages of C++ over Java: Java protects you from making mistakes that C/C++ dont, as youve C++ has many concepts and possibilities so it has a steep learning curve extensive use of operator overloading, function overloading and virtual functions can very quickly make C++ programs very complicated shortcuts offered in C++ can often make it completely unreadable, just like in C
Sample Hello.cpp
#include <iostream.h> #include <stdio.h> using namespace std; main() { cout << "hello world\n"; cout << "hello" << " world" << endl; }
Data types
simple native data types: bool, int, double, char, wchar_t bool is like boolean in Java wchar_t is wide char for representing data from character sets with more than 255 characters modifiers: short, long, signed, unsigned, e.g., short int floating point types: float, double, long double enum and typedef just like C
Operators
same as C, with some additions if you recognize it from C, then its pretty safe to assume it is doing the same thing in C++ Operator overloading
Type conversions
All integer math is done using int datatypes, so all types (bool, char, short, enum) are promoted to int before any arithmetic operations are performed on them Mixed expressions of integer / floating types promote the lower type to the higher type according to the following hierarchy: int < unsigned < long < unsigned long < float < double < long double
Program structure
just like in C program is a collection of functions and declarations language is block-structured declarations are made at the beginning of a block; allocated on entry to the block and freed when exitingthe block parameters are call-by-value unless otherwise specified
Arrays
similar to C dynamic memory allocation handled using new and delete instead of malloc (and family) and free examples: int a[5]; char b[3] = { a, b, c }; double c[4][5]; int *p = new int(5); // space allocated and *p set to 5 int **q = new int[10]; // space allocated and q = &q[0] int *r = new int; // space allocated but not initialized
UNIT-II
Declaring Class
Almost like struct, the default privacy specification is private whereas with struct, the default privacy specification is public Example: class point { double x, y; // implicitly private public: void print(); void set( double u, double v ); }; classes can be nested (like java) static is like in Java, with some weird subtleties
Access specifiers
public public members can be accessed from any function private members can only be accessed by classs own members and by friends (see ahead) Protected Class members, derived, and friends. access violations when you dont obey the rules... can be listed in any order can be repeated
More coding
class point { double x,y; public: point() { x=0;y=0; } // default point( double u ) {x =u; y=0; } // conversion point( double u, double v ) { x =u; y =v;} ...}
Operator overloading
Most operators can be overloaded in cpp Treated as functions But its important to understand how they really work
LIST OF OPERATORS
+ ~ ! = * /= += << >>
Types of overloading
Unary overloading Binary overloading
Inheritance
Objects are often defined in terms of hierarchical classes with a base class and one or more levels of classes that inherit from the classes that are above it in the hierarchy. For instance, graphics objects might be defined as follows:
Inheritance (continued)
class A : base class access specifier B { member access specifier(s): ... member data and member function(s); ... } Valid access specifiers include public, private, and protected
Hierarchy
Virtual Functions
A superclass pointer can reference a subclass object
Sphere *mySphere = new Sphere(); Object3D *myObject = mySphere;
If a superclass has virtual functions, the correct subclass version will automatically be selected
Superclass Subclass class Object3D { virtual void intersect(Ray *r, Hit *h); }; class Sphere : public Object3D { virtual void intersect(Ray *r, Hit *h); }; myObject->intersect(ray, hit);
Actually calls
Sphere::intersect
A class with a pure virtual function is called a pure virtual class and cannot be instantiated. (However, its subclasses can).
UNIT-III
IO STREAMS
Input/Output
Not part of the language; implemented in library (like C and Pascal) The C I/O library stdio.h is available quite cryptic to use fprint, fprintf, etc. The C++ library iostream is better type-safe extensible very easy to use
Iostream Basics
<< is "put to" operator >> is "get from" operator Three standard streams: cout, cin, cerr std::cin >> x; std::cout << Hello world!; std::cerr << Oops!; std::cout << x;
Unformatted I/O
cout.write(buffer, SIZE) cin.read(buffer, SIZE) The memory contents pointed by buffer is read/write. In formatted I/O, contents are translated into printable ASCII sequence
Format States
setiosflag(iso::S) Where S can be skipws, left, right, dec, oct, showpoint, uppercase, fixed etc.
Write in a File
#include <iostream> #include <fstream> ofstream fileobj(f.dat, ios::out);
file object
// create output
// output to file
Read in a File
#include <iostream> #include <fstream> ifstream fileobj(f.dat, ios::in);
input file object
// create
Exception handling
makes clear, robust, fault-tolerant programs C++ removes error handling code from "main line" of program
Common failures
new not allocating memory out of bounds array subscript division by zero invalid function parameters
typically used when error dealt with in different place than where it occurred useful when program cannot recover but must shut down cleanly
Exception handling
Exception handling improves fault-tolerance
easier to write error-processing code specify what type of exceptions are to be caught
Exception handling another way to return control from a function or block of code
Ignore exceptions
use this "technique" on casual, personal programs - not commercial!
specific errors
some have dedicated capabilities for handling them if new fails to allocate memory new_handler function executes to deal with problem
Exception Handling: try, throw, catch A function can throw an exception object if it detects an error
object typically a character string (error message) or class object if exception handler exists, exception caught and handled otherwise, program terminates
Format
enclose code that may have an error in try block follow with one or more catch blocks
each catch block has an exception handler
if exception occurs and matches parameter in catch block, code in catch block executed if no exception thrown, exception handlers skipped and control resumes after catch blocks throw point - place where exception occurred
control cannot return to throw point
1 2 3 4 5 6 7 8 9
// Fig. 13.1: fig13_01.cpp // A simple exception handling example. // Checking for a divide-by-zero exception. #include <iostream> using std::cout; using std::cin; using std::endl;
10 // Class DivideByZeroException to be used in exception 11 // handling for throwing an exception on a division by zero. 12 class DivideByZeroException { 13 public: 14 15 16 18 19 }; 20 DivideByZeroException() : message( "attempted to divide by zero" ) { } const char *what() const { return message; } const char *message;
17 private:
21 // Definition of function quotient. Demonstrates throwing 23 double quotient( int numerator, int denominator ) 24 { 25 26 27 28 29 } if ( denominator == 0 ) throw DivideByZeroException();
1. Class definition
1 2 3 4 5 6 7 8 9
// Fig. 13.1: fig13_01.cpp // A simple exception handling example. // Checking for a divide-by-zero exception. #include <iostream> using std::cout; using std::cin; using std::endl;
10 // Class DivideByZeroException to be used in exception 11 // handling for throwing an exception on a division by zero. 12 class DivideByZeroException { 13 public: 14 15 16 18 19 }; 20 DivideByZeroException() : message( "attempted to divide by zero" ) { } const char *what() const { return message; } const char *message;
17 private:
21 // Definition of function quotient. Demonstrates throwing 23 double quotient( int numerator, int denominator ) 24 { 25 26 27 28 29 } if ( denominator == 0 ) throw DivideByZeroException();
1. Class definition
1 2 3 4 5 6 7 8 9
// Fig. 13.1: fig13_01.cpp // A simple exception handling example. // Checking for a divide-by-zero exception. #include <iostream> using std::cout; using std::cin; using std::endl;
10 // Class DivideByZeroException to be used in exception 11 // handling for throwing an exception on a division by zero. 12 class DivideByZeroException { 13 public: 14 15 16 18 19 }; 20 DivideByZeroException() : message( "attempted to divide by zero" ) { } const char *what() const { return message; } const char *message;
17 private:
21 // Definition of function quotient. Demonstrates throwing 23 double quotient( int numerator, int denominator ) 24 { 25 26 27 28 29 } if ( denominator == 0 ) throw DivideByZeroException();
1. Class definition
30 31 // Driver program 32 int main() 33 { 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 } cout << endl; return 0; // terminate normally } } } catch ( DivideByZeroException ex ) { // exception handler cout << "Exception occurred: " << ex.what() << '\n'; // the try block wraps the code that may throw an // exception and the code that should not execute // if an exception occurs try { result = quotient( number1, number2 ); cout << "The quotient is: " << result << endl; while ( cin >> number1 >> number2 ) { cout << "Enter two integers (end-of-file to end): "; int number1, number2; double result;
try block encloses code that may throw an exception, along with code that should not execute if an exception occurs.
UNIT-IV
AN OVERVIEW OF JAVA
What is java?
Developed by Sun Microsystems (James Gosling) A general-purpose object-oriented language Based on C/C++ Designed for easy Web/Internet applications Widespread acceptance
Object oriented
focus on the data (objects) and methods manipulating the data all functions are associated with objects almost all datatypes are objects (files, strings, etc.) potentially better code organization and reuse
Portable
same application runs on all platforms the sizes of the primitive data types are always the same the libraries define portable interfaces
Secure
usage in networked environments requires more security memory allocation model is a major defense access restrictions are forced (private, public)
Dynamic
java is designed to adapt to evolving environment libraries can freely add new methods and instance variables without any effect on their clients interfaces promote flexibility and reusability in code by specifying a set of methods an object can perform, but leaves open how these methods should be implemented can check the class type in runtime
Java Disadvantages
Slower than compiled language such as C
an experiment in 1999 showed that Java was 3 or 4 times slower than C or C++
title of the article: Comparing Java vs. C/C++ Efficiency Issues to Interpersonal Issues (Lutz Prechelt)
Note that the command is java, not javac, and you refer to HelloWorldApp, not HelloWorldApp.java or HelloWorldApp.class
Exception
if you see this error, you may need to set the environment variable CLASSPATH.
Array types
Variables
dataType identifier [ = Expression]: Example declarations and initializations: int x; variable x=5; int[] intArray;
boolean b = true; Frame win = new Frame(); String x = how are you?; intArray = new int[2]; intArray[0] = 12; intArray[1] = 6; Person pArray = new Person[10];
Conditional Statements
The if else statement Form of the if else statement
Expression that evaluates to true or false
if ( boolean condition ) { //statement sequence } else { //alternative statement sequence } The else clause is optional, and may not be needed in every situation in which a segment of code is executed conditionally
Statements executed otherwise Block of statements that are executed if the condition is true
Conditional Statements
Relational operators The boolean condition in an if else statement is often expressed as a test of a relationship between two variables.
Is x equal to y? Is x greater than or equal to 0? Is x less than size? Is x not equal to 0? == <= < > >= !=
(x == y) (x >= 0) (x < size) (x != 0)
Conditional Statements
Relational operators Be sure to distinguish between the relational operator == and the assignment operator = x == y x = y; Tests if the contents of variable x are the same as the contents of variable y Assigns the value stored in variable y to variable x (overwriting what is in x and leaving y unchanged)
Several of the relational operators use two characters for their symbol. There must NOT be a space between these two characters. x == y x != y x <= y x >= y
Conditional Statements
Example
import java.util.Scanner; //needed for input stream classes public class ConditionalStatementExample { public static void main (String [ ] args) { //convert a possibly negative integer received from the keyboard to //its positive (absolute) value System.out.println(Enter an integer); Scanner console = new Scanner(System.in); BufferedReader br = new BufferedReader(isr); int theInteger = console.nextInt( ); if (theInteger < 0) theInteger = - theInteger; } }
If the integer is already positive, do nothing else clause is not needed.
Conditional Statements
Programming style
public static void main(String [ ] args) { //list of statements indented 2 to 4 spaces int num1, num2, num3 = 5; num1 = 3 * num3 % 7; num2 = 5 * num3 % 11; //which number is larger if (num1 >= num2) { num1 += num3; }
2 to 4 spaces
Main block
System.out.println(The larger pair is num1, num3); else { num2 += num3; } } Block of stmts. contained in else -- block
Conditional Statements
Programming style Note that if there is only a single statement in the if or else block, curly brackets are not needed. If there is more than one statement in one of these blocks, the curly brackets are required.
if (boolean condition) statement; else statement; } else { statement; Curly brackets optional statement; } Curly brackets required if (boolean condition) { statement; statement;
Conditional Statements
Nested if statements
Consider a function that assigns a letter grade to a numerical test score. (The test score is supplied as a parameter writing functions will be explained fully later, right now we only wish to illustrate a nested if statement. public char gradeGiver(int testScore) { if (testScore >= 90) If the condition is satisfied, the program returns return A; from this function call. Only scores less than 90 else are evaluated further inside this function. if (testScore >= 80) return B; else if (testScore >= 70) return C; By convention, each if and else block is else //testScore < 70 indented 2 to 4 spaces. return F: }
Conditional Statements
Nested if statements The preceding form is somewhat difficult to follow, therefore the preferred way of writing nested if statements is to use an else if construction.
public char gradeGiver (int testScore) { if (testScore >= 90) return A; else if (testScore >= 80) return B; else if (testScore >= 70) return C; else return F; }
Introduction
Java is a true OO language and therefore the underlying structure of all Java programs is classes. Anything we wish to represent in Java must be encapsulated in a class that defines the state and behaviour of the basic program components known as objects. Classes create objects and objects use methods to communicate between them. They provide a convenient method for packaging a group of logically related data items and functions that work on them. A class essentially serves as a template for an object and behaves like a basic data type int. It is therefore important to understand how the fields and methods are defined in a class and how they are used to build a Java program that incorporates the basic OO concepts such as encapsulation, inheritance, and polymorphism.
Classes
A class is a collection of fields (data) and methods (procedure or function) that operate on that data.
Circle centre radius circumference() area()
Classes
A class is a collection of fields (data) and methods (procedure or function) that operate on that data. The basic syntax for a class definition:
class ClassName [extends SuperClassName] { [fields declaration] [methods declaration] }
Bare bone class no fields, no methods public class Circle { // my circle class }
Adding Methods
A class with only data fields has no life. Objects created by such a class cannot respond to any messages. Methods are declared inside the body of the class but immediately after the declaration of data fields. The general form of a method declaration is:
type MethodName (parameter-list) { Method-body; }
Data Abstraction
Declare the Circle class, have created a new data type Data Abstraction Can define variables (objects) of that type:
Circle aCircle; Circle bCircle;
null
null
Java automatically collects garbage periodically and releases the memory used to be used in the future.
Circle aCircle = new Circle(); aCircle.x = 2.0 // initialize center and radius aCircle.y = 2.0 aCircle.r = 1.0
Circle aCircle = new Circle(); double area; aCircle.r = 1.0; area = aCircle.area();
Inheritance
Inheritance allows a software developer to derive a new class from an existing one The existing class is called the parent class or superclass The derived class is called the child class or subclass. Book Creates an is-a relationship The subclass is a more specific version of the Dictionary Novel Original (Remember has-a is Mystery History aggregation.)
94
Inheritance
The child class inherits the methods and data defined for the parent class To tailor a derived class, the programmer can add new variables or methods, or can modify the inherited ones Software reuse is at the heart of inheritance By using existing software components to create new ones, we capitalize on all the effort that went into the design, implementation, and testing of the existing software
Deriving Subclasses
In Java, we use the reserved word extends to establish an inheritance relationship
class Dictionary extends Book { // class contents }
96
public class Book { protected int pages = 1500; public String message() { System.out.println(Number of pages: + pages); }
public class Dictionary extends Book { private int definitions = 52500; public void defMessage() { System.out.println(Number of definitions + definitions); System.out.println(Definitions per page: + (definitions/pages)); }
99
100
public class Book { protected int pages; Book(int numPages) { pages = numPages; }
public class Dictionary { private int definitions; Dictionary(int numPages, int numDefinitions) { super(numPages); definitions = numDefinitions; }
Multiple Inheritance
Java supports single inheritance, meaning that a derived class can have only one parent class Multiple inheritance allows a class to be derived from two or more classes, inheriting the members of all parents Collisions, such as the same variable name in two parents, have to be resolved Java does not support multiple inheritance In most cases, the use of interfaces gives us aspects of multiple inheritance without the overhead.
Overriding Methods
When a child class defines a method with the same name and signature as a method in the parent class, we say that the childs version overrides the parents version in favor of its own. Signature: methods name along with number, type, and order of its parameters The new method must have the same signature as the parent's method, but can have a different body The type of the object executing the method determines which version of the method is invoked
105
Overriding
A parent method can be invoked explicitly using the super reference If a method is declared with the final modifier, it cannot be overridden The concept of overriding can be applied to data and is called shadowing variables Shadowing variables should be avoided because it tends to cause unnecessarily confusing code
public class Book { protected int pages; Book(int numPages) { pages = numPages; } public void message() { System.out.println(Number of pages: + pages); }
public class Dictionary { protected int definitions; Dictionary(int numPages, int numDefinitions) { super(numPages); definitions = numDefinitions; } public void message() { System.out.println(Number of definitions + definitions); System.out.println(Definitions per page: + (definitions/pages)); super.message(); }
Class Hierarchies
A child class of one parent can be the parent of another child, forming a class hierarchy Book
Dictionary Novel
Mystery
Romance
109
Class Hierarchies
Two children of the same parent are called siblings However they are not related by inheritance because one is not used to derive another. Common features should be put as high in the hierarchy as is reasonable An inherited member is passed continually down the line Therefore, a child class inherits from all its ancestor classes There is no single class hierarchy that is appropriate for all situations 110
111
Packages
Package A collection of related classes and/or interfaces Examples: The Java API java.lang Essential classes for the Java language java.text Facilities for formatting text output java.util Special utilities (e.g. Scanner) java.net Network communication Packages can be divided into subpackages java.awt Classes for GUIs and graphics java.awt.font Classes and interface for fonts java.awt.geom Classes for 2-dimensional objects
User-Defined Packages
Packages enable a programmer organize the code into smaller logically related units A large program may consists of hundreds of classes (800 in one current project with NASA) Every class is part of some package If you do not specify a package a class becomes part of the default packageAccess Classes defined within the same package can access one another more easily (no need for imports, fully qualified names) Some classes, object fields only accessible to classes in samepackage
Defining Packages
To define: add package statement to specify package containing the classes of a file package mypackage; public class myClass { } // myClass is part of mypackage Must be first non-comment statement in file _ Packages organized into subpackages using the notation foo.subpackage: package mypackage.mysubpackage; public class myClass2 { } // myClass2 is part of // mysubpackage, which is // within mypackage _ Packages in Eclipse _ Select FileNewPackage _ Enter the full name of the package
Example
Example Files: Driver.java Driver Files: Circle.java Rectangle.java OtherShape.java Files: PublicClass1.java PublicClass2.java Circle Rectangle OtherShape PublicClass1 NonPublicClass1 PublicClass2 graphics graphics.shapes graphics.otherstuff Packages: Files: Classes:
Exception
Error occurred in execution time Abnormal termination of program Wrong execution result Provide an exception handling mechanism in language system Improve the reliability of application program Allow simple program code for exeception check and handling into source
Exception Definition
Treat exception as an object All exceptions are instances of a class extended from Throwable class or its subclass. Generally, a programmer makes new exception class to extend the Exception class which is subclass of Throwable class.
Exception Definition
class classUserErr UserErrextends extendsException Exception { {} } class classUserClass UserClass{ { UserErr UserErrx x= =new newUserErr(); UserErr(); // //... ... if if(val (val< <1) 1)throw throwx; x; } }
Exception Definition
We can pass the object which contains a message for the exception in string form
class classUserErr UserErrextends extendsException Exception{ { UserErr(String // UserErr(Strings) s) super(s); super(s); //constructor constructor } } class classUserClass UserClass{ { // //... ... if if(val (val< <1) 1)throw thrownew newUserErr("user UserErr("userexception exceptionthrow throwmessage") message") } }
...
...
...
Definition of Exception
Error Class
Critical error which is not acceptable in normal application program
Exception Class
Possible exception in normal application program execution Possible to handle by programmer
System-Defined Exception
Raised implicitly by system because of illegal execution of program When cannot continue program execution any more Created by Java System automatically Exception extended from Error class and RuntimeException class
System-Defined Exception
IndexOutOfBoundsException : When beyond the bound of index in the object which use index, such as array, string, and vector ArrayStoreException : When assign object of incorrect type to element of array NegativeArraySizeException : When using a negative size of array NullPointerException : When refer to object as a null pointer SecurityException : When violate security. Caused by security manager IllegalMonitorStateException : When the thread which is not owner of monitor involves wait or notify method
Programmer-Defined Exception
Exceptions raised by programmer Check by compiler whether the exception handler for exception occurred exists or not If there is no handler, it is error Sub class of Exception class
Exception Occurrence
Raised implicitly by system Raised explicitly by programmer throw Statement throw throw ThrowableObject; ThrowableObject;
Exception Occurrence
class classThrowStatement ThrowStatementextends extendsException Exception { { public static void exp(int ptr) { public static void exp(int ptr) { if if(ptr (ptr== ==0) 0) throw thrownew newNullPointerException(); NullPointerException(); } } public publicstatic staticvoid voidmain(String[] main(String[]args) args){ { int i = 0; int i = 0; ThrowStatement.exp(i); ThrowStatement.exp(i); } } } }
Exception Occurrence
throws Statement
When programmer-defined exception is raised, if there is no exception handler, need to describe it in the declaration part of method
[modifiers] [modifiers] returntype returntype methodName(params) methodName(params) throws throwse1, e1,... ...,ek ,ek{ {} }
Exception Handling
try-catch-finally Statement Check and Handle the Exception
try try{{
// // }}catch catch(ExceptionType1 (ExceptionType1 identifier) identifier){{ // // }}catch catch(ExceptionType2 (ExceptionType2identifier) identifier){{ // // }}finally finally {{ // // }}
Exception Handling
Default Exception Handler When system-defined exception occurred, if programmer does not deal with it, it would be processed by default exception handler Simple function to output error message and exit Execution Order of Exception Handler Finally clause is executed independent of exception and catch
Exception Propagation
public public class class Propagate Propagate{{ void void orange() orange(){{ ArithmeticException ArithmeticExceptionOccurred Occurred int m = 25, i = 0; int m = 25, i = 0; ii= =m m//i; i; }} void void apple() apple(){{ orange(); orange(); }} public publicstatic staticvoid voidmain(String[] main(String[]args) args){{ Propagate Propagatepp= =new newPropagate(); Propagate(); p.apple(); Output p.apple(); Outputby byDefault DefaultException Exception }} Handler Handler }}
java.lang.ArithmeticException: //by java.lang.ArithmeticException: byzero zero at atPropagate.orange(Propagate.java:4) Propagate.orange(Propagate.java:4) at atPropagate.apple(Propagate.java:8) Propagate.apple(Propagate.java:8) at atPropagate.main(Propagate.java:11) Propagate.main(Propagate.java:11)
Exception Propagation
Explicit Description for possibility of Exception Occurrence
System-Defined Exception
Do not need to announce the possibility of exception occurrence
Programmer-Defined Exception
When it is not managed in correspond method, the exception type should be informed. Use the throws clause
Exception Propagation
class class MyException MyExceptionextends extendsException Exception{{}} public publicclass classClassA ClassA{{ // // public publicvoid voidmethodA() methodA()throws throwsMyException MyException{{ // // if if(someErrCondition()) (someErrCondition()) throw thrownew newMyException(); MyException(); // // }} }}
body end
A Multithreaded Program
Main Thread
start
start
start
Thread A
Thread B
Thread C
Java Threads
Java has built in thread support for Multithreading Synchronization Thread Scheduling Inter-Thread Communication:
currentThread yield sleep resume start run stop setPriority getPriority suspend
Threading Mechanisms...
Create a class that extends the Thread class Create a class that implements the Runnable interface
An example
class MyThread extends Thread { // the thread public void run() { System.out.println(" this thread is running ... "); } } // end class MyThread class ThreadEx1 { // a program that utilizes the thread public static void main(String [] args ) { MyThread t = new MyThread(); // due to extending the Thread class (above) // I can call start(), and this will call // run(). start() is a method in class Thread. t.start(); } // end main() } // end class ThreadEx1
142
An example
class MyThread implements Runnable { public void run() { System.out.println(" this thread is running ... "); } } // end class MyThread class ThreadEx2 { public static void main(String [] args ) { Thread t = new Thread(new MyThread()); // due to implementing the Runnable interface // I can call start(), and this will call run(). t.start(); } // end main() } // end class ThreadEx2
144
runnable
stop() notify() slept resume() unblocked
non-runnable
dead
145
class C extends Thread { public void run() { for(int k=1;k<=5;k++) { System.out.println("\t From ThreadC: k= "+k); } System.out.println("Exit from C"); } }
class ThreadTest { public static void main(String args[]) { new A().start(); new B().start(); new C().start(); } }
Run 1
[C:\jdk1.3\bin] threads [1:76] java ThreadTest From ThreadA: i= 1 From ThreadA: i= 2 From ThreadA: i= 3 From ThreadA: i= 4 From ThreadA: i= 5 Exit from A From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5 Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5 Exit from B
Run2
[C:\jdk1.3\bin] threads [1:77] java ThreadTest From ThreadA: i= 1 From ThreadA: i= 2 From ThreadA: i= 3 From ThreadA: i= 4 From ThreadA: i= 5 From ThreadC: k= 1 From ThreadC: k= 2 From ThreadC: k= 3 From ThreadC: k= 4 From ThreadC: k= 5 Exit from C From ThreadB: j= 1 From ThreadB: j= 2 From ThreadB: j= 3 From ThreadB: j= 4 From ThreadB: j= 5 Exit from B Exit from A
Shared Resources
If one thread tries to read the data and other thread tries to update the same date, it leads to inconsistent state. This can be prevented by synchronising access to data. In Java: Synchronized method:
syncronised void update() {
accoun t
152
Thread Priority
In Java, each thread is assigned priority, which affects the order in which it is scheduled for running. The threads so far had same default priority (ORM_PRIORITY) and they are served using FCFS policy.
Java allows users to change priority:
ThreadName.setPriority(intNumber)
MIN_PRIORITY = 1 NORM_PRIORITY=5 MAX_PRIORITY=10
Strings
Java provides a class definition for a type called String Since the String class is part of the java.lang package, no special imports are required to use it (like a header file in C). Just like regular datatypes (and like C), variables of type String are declared as: String s1; String s2, s3; //etc. Note that String is uppercase. This is the Java convention for classnames.
Strings
Initializing a String is painless
s1 = This is some java String;
Note that double quotes are required. Memory is allocated dynamically. Think of above method as shortcut for more standard way (assuming s1 has been declared): s1 = new String(This is some java String); new operator required to create memory for new String object.
String methods
Given a String object we can then access any public String method or instance variable (field). Best to think of analogy with C. Given a variable of some struct type, we can access any of the structs members. If one of these members is a pointer to a function, we can essentially call a function using the struct. (x.doit(x,)) In Java, this idea is taken quite a bit further, but the above analogy is a good start.
String Examples
Best to see by way of example:
String s = new String(Hello); Char c = s.charAt(3); System.out.println(c);
Method charAt called on String object s taking single integer parameter. How might this look in a procedural language with structures? (homework)
Streams
Stream: an object that either delivers data to its destination (screen, file, etc.) or that takes data from a source (keyboard, file, etc.) it acts as a buffer between the data source and destination Input stream: a stream that provides input to a program System.in is an input stream Output stream: a stream that accepts output from a program System.out is an output stream A stream connects a program to an I/O object System.out connects a program to the screen System.in connects a program to the keyboard
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
How to do I/O
import java.io.*; Open the stream Use the stream (read, write, or both) Close the stream
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
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
The fileName specifies where the (external) file is to be found You never use fileName again; instead, you use fileReader
Using a stream
Some streams can be used only for input, others only for output, still 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
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)
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);
Reading lines
String s; s = bufferedReader.readLine( ); A BufferedReader will return null if there is nothing more to read
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!
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
My LineReader class
class LineReader { BufferedReader bufferedReader; LineReader(String fileName) {...} String readLine( ) {...} void close( ) {...} }
readLine
String readLine( ) { try { return bufferedReader.readLine( ); } catch(IOException e) { e.printStackTrace( ); } return null; }
close
void close() { try { bufferedReader.close( ); } catch(IOException e) { } }
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)
writeLine
void writeLine(String line) { printWriter.println(line); }
close
void close( ) { printWriter.flush( ); try { printWriter.close( ); } catch(Exception e) { } }
Serialization
You can also read and write objects to files Object I/O goes by the awkward name of serialization Serialization in other languages can be very difficult, because objects may contain references to other objects Java makes serialization (almost) easy
ObjectOutputStream objectOut = new ObjectOutputStream( new BufferedOutputStream( new FileOutputStream(fileName))); objectOut.writeObject(serializableObject); objectOut.close( );
ObjectInputStream objectIn = new ObjectInputStream( new BufferedInputStream( new FileInputStream(fileName))); myObject = (itsType)objectIn.readObject( ); objectIn.close( );