Programming in Java

Books 1. Java 2 - The Complete Reference, Herbert Schildt (Seventh Edition). 2. The Java Programming Language, Ken Arnold, James Gosling & David Holmes (Third Edition). 3. Core Java Volume I ± Fundamentals, Eigth Edition, C S Horstmann & G. Cornell 4. Java.sun.com/docs/books/tutorial, javaworld.com -------------------------------------------------------------------------------------------------------

JAVA Just Another Vague Acronym Initially called Oak Originally designed by James Gosling

Research language vs. production language

A language is called research language if it has untested features (i.e. features that had not been tested in its predecessor languages) A language is called production language if it does not have any untested features.

Java is not a research language. It is a production language C and C++ are examples of research languages.

Advantages of Java over C++
(i) (ii) (iii) Java syntax is similar to C++. Java is more object-oriented than C++. It is easier to write bug-free code in Java than in C++.

e.g. If you write the code while (someIdentifier = 1) { //do some thing } in C++, you will be caught in an infinite loop. But in Java this code will flagged be as compile time error. ‡ ‡ ‡ ‡ You will find bound checking of arrays. There is no manual memory allocation and deallocation No pointer arithmetic and pointer syntax. There are no multiple inheritances.

Because of all these reasons, it is easier to write bug free code and this reduces the program development time. (iv) Java is architecture-neutral. Even if you upgrade the operating system and hardware, the Java program written in the older operating system and previous hardware will continue to run. This scenario is known as `Write Once Run Everywhere`.

Uses of Java

‡ ‡ ‡

Write application for establishing communication between client and server, Develop embedded systems, In new devices and applications.

Differences between Java and C++
1) C++ features not supported by Java Operator overloading, multiple inheritance, header files, structures and unions, typedef, virtual base class, default argument, goto, delete, destructor, automatic type conversion that results in loss of precession, otherwise automatic type conversion is permitted, primitive type can be passed by value only, object can be passed only by reference,. 2) Features of Java not found in C++ Multithreading, packages, interfaces, Application Programming Interface (API) classes, enhanced `break` and `continue`, characters are unsigned 16 bits, unsigned right shift (>>>) operator, built-in String class and documentation comments (/** some comments */). 3) Features that are shared between C++ and Java boolean variables, access specifiers and support for exception handling.

Java Buzzwords

Java is described by the by the following buzzwords.

Simple ± Java has eliminated many rarely used, poorly understood and confusing features of C++. It is easy to achieve fluency in Java. Object-oriented ± It is more object-oriented than C++. Architecture-neutral ± Java program written for a specific operating system and hardware can run in other operating system and hardware. This is necessary because Java codes are downloaded from the Internet to run on a variety of CPU and operating system. Portable ± All primitive types take the same amount of storage on all architectures. Robust ± Java provides early error checking facility and so it is easy to develop bug-free code.

Java Buzzwords

Multithreaded ± Java has API classes that support multithreading. Network-savvy ± Java has support for TCP/IP protocols and remote method invocation (RMI). Session management ± There are API classes for session management and cookies. High performance ± In C++, you include files (header files e.g.) for using built-in functions and after compilation, these functions find their place in the compiled code even if a few of them only are actually used in the source code. This is not so with Java. Consequently, the size of the java compiled code is small and so the space requirement and time of execution is low and hence the performance is high. Interpreted ± Java compiler converts the Java source code into bytecodes and these are interpreted by the Java interpreter also known as the Java Virtual Machine (JVM). The JVM differs from architecture to architecture. Dynamic ± A Java program written using API classes need not be recompiled when the API classes are modified and/or upgraded.

Coding Style

Java developers follow coding style in writing the name of an identifier depending upon what it stands for.

The classes and interfaces are named using words in title case (e.g. Employee, String, Thread, Runnable). If a class name need to consist of more than a single word then each word is written in title case and words are concatenated without using underscore (e.g. FinanceDepartment). The method and variable names are written in lower case. If you need more than a single word to construct such a name then the first word is written in title case and the rest of the words are written in lower case and the words are concatenated (dailyTemperature). The name of the constants are written in uppercase and if such a name need more than one word then the words are joined using underscore (e.g. GRAVITATIONAL_CONSTANT).

signed and 32 bits). long (for long integers. ‡ The true and false are known as boolean literals ‡ Can be assigned to boolean variables only ‡ Can be used in expressions with boolean operators. . signed and 16 bits). int (for integer. float (for floating point numbers. signed and 64 bits). ‡ The true and false are not converted into numeric representation. short (for short integer. double (for floating point numbers. signed and 32 bits). signed and 64 bits). byte (for signed 8 bit integer) boolean having only two possible values true and false (unlike zero and non-zero) and it requires no storage.Basic (primitive) data types char (unsigned and 16 bits).

+= (increment and assignment). í (subtraction). /= (division and assignment).Arithmetic operators + (addition). -= (decrement and assignment).(unit decrement). % (modulo operation can be applied on integers as well as floating point numbers). *=(multiplication and assignment). %= (modulo and assignment) and -. * (multiplication). Arithmetic operators can be applied only on numeric types and character type not on boolean type . / (division). ++(unit increment).

| (bitwise or). Operators ~ (negation). .B. ~= (bitwise not followed by assignment. >> (right shift). int. char and byte types only. >>> (unsigned right shift). >>>= (bitwise unsigned right shift followed by assignment) and <<= (bitwise left shift followed by assignment) N. ^ (exclusive or). & (bitwise and). << (left shift). short. Java uses 2`s complement form to store negative numbers.Bitwise operators Perform bit operations on its operands and can be applied on long. &= (bitwise and followed by assignment). >>= (bitwise right shift followed by assignment). ^= (bitwise exclusive or followed by assignment).

. In short circuit or if the first expression is true than the second expression will not be evaluated. >= (greater than or equal to). != (not equal to) and ?: ( conditional operator) N. ^= (exclusive or followed by assignment). < (less than). ^ (exclusive or). && (short circuit and). ! (not). == (equality). || (short circuit or). !=( not equal to). | (or).B. >(greater than) Boolean logical operators (can be applied only on Boolean type) & (and).Relational & Boolean logical operators Relational operators == (for testing equality of numbers or characters or object references returned by an expression). In short circuit and if the first expression is false then the second expression will not be evaluated. <= (less than or equal to).

Operator precedence () ++ * + >> == & ^ | && || ?: = operator= [] -/ >>> != ~ % ! << .

Type casting The type casting is performed using the syntax (type) identifier.Code example involving >>> int a = -1. (111111«1) (Java uses 2`s complement form to store negative number) a = a>>> 24 (0«011111111 = 255). .

Automatic type conversion The automatic type conversion takes place in such a way that data widening is permitted but shortening is not. char byte short int long (data widening) float double Inversion of the arrows will lead to compile time error . The conversion is performed in such a way that precision of data is not lost.

--------------------------------------------------------------------------------------------------------int a = «. int m = «. x = y. //this is okay -------------------------------------------------------------------------------------------------------int a = «.data shortening n = (short) m. .//this is okay ± data widening -------------------------------------------------------------------------------------------------------float x = «. double y = 2. byte b = «. short n = m.798762. // compile time error. byte b = «. b = a. //this is okay. The result is a%256 when a is outside the range of byte. //compile time error ± data shortening y = x.Examples on type conversion rules and type casting. b = (byte)a. The result is m%512 when m is outside the range of short integer m = n. //compile time error.

Rules for automatic type promotion in arithmetic expression ‡ The bytes and shorts are promoted to integers ‡ If one of the operands is float or double or long then the other(s) is (are) promoted to float or double or long and stored in float or double or long.g. e. Any mismatch between the type of formal and actual parameter(s) In function call is flagged as compile time error. .Automatic type promotion Java is a strongly typed language. Any type mismatch is flagged as compile time error.

Used to separate package name from sub package and to separate a variable or a method from a reference variable. surrounding cast types Braces { } Used to contain the values of automatically initialized arrays and to define a block of code Square brackets [ ] Used to declare array types and also for dereferencing array values Semicolon . method.g. interface. numeric literals e. ob. false.g. ob.g. boolean logical operators) ‡ . string literals ³java´) Comments (// single line.2. 45. /** */ documentation comment) Separators Parentheses ( ) Used to contain a list of parameters in method definition & invocation. variable. bitwise operators. 1. Used to separates consecutive identifiers in variable declarations and to chain statements together inside for loop Period . character literals e. relational operators. containing expressions in control statements.m) Operators (Arithmetic operators.pkg2. µj¶. defining operator precedence. Used to terminate a statement Comma .f(). constant) Literals (true.Lexical elements (Building blocks of Java source code) ‡ ‡ ‡ ‡ ‡ White spaces Identifiers (name of a class. /* */ multi-line.(e. pkg1.

private. else. byte. protected ± special kind of modifiers known as access specifiers class ± to declare a class. double. static. while. continue. int. case. long. do. default.Lexical elements (Building blocks of Java source code) ‡ Keywords char. throw. short. if. finally. final ± modifiers public. throws ± used in exception handling abstract. interface ± to declare an interface extends ± to inherit a class implements ± to convert an interface into a class new ± for creating object. this ± refers to the current object super ± refers to the super class . void ± to declare basic type or no type for. boolean. catch. switch. return ± used to form control statements try. float. break.

g if (obj instanceof X) native ± refers to code written in native programming languages namely. assert ± used to ensure whether the value of a boolean expression is true. Used as modifier in method declaration. E. C.g. .Lexical elements (Building blocks of Java source code) Keywords synchronized ± used in multithreaded programs package ± for declaring package (an umbrella) import ± to make package members available to a source file transient ± used in the context of serialization volatile ± used to maintain data consistency instanceof ± used to test whether an object is an instance of a specific class e. C++. private native void method( ).g. e. assert expression.

x and chrs are actually references. The elements of String arrays are initialized by null.  The identifiers m. . The array elements are initialized by blank space. The elements of boolean arrays are initialized by false.Arrays 1-D Array type[ ] arrayname = new type[size]. type arrayname [ ] = new type[size].0f. The array is created and all elements are initialized by zero.g. char [ ] chrs = new char[20]. float [ ] x = new float[10]. e.  A reference is similar to a pointer except that it can`t point to an arbitrary memory location and you can`t apply arithmetic on references. The array is created and all elements are initialized by 0. int [ ] m = new int[10].

e. the memory is allocated for the array and all the elements of the array are initialized by their default values. only a reference is declared and it points to nothing (null). The array is created i. and arrayname = new type[size]. arrayname = new type[size]. is equivalent to type[ ] arrayname. type[ ] arrayname. Array is not created.1-D Arrays type[ ] arrayname = new type[size]. . type[ ] arrayname = new type[size].

³ class-based´. ³ concurrent´. valn}. ‡ The index starts with zero. ³ objected-oriented´. type [ ] arrayname = { val1. ³ general-purpose´. . ‡ You may initialize an array at the point of declaration. µv¶. .g. String [ ] strs = {³Java´. ‡ To access an array element use arrayname[index]. e. ³ is´. ³ a´. µa¶. µa¶}. val2.. ³ language´}. char [ ] chrs = {µj¶..1-D Array ‡ Every array name is a reference.

length. ‡ You can use arrayName. Java provides bound checking of arrays. or an index out of the bound of the array.length to access the length of the array Example code: int sum(int[ ] a) { int result = 0. i++) result += a[i]. for(int i =0. } .1-D Arrays ‡ You can`t have negative index. return result. i < a.

2D arrays type[ ] [ ] arrayname = new type[size1][size2]. . i++) arrayname[i] = new type[size2]. for (i = 0. i<size1. You may not mention the second dimension type[ ] [ ] arrayname = new type[size1][ ]. Intialization at the point of declaration: type[ ] [ ] arrayname = { { }. { } }.

Arrays 
Java arrays, even of basic types, are objects. (Array names are references)  Java arrays are created dynamically on the heap.  The array index may have type short, int, byte, char, but it cannot be long, float, double or boolean  Once an array is created its length cannot be altered

Control statements

while, do-while, for, for-each version of for loop, if-else, switch-case-default, break, continue, labeled break; labeled continue, return

for-each version of for loop
for (type iteration-var : array-name ) { statements }
Example code segment: int sum(int[ ] a) { int result = 0; for(int i : a) result += i; return result; } Using conventional for loop:

int sum(int[ ] a) { int result = 0; for(int i =0; i < a.length; i++) result += a[i]; return result; }

Labeled break A label is an identifier followed by a : (colon) e.g. there: Syntax: break label; e.g. break there;

Code example: first: for(,,,) { //label is defined and can be referred to //inside this block //code if( condition) break first; // label is used //code }

Labeled break
Nested labeled break Code Example:

first: for (,,,) { //outer most loop //code second: for (,,,) { //inner loop //code if( condition) break first; //code third: for (,,,) { //inner most loop //code if( condition) break second; else break third; }//end of inner most loop }//end of inner loop }//end of outer loop

Labeled break
The following code will not compile. first: for (,,,) {//outer loop //code second: for (,,,) { //code if( condition) break third; //code third: for (,,,) { //code if( condition) break second; else break third; }//end of inner most loop }//end of inner loop }//end of outer loop You cannot break to a label which is not defined for the enclosing block.

Labeled continue

Syntax:

continue label;

Code example: first: for(,,,) { //label is defined and can be referred to //inside this block //code if( condition) continue first; // label is used //code }

Labeled break
Nested labeled continue Code Example:

first: for (int i=0; i<m; i++) {//outer loop //code second: for (int j=0; j<n; j++) {//inner loop //code if( condition) continue first; //control transferred to i++ //code third: for (int k=0; k<p; k++) {//inner most loop //code if( condition) continue second; //control transferred to j++ else continue third; //control transferred to k++ }//end of inner most loop }//end of inner loop }//end of outer loop

.Labeled continue The following code will not compile.) {//outer loop //code second: for (. .) {//inner loop //code if( condition) continue third..) {//inner most loop //code if( condition) continue second... //code third: for (. }//end of inner most loop }//end of inner loop }//end of outer loop You cannot continue to a label which is not defined for the enclosing block. else continue third.. first: for (..

Pascal`s triangle).g. If you want to output ragged arrays (e. use labeled break. use labeled continue. .Usage of labeled break & labeled continue When you want the program control to come out of a deeply nested loop.

Classes A class is a reference type. Partial syntax for class declaration: [modifier] class ClassName { //field declarations //static initialization block //initialization block //constructor definition //method definition //class declarations //interface declarations } .

‡ Static fields are called class fields because they belong to the class and do not belong to the object.Classes ‡ Fields can be static or non-static. ‡ The class fields receive their share of memory when the class file is loaded and instance fields receive their share of memory when an object is created. but a class field is shared by all the objects of a class. ‡ Every Java source file is converted into a class file (.class file) by the Java compiler . ‡ There exists only one (the original) copy of a class field. Each object of a class has a copy of each of its instance field. ‡ The non-static fields are called instance fields.

a default public constructor will be synthesized by the compiler. ‡ If you do not provide any constructor. ‡ The type and number of arguments of the function are considered for overload resolution. Return type is not used for overload resolution . but default arguments are not permitted. ‡ Overload resolution (which of the overloaded function is to be called) takes place at the time of compilation. ‡ ‡ Constructors cannot be declared static. Methods can be overloaded.Classes ‡ Constructors can be overloaded (default / parameterized). ‡ Automatic type promotion takes place at the time of overload resolution.

g. set ( ) method) ‡ A method that only reads the state of an object is called an accessor method (e. ‡ While passing arguments to a method. ‡ A static method can access only static fields. .Classes ‡ Methods can be static or non-static. ‡ An object is an instance of a class. ‡ A method that changes the state of an object is called a mutator method (e. ‡ The state of an object is determined by the value of its instance fields.g. get ( ) method). the basic types are passed by values and objects are passed by references. call only other static methods and does not have `this` reference.

class.Keyword final ‡ `final` is used as a modifier of a field. final double PI = «.g. e. method. //a final field final void method(«) { //a final method body of the method } final class SomeClass { //a final class body of the class } .

e. ‡ final fields are often declared static and public e. .14. use the modifier final. public static final double PI = 3.g.g.Keyword final ‡ If a field is declared final then its value cannot be changed. Blank finals are not permitted. ‡ If a field is declared as final then it must be initialized at the point of declaration.14. final double PI. final double PI = 3. //compile time error ‡ So if you want to treat a field as a constant.

‡ If a class is declared final then it cannot be extended (inherited). ‡ If a field is declared final then its value cannot be altered. .Keyword final ‡ If a method is declared final then it cannot be overridden.

0f. . short.  float type receives 0.  object references receive null value. long.  boolean type receives false.0.  char type receives blank space.  double type receives 0.  int.Classes ‡ Every field of a class except the final fields receives a default value at the point of declaration. byte receives a value 0.

«.Local variables ‡ Variables declared inside a method or inside a block of code e.g. . // x is local to this block « }//ends ‡ A block of code is defined by a pair of braces. ‡ Though field of class (if it is not final) has default value but local variables do not have default values and they must be initialized at the point of declaration. // flag is local to the method int m = 10. void method(«) { boolean flag = true.67. } {//block of code starts double x = 4.

e.The `this` reference ‡ The `this` reference refers to the current object (invoking object i. n. (the period operator). } } . this.e.member Example code class X { int m. int n) { this. object currently in use).n = n. ‡ Members of `this` are accessed by . this. i. X(int m.m = m.

??? What operators are not found in Java but found in C++??? :: -> What is the most unfortunate construct of programming languages?? .

The `this` reference ‡ The `this` reference can also be used to call another constructor of the same class. } X(int m. // must be the first non-comment statement in this definition.m = m. n. X(int m) { this. } } . int n) { this(m). Example code: class X { int m. this.n = n.

x4 points to the same object as x3 points to. If you test the return value of x3 == x4 you will get true because the object pointed to by x3 and x4 are the same. X x3 = new X(10.Object creation X x1 = new X ( ). No new object has been created. All objects are created on the heap at the run time. Object not yet created. X x4. There is no compile time object .20). X x2 = new X(4). only a reference has been declared x4 = x3.

if necessary) the equals method.Objects equality ‡ The state of an object is defined by the value of its instance fields. originally defined in the Object class . ‡ The state of objects can be compared using (overriding. ‡ Two objects are said to be equal if they have the same state.

Inside a class: class X { //other code X makeACopy( X x) { this.makeACopy(x).m = x. . return this. e.g. this.n.20).Object cloning Making an exact copy of an object is called object cloning.n = x.m. X x1 = x. } } X x = new X(10. ‡ x == x1 returns false because x and x1 points to object with the same state but different location.

x2 is now a copy of x1. e. X (X ob) { m = ob.Object cloning You may also use constructor for object cloning.g. 10).m. . n = ob. } X x1 = new X(5. X x2 = new X(x1).n.

.main method  The main method has the following form public static void main(String[ ] args)  The main method of a Java program must be declared public and static.  Its return type is void and its argument is an array of strings.  The main method is declared static because it starts its execution before any object comes into existence  It is public because it is to be accessed from outside the class it is defined in.

print      System (built-in class) is a class out is an object of PrintStream (built-in class) class print and println are methods defined inside the PrintStream class.Sending output to the standard output device (display screen) Use System. print and println methods can take any argument except of type void.println or System.out.out. The built-in classes will be referred to as the API (Application Programming Interface) classes. . print and println convert their arguments into string before sending them to the console (display screen).

out. System.println(³Computing powered by Java´). } //main } // HelloWorld The name of the source file must be HelloWorld.out.java. System. double x = 27. .print("The value of x is " + x).println(³Welcome to the world of Computing´).Your first Java program class HelloWorld { public static void main(String[ ] args) { System.out.

Your first Java program  To compile this code use javac command.java or javac Helloworld. javac HelloWorld.java.  A class file is created by the java compiler. you need to type java HelloWorld at the command line. HelloWorld.  To execute the program. .class  The name of the class file is exactly the same as the name of class in the source code (no change of case).java  You could also type javac helloworld.

} Box (double l. double h) { this(l.17).println(b1. this.out. b = 10. this.out. b). b. h = 10.h. } }//BoxTest . h. System. double b. return this. System.l. Box b2 = new Box(b1).} Box (double l) { this. double b) { this.out. //calling the other constructor Box(double l.b = b.volume( )).println(b1 == b2). h = ob. System. this.equals(b2)). } Box modifyObject( ) { //a mutator method this.l = l.14. Box ( ) { l =10. else return false. } double volume ( ) { return l*b*h.h++. Box b3 = b2.b.Another program class Box { double l. b = ob.l = l. double b) this. } boolean equals(Box ob) { // tests equality of two objects if( l == ob.b && h == ob.println(b1.l++. } Box (double l. } Box (Box ob) { //object cloning l = ob.l && b == ob. } }//Box class class BoxTest { public static void main(String[ ] args) { Box b1 = new Box (12.h) return true.h = h.b++.

Box. You can`t use java Box because this class does not have the main method If you incorporate a main method inside the Box class you can execute it using the command java Box.Some observations After compilation of this code two class files are created by the java compiler. To execute the program. . you need to type java BoxTest at the command line.class.class & BoxTest.

.Comments How many main methods you may have in a Java source file?  You may have one main method in each of the classes that the source file has.  This is useful for unit testing (Developing and testing each class separately).  The argument of java command must be the name of the class which you want the execution to start from.

println(args[i]). i<args.Processing command line arguments Code Example class CommandLine { public static void main(String[ ] args) { for(int i=0.out.length. } } . i++) System.

but in Java everything & everything must be inside a class.Remarks  In C++ you may have variables and methods outside class. . but you can`t write a Java program without using classes.  You may write a C++ program without using classes.

i<5. for(int i=0.30.50). i++) barray[i] = new Box( ). for(int i=5.Creating an array of objects class BoxTest1 { public static void main(String[ ] args) { Box [ ] barray = new Box[10] . i++) barray[i] = new Box(10. i<10. } } Exercise: Create a 2D array of objects of the Box class .

. each time an object is created.Initialization block An initialization block is a block of statements that appears within a class declaration. ‡ The initialization blocks are executed in order of text. ‡ You may use `this` reference. ‡ This is used for complex initialization. outside of any member or constructor declaration and which initialize instance fields. ‡ The initialization block gets executed. you may use `super` inside initialization block but you cannot use return statement.

{ } } // this is an initialization block id = nextId++.Code example class Employee { int id. . static int nextId = 1000.

‡ Block is executed when the class file is loaded. . super and return. e. } A static initialization block ‡ Can only refer to static members of the class ‡ Cannot have this reference. static { //code.Static initialization block A static initialization block is an initialization block declared as static.g.

println(³run´). } } .out.Will this program run? class X { static { System.

out. This error message can be overcome if you use System.Answer Program will compile. i. class X { static { System.exit(0).exit(0). it displays the string ³run´ and will terminate with an error message saying that `main is not found`. System.e. When you try to execute it.println(³run´). } } .

. static int nextId. static { // this is a static IB nextId = (int) (Math.random( )*1000). } { } } // this is an IB id = nextId++.Code example using initialization block & static initialization block class Employee { int id.

} // code to define the nextPrime() method } Exercise: Complete this program . i<10. static { knownPrimes[0] = 2.Generating prime numbers at the load time class Primes { static int [ ] knownPrimes = new int[10]. i++) knownPrime[i] = nextPrime( ). for(int i=1.

Abstract class An incomplete class is called an abstract class. Incomplete class A class is called incomplete if its specification either has not been implemented completely or implementation is unknown. Concrete class A class that is complete is called a concrete class.Some definitions Top-level class & Nested class A class is called a top-level class if it is not declared inside any other class or interface. otherwise it is called a nested class. .

use the modifier `abstract`. abstract class X { //code } .g.Abstract classes To declare a class abstract. e.

‡ It is not possible to create an object of an abstract class but you can declare a reference. ‡ An abstract class cannot be declared final. ‡ A class which is not declared abstract cannot have abstract methods. ‡ If you do not declare a class abstract then you must give the definition of all of its methods. .Abstract classes ‡ Any class may be declared abstract and a class must be declared abstract if one of its methods is abstract. This does not make the methods inline.

e. ‡ To declare a method abstract use the modifier abstract. abstract rtype methodName (arglist ). ‡ An abstract method cannot be declared static . ‡ An abstract method cannot be declared final. ‡ A method with a body cannot be declared abstract.Abstract methods ‡ A method is called abstract if it does not have a body.g. abstract boolean f(X x).

Partial syntax: interface InterfaceName { //field declarations //method declarations //classes //interfaces } . An interface is a pure specification.Interfaces An interface is a reference type that does not describe how it is implemented.

I.14.m.Interfaces  The fields of an interface are implicitly public. Example of an interface interface I { int m = 10.  The nested classes and interfaces are public.x. double x = 3. } To access the members of I use I. . static and final.  The methods are public and abstract.

Serializable is a marker interface  You cannot instantiate an interface. but you can write I x.g. e.g. Since an interface is a pure specification so it is often necessary to give an implementation of the interface. e.Interfaces  An empty interface is called a marker interface and it acts like a flag. To implement an interface use the clause implements . however you can declare a reference. You cannot write I x = new I( ).

I2.Interfaces A partial syntax for implementing an interface: class ClassName implements I1 [.I3. I2 { //definition of the methods of I1 & I2 } .«] { body of the class } A class can implement any number of interfaces ----------------------------------------------------------------------------------------------A class implementing a single interface I class X implements I { //definition of the methods of I } A class implementing two interfaces I1 & I2 class Y implements I1.

An example of an Interface & its implementation
interface Shape { double area( ); } class Triangle implements Shape { double d1, d2,d3; Triangle( ) { } Triangle (double d1, double d2, double d3) { this.d1 = d1; this.d2 = d2; this.d3 = d3; } public double area ( ) { return Math.sqrt(«) : } }

Interfaces
Any number of classes can implement an interface. You could write class Rectangle implements Shape { double d1, d2; Rectangle( ) { } Rectangle (double d1, double d2) { this.d1 = d1; this.d2 = d2; } public double area ( ) { return d1*d2; } }

Interfaces
A class that implements an interface may have its own methods. e.g.

class Rectangle implements Shape { double d1, d2; Rectangle( ) { } Rectangle (double d1, double d2) { this.d1 = d1; this.d2 = d2; } public double area ( ) { return d1*d2; } double perimeter( ) { return d1*d2; } }

Interface reference can receive class object but converse is not true
class ShapeTest { public static void main(String[ ] args) { Shape sh; //declare a reference of Shape. But cannot create object Triangle ob = new Triangle(3,4,5); Rectangle ob1 = new Rectangle (10,20); sh = ob; //interface reference can receive object System.out.println(sh.area( ));//calls area()@Triangle sh = ob1; System.out.print(sh.area( )); //calls area()@Rectangle //but objects cannot receive interface reference ob = sh; //compile time error ob1 = sh; //compile time error ob = (Triangle)sh; ob1 = (Rectangle)sh; } }

Interfaces
If you do not define a method of an interface then the class implementing the interface must be declared abstract. e.g. abstract class Rectangle1 implements Shape { double d1, d2; Rectangle( ) { } Rectangle (double d1, double d2) { this.d1 = d1; this.d2 = d2; } }

An interface with data only
interface DataOnly { int YES = 1; int NO = 0; double DONT_KNOW = 0.5; } class Test { public static void main(String[ ] args) { System.out.println(DataOnly.YES); } } class X implements DataOnly public static void main(String[ ] args) { System.out.println(YES); System.out.println(DataOnly.YES); //this is also correct } }

Top-level & nested interface
‡ An interface is called a top-level interface if it is not declared inside any other interface/class. ‡ Any interface declared inside any other interface/class is called a nested interface.

Extending classes (Inheritance)
To inherit a class use the clause extends ‡ A class can extend one and only one class (i.e. multiple inheritance is not permitted), ‡ Any number of classes can extend a class. A partial syntax for extending a class: class SubClass extends SuperClass { body of the class } ‡ All inheritances are public inheritance. ‡ A sub class cannot access the private members of its super class.

member ‡ `super` is available only to the non-static members of a class . inside constructor of the subclass. ‡ To call super class constructor use super(arglist).Keyword `super` `super` is used ‡ to the call the constructor of super class ‡ to access super class members (methods and fields). ‡ This must be the first non-comment statement in the constructor definition ‡ To call members of the super class use super.

//code } } . BoxColor( ) { } BoxColor( double l.An example class BoxColor extends Box { int c. //commenting this statement will call the // default constructor of the super class this.Using `super` .w.c = c. int c) { super( l. double w.h).area( ). double h. } double area ( ) { //code super.

f( ).m = 10. n.Data hiding & method overriding class X { int m. //accessing m of the super class super. //data hiding .these fields hide the m and n @X void f( ) { //overriding f( )@X //body of the method } void h( ) { //code super. calling f( )@X } }//Y . void f( ) { //body of the method } void g( ) { //body of the method } }//X class Y extends X { int m.n.

//compile time error .Super class reference can receive subclass objects but converse is not true X x.subclass reference cannot receive super //class object y = (Y)x. x = y. // Super class reference can receive subclass objects y = x. Y y = new Y( ). //type casting is possible .

double d3) { this. this.d1 = d1. double d2.d2 = d2.d3 = d3. Triangle( ) { } Triangle (double d1. } double area ( ) { return Math.d3. this. d2. } class Triangle extends Shape { double d1.sqrt(«) : } } .Dynamic method dispatch abstract class Shape { abstract double area( ).

double d2) { this.Dynamic method dispatch (contd. } } .) class Rectangle extends Shape { double d1. Rectangle( ) { } Rectangle (double d1. this.d1 = d1.d2 = d2. } double area ( ) { return d1*d2. d2.

println(sh. no compile time error here. because they are independent classes. //you cannot create object of Shape Triangle ob = new Triangle(3.20). --compile time error ob1 = (Rectangle)sh.//This is okay because sh now holds Rectangle ob = (Triangle)sh. Rectangle sh cannot be cast into Triangle.out.5).) class ShapeTest { public static void main(String[ ] args) { Shape sh. sh = ob. //super class reference receives sub class object System.println(sh. but runtime error(exception) occurs.4.area( )). The name of this exception is ClassCastException . Rectangle ob1 = new Rectangle (10.//area()@Rectangle //ob = sh.area( )).out. --compile time error //ob1 = sh. //area()@Triangle sh = ob1.Dynamic method dispatch (contd. /*sh is now holding the type Rectangle. */ } } . System.

22.Announcement JAVA QUIZ I Scheduled on Jan. 2010 (This FRIDAY) PORTIONS Up to Dynamic method dispatch .

Object class
‡ The Object class is at the root of class hierarchy. ‡ Every class is an extension of the Object class and inherits the methods of the Object class. Constructor public Object( )

Object class
Methods public boolean equals (Object ob) Assuming that x, y, z are not null the equals function is ‡ reflexive i.e. x.equals(x) always returns true, ‡ symmetric i.e. x.equals(y) and y.equals(x) always have the same value ‡ transitive i.e. if x.equals(y) and y.equals(z) have the same value then x.equals(z) has the same value as that of x.equals(y) and y.equals(z). To test whether two objects have the same state, override this method.

Object class
public String toString( ) Converts the current (invoking) object into its String representation. The print and println methods call the toString( ) method to convert its argument into string before sending it to the console. e.g. class X /* class X extends Object */ { public String toString( ) { return ³Inside toString method´; } } class Y { public static void main(String[ ] args) { X x = new X( ); System.out.println(x) //output: Inside toString method } }
Exercise :Do not override tooString. Create an object of Object class and pass it to println method

Exercise
Do not override toString. Create an object of Object class and pass it to println method

Object class
public final Class getClass( ) It returns the class the current object belongs to. The Class class is an API class. The following code establishes that every array name is an object. class ArrayTest { public static void main(String[ ] args) { int [ ] m = new int[10]; System.out.println(m.getClass( )); //op: class [I } }

Exercise:Try with arrays of other type

Object class
protected Object clone( ) throws ClassNotSupportedException. It makes an exact copy of an object. protected void finalize( ). This method is called just before the garbage collector is called. Garbage collector is a piece of software that reclaims the memory occupied by objects that are no longer in use. public final void public final void public final void public final void public final void wait ( ) throws InterruptedException wait (long ms ) throws InterruptedException wait ( long ms, int ns) throws InterruptedException notify ( ) notifyAll( )

public int hashcode( ). Computes the hash code from current object Object class has only declared methods and it has no inherited methods because it is not inherited from any other class and so it is called the cosmic super class.

extends & implements
‡ A class that extends another class can also implement interface. ‡ extends clause appears before the implements clause.

e.g. class Y extends X implements I1[,I2,I3,«] { body of the class }

Extending interfaces
Interfaces can be extended. e.g. interface I extends I1 { body of the interface }

‡ Multiple inheritance is NOT possible. ‡ The interfaces are organized in a tree structure and there is no fixed root in this tree. [The class hierarchy has a fixed root (Object class)] ‡ The interface hierarchy is different from the class hierarchy

} interface I2 extends I1{ float h(Object ob). double g(double d).Extending interfaces (example) interface I1 { int f(int n). } class X implements I2 { public int f(int n) { } public double g(double d) { } public float h(Object ob) { } } .

} . double g(double d). compile time error int f(int n).Extending interfaces interface I1 { int f(int n). compile time error double g(double d). //void g(double d). } interface I3 extends I1 { // void f(int n).

C { //try to implement f( ) and g( ) //error because signature of f () and g() are the same but return type //is different in both the interfaces } .Extending interfaces interface A { int f( ). } class X implements A. String g ( ). void g( ). } interface C { void f( ).

} interface D extends A { int f ( ). //overriding String g ( ).Extending interfaces interface A { int f( ). String g ( ). //overriding } .

String g ( ). //overriding } class X implements D { public int f( ) { return 0.Extending interfaces interface A { int f( ). //overriding String g (). } } Will it compile?? YES . } interface D extends A { int f ().} public String g() { return "" .

14. } . } interface I2 extends I1 { double SPEED_OF_LIGHT = 3e10.Inheriting constants interface I1 { double PI = 3.

This value of m hides the value m = 1 int n = 20 + A.m. // accessing m@A } .Inheriting and hiding constants interface A { int m = 1.14. } interface B extends A { int m = 10. //m@B. double x = 3.

‡ For each class declared in the source code a class file is created. ‡ For each interface declared in the source code a class file is created. .Number of class files ‡ Is equal to the number of interfaces and classes present in the source code.

 TEST DURATION: 15 MINUTES  MAXIMUM MARKS: 10  WRITE YOU REGISTRATION NUMBER ON THE QUESTION PAPER AS SOON AS YOU RECEIVE IT. .  ENCIRCLE THE CORRECT ANSWER(S).  DO NOT ANSWER QUESTIONS UNTIL YOU ARE ASKED TO.  DO NOT OVERWRITE ANYWHERE ON THE PAPER.  A QUESTION MAY HAVE MULTIPLE CORRECT ANSWERS.PROGRAMMING IN JAVA QUIZ I  ANSWER ALL QUESTIONS.

deep nesting is possible) but nesting up to level two is recommended.e. . ‡ You may have any number of levels of nesting (i.Nested classes ‡ A class declared inside any other class/interface is called a nested class. use the modifier static ‡ A nested class can extend some other class and can itself be extended. ‡ A nested class can be declared static or non-static ‡ To declare a static nested class.

X is the enclosing (outer) class of Y and Z //code [static] class Y { // a nested class .Nested classes class X { //A top level class .is the enclosing (outer) class of Z //code [static] class Z { //a nested class //code }// Z //code }//Y //code }//X .

X$Y. ‡ A nested class can be static or non-static. ‡ JVM is not aware of the nesting of the classes.class and X$Y$Z.class files are created.Nested classes ‡ After compilation X.class. .

‡ Inner classes cannot have static members. ‡ An inner class is a member of its enclosing class and so it can be declared public.Inner classes ‡ A non-static nested class is called an inner class. including the private members. ‡ From the code of inner class it is possible to access directly (without using object of the outer class) members of outer class. private or protected. ‡ From the code of outer class direct access to the members of the inner class is not possible. . but it is possible to do so using an object of the inner class. They cannot have final fields.

d = d. this.m = m.out. } } After compilation the class files created are X. } void show( ) { // a method of Y System. double d.class and X$Y. Y(int mm. X(int m. //show( ). this. //direct access of m@X display( ).4). error ± outer class cannot directly access members of inner class Y y = new Y(10. y.show( ).dd = dd. double dd) { this.println(m).mm = mm. 10. } class Y { //an inner class int mm. double dd.println(mm).out.class . double d) { this.Inner class (an example) class X { //an outer class int m. } }//Y void display( ) { // a method of X //System.

inside a loop. inside method body. . Features  A local inner class  is a non-static nested class. private or protected. inside initialization block.  The only class modifier that can be used with a local inner class is final. provided the parameters and local variables are final.  is completely inaccessible outside the block it is declared.g.  can access parameters and local variables of the method/block inside which it is declared.  A local inner class  can directly access members of its enclosing class.Local inner class Definition An inner class declared inside a block of code (e. inside constructor) is called a local inner class.  is not a member of the enclosing class and so it cannot be declared public.

out.5.error x is not final } }// local inner class Y ends here return 0. x are declared final then they can be accessed from within Y. -.class .println(m). show( ).n. the class files that are created are X. double x = 4.class & X$1Y. //you can directly access members of X // System.out. }//f }//X   If d. void show() { } int f(double d) { int n = 6. After compilation.println(x).Local inner class (an example) class X { //code int m = 10. class Y { //a local inner class //body of Y void display() { System.

. Feature Since it does not have a name so it cannot have a constructor.  The AICs are extensively used in event handling.Anonymous inner class Definition An Anonymous Inner class (AIC) is an inner class that does not have a name. Usage  If you want to create object of a class only once during an execution of a program then use AIC.

//other code of Y }//Y The class files created after compilation of this code are X.class & Y$2.d = d.class. X x = new X( ) { //AIC starts here //code of AIC }/*AIC ends here*/. X x = new X( 10. double d) { this.8) { //AIC starts here //code of AIC }/*AIC ends here*/. 9. } X( ) { } } class Y { //X x = new X( ).n = n.class. Y$1. this.Anonymous inner class (an example) class X { X(int n. Y.class. .

If there are too many statements.e. i.e. is related to X by inheritance. . at the most six statements are recommended). is a subclass of X. mentioned in the above example.Anonymous inner class  The AIC. readability becomes a problem.  X is a super class of the AIC  An AIC can access arguments of the super class constructor if they are final.  The numbers of lines of code within an AIC should not be too many (i.

the AIC is an extension of the Object class.Anonymous Inner class (another example) class A { Object ob = new Object( ) { //AIC starts //body of AIC }/* AIC ends here */ . . //other code } In this example.

class. The AIC declared here implements the interface I. .Anonymous inner class You may also use an interface to declare an AIC. }//Y The class files created after compilation are I. Y.g.class & Y$1. interface I { } class Y { I i = new I( ) { //AIC starts here //code of AIC }/*AIC ends here*/.class. e.

.Syntax for declaration of AIC SuperType identifier = new SuperType( ) { //code of AIC }.  If the super type is a class then the AIC extends the class.  The super type may be either a class or an interface.  If the super type is an interface then the AIC implements the interface.

final/abstract & strictfp Modifier of local inner class final Modifiers of AIC None .Class Modifiers of inner class Modifiers of inner class public/private/protected.

the floating-point arithmetic behaves the same when the application program is moved to a different platform. but the floating point arithmetic may produce different results on different platform. strictfp guarantees common behavior across platforms in the results of floating point arithmetic i.Modifier strictfp Though Java is platform independent.e. .

. final/abstract and strictfp.Modifiers of top-level class  The only modifiers that can be used for a top level class are public.  The class modifiers can be used in any order but the above order is recommended.

abstract & strictfp.Modifiers of top-level interface  The modifiers that can be used for a top-level interface are public. .  They can be used in any order but the mentioned order is recommended.

makes an exact copy of str. ‡ Strings are immutable (constant). char [ ] value = {µJ¶. Constructors ‡ public String ( ) -. µv¶. are instances of this class.g. Comparable. µa¶}. . CharSequence ‡ The String class represents character strings. ‡ public String(char[ ] value) -. String str = new String(value). ‡ public String(String str) -. µa¶.creates an empty string.constructs a new String from a character array e.String class public final class String extends Object implements Serializable. All string literals in Java programs. such as ³Java Language".

The length of the new String is a function of the charset. and hence may not be equal to the length of the byte array. int offset. The length of the new String is a function of the charset. picking up count number of characters from the position offset of the array value.String class Constructors ‡ public String(char[ ] value. int length. int count) Constructs a new String that contains characters. and hence may not be equal to the length of the subarray. public String(byte[ ] bytes. int offset. String charsetName) throws UnsupportedEncodingException Constructs a new String by decoding the specified subarray of bytes using the specified charset. ‡ public String(byte[ ] bytes) Constructs a new String by decoding the specified array of bytes using the platform's default charset. ‡ .

g. 4. 69. String str = new String(bytes. UTF-32 UTF (Unicode Transformation Format) e. 70}. UTF-8.e. 0. i. System.println(str + " " + str. how the characters are mapped into integers and visa-versa.length( )). "ASCII"). Some of the character sets (character encoding schemes) are ASCII.Character sets A character set (charset) is a character encoding scheme. byte [ ] bytes = {67. //output: ABCD 4 . UTF-16.out. 68. UTF-7.

The decoding scheme uses platform's default charset. and hence may not be equal to the length of the subarray. The length of the new String is a function of the charset. int length) Constructs a new String by decoding the byte array from the position offset.String class ‡ public String(byte[ ] bytes. picking up exactly length number of bytes. . int offset. ‡ public String(StringBuffer buffer) Constructs a new string that contains the sequence of characters currently contained in the string buffer argument.

An index ranges from 0 to length() . the last character to be copied is at the index srcEnd-1 (thus the total number of characters to be copied is srcEnd . ‡ . The first character to be copied is at the index srcBegin.String class Methods ‡ public int length() Returns the length of this string. int srcEnd.srcBegin). int dstBegin) Copies characters from this string into the character array dst.1. char[ ] dst. ‡ public char charAt(int index) Returns the character at the specified index. public void getChars(int srcBegin. The length is equal to the number of 16-bit Unicode characters in the string.

storing the result into a new byte array. ‡ public boolean equals(Object ob) Compares this string to the specified object.String class ‡ public byte[ ] getBytes( ) Encodes this String into a sequence of bytes using the platform's default charset. . storing the result into a new byte array. ‡ public byte[ ] getBytes(String charsetName) throws UnsupportedEncodingException Encodes this String into a sequence of bytes using the named charset.

ignoring case considerations. ‡ public boolean equalsIgnoreCase(String anotherString) Compares this String to another String. .String class ‡ public boolean contentEquals(StringBuffer sb) Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer.

‡ public int lastIndexOf(int ch) Returns the position of the last occurrence of the character ch in this string. e.g.indexOf(µa¶) returns 1.String class ‡ public int indexOf(char ch) returns the position of the first occurrence of the character ch in this string object. . If there is no such character then -1 is returned. String str = ³java language´. str.

String class ‡ public int indexOf(char ch. ‡ public int lastIndexOf(int ch. . int fromIndex) returns for position of the last occurrence of the character ch starting from the position fromIndex. int fromIndex) returns for position of the first occurrence of the character ch starting from the position fromIndex.

str1. e. String str1 = ³java language and java virtual machine´.g.String class ‡ public int indexOf(String str) returns the position of the first occurrence of the substring str in the current string. .indexOf(³java´) returns 0. ‡ public int lastIndexOf(String str) returns the position of the last occurrence of the substring str in the current string.

str1. int fromIndex) returns the position of the last occurrence of the substring str in the current string starting from the position fromIndex. e.g. int fromIndex) returns the position of the first occurrence of the substring str in the current string starting from the position fromIndex. ‡ public int lastIndexOf(String str. .indexOf(³java´.String class ‡ public int indexOf(String str. 1) returns 18.

compareTo(³Programming´). o/p ±ve int Compares two strings lexicographically. if this string object follows the argument string then +ve value is returned. ³Programming´.String class ‡ public int compareTo(String anotherString) e. . The comparison is based on the Unicode value of each character in the strings.compareTo(³Java´). ‡ public int compareToIgnoreCase(String str) Similar to compareTo method except that case is ignored.g. If this string object precedes the argument string then ±ve value is returned. if they are equal then 0 is returned. o/p +ve int ³Java´.

int endIndex) e.g. The substring begins at the specified beginIndex and extends to the character at index endIndex . Thus the length of the substring is endIndex-beginIndex. .substring(2.g.substring(2) returns "happy³ Returns a new string that is a substring of this string.String class ‡ public String substring(int beginIndex) e. 7) returns "happy³ Returns a new string that is a substring of this string. "unhappy". "unhappy".1. The substring begins with the character at the specified index and extends to the end of this string. ‡ public String substring(int beginIndex.

³Java´. If the oldChar is not found then this string is returned. String replacement) Replaces the first substring of this string that matches the given string str by the given replacement.g.¶e¶). char newChar) e. Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. returns Java language. .concat(³ language´).g. ‡ public String replace(char oldChar.String class ‡ public String concat(String str) Concatenates the specified string to the end of this string.replace(µa¶. ‡ public String replaceFirst(String str. ³Java´. e.

The default locale of windows is English(US) ‡ public String toUpperCase() . String replacement) Replaces each substring of this string that matches the given str with the given replacement. ‡ public String toLowerCase() Converts all of the characters in this String to lower case using the platform`s default locale.String class ‡ public String replaceAll(String str.

³MAC´). e. String country). String variant). The constructors of this class are Locale (String language) Locale (String language. country and any special variant (e. the name of the OS). Locale(³english´. Locale(³english´. You will find Locale class in Java.Locale In computing. .g. Locale(³english´).g. Locale (String language. String country. ³Singapore´). ³Singapore´. locale is defined by the user`s language.

String class ‡ public String toLowerCase(Locale locale) Converts all of the characters in this String to lower case using the rules of the given Locale. ‡ public String toUpperCase(Locale locale) .

‡ public String toString( ) Returns this object .String class ‡ public String trim() Returns a copy of the string. with leading and trailing whitespace omitted.

the starting offset of the subregion in the string argument. String other. len . "java language". toffset . int toffset. int len) Tests if two string regions are equal. int len) .g.the string argument.regionMatches(0. e. "java".the starting offset of the subregion in this string.the number of characters to compare.String class ‡ public char[ ] toCharArray( ) Converts this string to a new character array. int ooffset. String other. ‡ public boolean regionMatches(int toffset. 0. ‡ public boolean regionMatches(boolean ignoreCase. int ooffset. other . 4) returns true. ooffset .

String class  public String[ ] split(String str) Splits this string around matches of the given string str. for(int i=0.split(³ ³).. String [ ] strs = ³Programming in Java´. e. The hash code for a String object is computed as s[0]*31^(n-1) + s[1]*31^(n-2) + .length.i++) System.out. n is the length of the string.g. .. i<strs.println(strs[i]). and ^ indicates exponentiation. + s[n-1] using int arithmetic. where s[i] is the ith character of the string.  public int hashCode( ) Returns a hash code for this string.

startsWith(³Java´). int toffset) Tests if this string starts with the specified prefix beginning a specified index. .g. ³Java language´. o/p: true ‡ public boolean endsWith(String suffix) Tests if this string ends with the specified suffix.String class ‡ public boolean startsWith(String prefix) Tests if this string starts with the specified prefix. e. ‡ public boolean startsWith(String prefix.

String class ‡ public static String valueOf(Object obj) Returns the string representation of the Object argument. int offset. ‡ public static String valueOf(char[ ] data) ‡ public static String valueOf(char[ ] data. int count) ‡ public static String valueOf(boolean b) .

g. e.String class ‡ public static String valueOf(char c) Returns the string representation of the char argument.valueOf(µa¶). String. ‡ public static String valueOf(int i) ‡ public static String valueOf(long l) ‡ public static String valueOf(float f) ‡ public static String valueOf(double d) .

Exercise Write a program to demonstrate the functionality of the constructors and the methods of the String class. .

Portions for CAT I Up to String class .

StringBuffer class public final class StringBuffer extends Object implements Serializable. CharSequence  The objects of StringBuffer class are mutable.  Capacity of a SB object is defined by the maximum number of characters that it can accommodate.  Length of a SB object is defined as the number of characters in the buffer. Constructors  public StringBuffer( ) Constructs a string buffer with no characters in it and an initial capacity of 16 characters. .

If the capacity argument is less than 0.StringBuffer class  public StringBuffer(int capacity) Constructs a string buffer with no characters in it and an initial capacity specified by the capacity argument.  public StringBuffer(String str) Constructs a string buffer so that it represents the same sequence of characters as the string argument. NegativeArraySizeException is thrown. NullPointerException is thrown . If you pass null as argument. The initial capacity of the string buffer is length of the string argument + 16.

If the current capacity > minimumCapacity. . If the current capacity of this string buffer is less than the argument.StringBuffer class Methods ‡ public int length( ) Returns the length (character count) of this string buffer. then a new internal buffer is allocated with greater capacity. Ensures that the capacity of the buffer is at least equal to the specified minimum. ‡ public void ensureCapacity(int minimumCapacity) Explicitly allocating rooms. New capacity = max(minimumCapacity. method returns. 2*oldCapacity + 2). ‡ public int capacity( ) Returns the current capacity of the String buffer.

capacity( )).print(sb.//capacity = 16 sb.ensureCapacity(20). System. 2*16 + 2). .StringBuffer class StringBuffer sb = new StringBuffer( ).out. //output capacity = max(20.

‡ public char charAt(int index) Returns the character at the location index of this StringBuffer object. If the newLength is less than the current length then excess characters are truncated. If the index is negative then IndexOutOfBoundsException is thrown. If the newLength is negative then IndexOutOfBoundsException is thrown. otherwise new rooms are filled with null. .StringBuffer class ‡ public void setLength(int newLength) Sets the length of this String buffer.

char ch) Replaces the character at the location index by the character ch. ‡ public StringBuffer append(Object obj) Appends the string representation of the Object argument to this string buffer. . char[ ] dst. int srcEnd. int dstBegin) Similar to the getChars method of String class.StringBuffer class ‡ public void getChars(int srcBegin. ‡ public void setCharAt(int index.

int len) Appends the string representation of a subarray of the char array argument to this string buffer. int offset.StringBuffer class ‡ public StringBuffer append(String str) Appends the string to this string buffer. ‡ public StringBuffer append(StringBuffer sb) Appends the specified StringBuffer to this StringBuffer. ‡ public StringBuffer append(char[ ] chrs) Appends the string representation of the char array argument to this string buffer. ‡ public StringBuffer append(char[ ] chrs. The subarray starts at offset and has len characters .

StringBuffer class ‡ public StringBuffer append(boolean b) Appends the string representation of the boolean argument to the string buffer. ‡ ‡ ‡ ‡ ‡ public StringBuffer append(char c) public StringBuffer append(int i) public StringBuffer append(long l) public StringBuffer append(float f) public StringBuffer append(double d) .

The substring begins at the specified start and extends to the character at index end ± 1. . int end) Removes the characters in a substring of this StringBuffer. String str) Replaces the characters in a substring of this StringBuffer with characters in the specified String. public StringBuffer deleteCharAt(int index) Removes the character at the specified position in this StringBuffer.StringBuffer class ‡ public StringBuffer delete(int start. ‡ ‡ public StringBuffer replace(int start. int end. The substring begins at the specified start and extends to the character at index end ± 1.

‡ public String substring(int start. . int end) Similar to the substring method of String class.StringBuffer class ‡ public String substring(int start) Similar to the substring method of String class.

‡ public StringBuffer insert(int where. The subarray begins at the specified offset and extends len characters. Object obj) Inserts the string representation of the Object argument into this string buffer. char[ ] chrs. String str) Inserts the string into this string buffer.StringBuffer class ‡ public StringBuffer insert(int where. ‡ public StringBuffer insert(int where. . int len) Inserts the string representation of a subarray of the chrs array argument into this string buffer. int offset.

char c) public StringBuffer insert(int where. double d) . boolean b) public StringBuffer insert(int where. int i) public StringBuffer insert(int where.StringBuffer class ‡ public StringBuffer insert(int where. long l) public StringBuffer insert(int where. ‡ ‡ ‡ ‡ ‡ ‡ public StringBuffer insert(int where. float f) public StringBuffer insert(int where. char[ ] chrs) Inserts the string representation of the char array argument into this string buffer.

int fromIndex) public int lastIndexOf(String str) public int lastIndexOf(String str. . int fromIndex) Similar to the String class methods.StringBuffer class ‡ ‡ ‡ ‡ public int indexOf(String str) public int indexOf(String str.

‡ public String toString( ) Converts to a string representing the data in this string buffer. .StringBuffer class ‡ public StringBuffer reverse( ) The character sequence contained in this string buffer is replaced by the reverse of the sequence.

. Memory management is more involved in StringBuffer objects than in String objects and so run time overhead for managing StringBuffer objects is higher than String objects.Exercise Develop a program to demonstrate the functionality of the constructors and the methods of the StringBuffer class.

 There is no restriction on the number of classes and interfaces that a compilation unit may have. You may have other classes and interfaces in the same compilation unit.package  A source file is called a compilation unit or translation unit. but they cannot be declared public.  A compilation unit may have at the most one top-level public class or interface. . These other classes and interfaces present in the compilation unit act as helper classes and interfaces.

g. video). . audio. other packages and resource files (e. interfaces.  Members Classes. image.package  Definition of package A package is a software unit that can be distributed independently and be combined with other packages to form application.

To develop a named package. e.pkg2.  A package without a name is called a default package.  A package statement consists of the keyword package followed by a package name terminated by a semi colon. use package statement inside the source file. .package  There is no restriction on the number of members that a package may have. package pkg1. A package name is an identifier.g. This package may have a name. A package is a container that can expand automatically to accommodate as many members as it is required. it may not have name. package pkg1.  Every compilation unit (Java source file) belongs to a package.

 The package statement is optional. the compilation unit belongs to an unnamed package. then it must be the first non-comment statement of the source file.  In absence of package statement. if present. called default package.package  The significance of the package statement is that the classes and interfaces declared inside the source file are members of the package. But. .

 The classes and interfaces declared inside a package can talk to each other. . even if they are declared inside a different compilation unit.package  You may have at the most one package statement in a compilation unit.  Any number of compilation units may belong to a single package.  The classes and interfaces declared inside a package can talk to only public classes and interfaces declared in other packages each other.

g. e:\java\08mca\pkg1 e.java  This source code needs to be stored inside a subdirectory \pkg1 under some directory. . public class Example { } //other classes and interfaces  Suppose the name of this Java source file (compilation unit) is Example.  Note that the name of the sub directory is the same as the name of the package.Developing package (example) package pkg1.  The sub directory \pkg1 can be under any directory.

Developing package  The directory under which the sub directory \pkg1 is created is called a base directory/development directory.  So Example.java go to the sub directory e:\java\08mca\pkg1 & type javac Example.g.java . e:\java\08mca is a base directory. e.java is stored inside e:\java\08mca\pkg1\  To compile Example.  A base directory can be any directory.

Example  If you want to develop a package with name pkg1.java  To execute the class file you need to go to the base directory (i.pkg2 then you need to create a subdirectory \pkg1\pkg2 under some base directory & store the source file the subdirectory «\pkg1\pkg2 .Developing package  You may also compile this file from some other directory specifying the full path e:\java\08mca\pkg1\Example. e:\java\08mca) and type java pkg1.e.

java. . Example1.Including more classes and interfaces into a package  Any number of compilation units may belong to a package. as the first non-comment statement of the file and store it inside the sub directory «\pkg1 and compile.  In this way you may add more classes and interfaces to the package pkg1.  At present the only source file which is inside the package pkg1 is Example.java with the package statement package pkg1.  How to add more classes and interfaces to the package pkg1?  Create another Java source file say.

 Any directory can be a base directory.  In order that members of different packages can talk to each other.  The collection of all base directories is called class path.  You may have any number of base directories in your file system.Base directory & class path  Definition of base directory A base directory is any directory whose sub directory may contain Java class files. you must tell the run time environment where the class files are stored. .

. add the following line to the .Base directory & class path  Telling the run time environment where the class files are stored.  On UNIX/Linux. is referred to as setting the classpath.  If you use BASH shell.  How to set classpath?  Setting the classpath depends on the environment you are working in. add the following line to the .  if you use C shell.cshrc file: setenv CLASSPATH name of base dirs separated by .bashrc file or in the bash-profile file: export CLASSPATH = name of base dirs separated by .

 A frame appears.  Type the name of the base directories separated by semi-colons inside the text box labeled variable value.  On windows 95/98. add the following line in the autoexec.bat file set classpath = name of the base directories separated by .  Type classpath inside the text box labeled variable name. .Base directory & class path  On windows environment except win 95/98  Control Panel System Advanced Environment variables New.

pkg2 then pkg2 is a sub package of pkg1  Every .g. the name pkg1. if the name of a package is pkg1. e. package names are written in lower case.g. (dot).package  By convention. in a package name is mapped to a \ in windows and to a / in UNIX/Linux. A sub package name is separated from a package name by . e.pkg2 is mapped to baseDirectory\pkg1\pkg2 .

http  java.  The Java standard library is distributed among a large number of packages and the roots of these packages are java and javax  Some of the standard library packages are java.awt. java.awt is a sub package of the package java.math.awt.package  The packages are organized in the form of hierarchy.lang. java. java.util. javax.swing. .servlet. java. java.event.awt. javax.event is a sub package of the package java.awt.

lang package are String.package  Some of the library classes declared inside the java. GregorianCalendar  The fully qualified name of the String class is java. System.  The fully qualified name of a class is defined by packagename. Math. .String.  The interface Serializable is declared inside the package java.lang.ClassName  Package name is case sensitive. Calendar.util package are Date.lang  Some of the library classes declared inside the java.

Example is different from the class pkg1.g. e.vit may be the root of the all packages being developed at VIT .pkg2.Why package?  To guarantee uniqueness of class and interface name. Sun Microsystems recommends that you use the internet domain name of your organization written in reverse as the root of the packages and then use sub packages for different projects.Example and pkg2.Example.  The class pkg1. in.  To absolutely guarantee the uniqueness of class and interface name.ac.

ClassName. ---import on demand import java. (called import on demand) import packagename.*.Date.single type import The import statement import packagename.*.*. (single type import) import packagename1[.import statement An import statement appears inside a source file. (called import on demand) e.packagename2«]. . --.g. An import statement may have one of the following forms: import packagename. implies that the members of the package named `packagename` are available to this source file.util.awt.*. import java.

*. implies that the members of the package named packagename1.packagename2 are available to this source file. implies that the class ClassName is available to this source file.import statement The import statement import packagename. The import statement import packagename1. .ClassName.  not about actual inclusion of the classes & interfaces (of the package) into the compiled code  Only those members of the package that are actually used in the source file are included into the compile code.packagename2.  The import statement is about availability only.

g. . Z. I1.import statement e.*. Y. X. if a package pkg1 has a number of public classes and interfaces say. and use only the class X inside the source file then the class file of the class X only is included into the compiled code. I2 and if you use the import statement import pkg1.

 A compilation unit may have any number of import statements.  If import statement is present then (in absence of package statement) it must the first non-comment statement of the source code.*. package pkg1. e.import statement  The import statement is optional. import pkg2.g. .

e. but not for the package name. you may use wild card (*) for members of a package. . Because this statement makes an attempt to import all the sub packages of the package java i. But you cannot write import java. you can write import java.import statement  One import statement can make available the members of one package only.*.g.*.e.  A single import statement cannot make members of multiple packages available.*.util.

you find the Date class inside the package java.  Two different packages may contain the same class/interface.*. you can write either java. inside the same source file.import statement  You can import types (classes and interfaces) but you cannot import objects.  But you cannot access the Date class without qualifying it by its package name i.*.util.sql.g. import java.sql.e.  You may use the import statements import java.Date or java.sql.Date . e.util.util and java.

util. import java. import java.sql.sql. .util.import statement Alternatively.Date. OR import java.*. you may use one of the following code segments.*.Date. import java.

import statement  An import statement of the form import pkg1. This is why it is preferable to use import on demand to single type import. is called single type import  Using import on demand is easier than single type import.*.ClassName. is called import on demand  An import statement of the form import pkg1. .  Using import on demand has no effect on the size of the compiled code.

.lang Though you use the System class in the code System.lang because java.println but you need not import java.out.lang is automatically imported into every Java source file.A note The System class is declared in the package java.

 It is possible to completely dispense with import statements (using fully qualified name of the classes and interfaces).  #include incorporates the entire content of the header file into the compiled code.Difference between #include and import  import is about availability of the members of a package.  This is the reason why the size of a Java compiled code is smaller than that of C++ code. Only those classes and interface that are actually referred to in the source code are included into the compiled code. but it is not possible to completely dispense with #include. .

Access protection  Access to a class/interface member is protected by access modifier. protected (modifier used is protected) public (modifier used is public) ± most access .  There are four different levels of access namely. This is the default access). private (modifier used is private) ± least access package (no modifier is used.

.  If it is declared private then it is visible only inside the class (least access).Access protection  If a class member is declared as public then it is visible everywhere (most access).  If it is declared protected then it is visible in the package it is declared and also in the sub class declared in other packages.  If it is declared without any access modifier then it is visible throughout the package.

Access protection (Example) package pkg1. //visible only inside this class protected double d. //visible inside this package & in a sub class in //other package void f( ) {//visible anywhere inside the package pkg1. public class X { // class X is visible everywhere private int m. //no access modifier used //member is said have package scope } protected double g( ) { //visible inside this package & in a sub class in //other package } public double h( ) { //visible everywhere } }//X .

public class Y { //can access public members of X //cannot access protected members of X.*. import pkg1.Access protection (Example) package pkg2. members without modifier // & the private members } class Z extends X { //can access public and protected members of X //cannot access members without modifier & private members of X } .

Class modifier access private No modifier protected public Same class Yes Yes Yes Yes Same package sub class No Yes Yes Yes Same package non-sub class No Yes Yes Yes Different package sub class No No Yes Yes Different package non.sub class No No No Yes .

the class must be declared public. . i. the members of a Java class are visible everywhere inside the package the class is declared.  The members of a Java class are by default not private.e.Access protection  In order that the public and protected members of a class may be accessed in other packages. by default (in absence of any access modifier).  The members of a C++ class are by default private. The default scope is package.

 The class Throwable is at the root of the exception class hierarchy.  Every exception is an object of built-in exception class or userdefined exception class.Exception handling  Exceptions are run-time errors.  The built-in exception classes are organized in hierarchy. .  Every user-defined exception class must be a sub class of a built-in exception class.

Built-in Exception class hierarchy Object Throwable Error Exception IOException RuntimeExeption .

Exception class hierarchy Error LinkageError VirtualMachineError ThreadDeath NoClassDefFoundError -.OutOfMemoryError --StackOverflowError --UnknownError --InternalError .

IllegalThreadStateException ---.ArrayIndexOutOfBoundsException ---.NumberFormatException ---.StringIndexOutOfBoundsException ---.IllegalArgumentException ---.ConcurrentThreadException .Exception class hierarchy RuntimeException ------------- ArithmethicException ( divide by zero) ArrayStoreException (storing object of wrong type) EmptyStackException (a pop was attempted on an empty stack) IndexOutOfBoundsException ---.

FileNotFoundException ---.InterruptedException ---.EOFException .Exception class hierarchy IOException ---.

. Format of try-catch-finally: try { //code to be monitored for exception }catch(ExceptionType1 ob) { // code to be executed when exception occurs (known as exception handler) }catch(ExceptionType2 ob) { // code to be executed when exception occurs (known as exception handler) } . . catch. throw and throws. finally. finally{ //code that must be executed before try block ends } .Exception handling Exception handling is performed using the keywords try.

closing files.g.  The exception types in different catch blocks associated with a try block must be different. releasing locks) even in the face of runtime errors then use finally block & write this code inside finally block. disconnecting from the database. .  If you need to release some resources (e.Exception handling  If there is no catch block then there has to be a finally block  You may have any number of catch blocks (even zero)  In presence of catch block.  If finally block is present then it will be executed even if no exception is thrown. finally is optional.

c.println(³hello there´). System. System.out.Exception handling public class ExceptionTest { public static void main(String[ ] args) { int a=10.ArithmeticException: / by zero at ExceptionTest.main (ExceptionTest.out.lang. b=0.java:5) The string in italic is called stack trace . //will be printed c = a/b.println(³hello´). //will not be printed } } It will compile On execution you will find the following output: hello there Exception in thread ³main´ java.

} } Output: hello there java.ArithmeticException: / by zero hello .println("hello").println(³hello there´).println(e).out.out.out. try { c = a/b.Exception handling If exception is handled then it is possible to recover from error and resume execution. System. c.lang. //exception handler } System. b=0. //code to be monitored for exception }catch(ArithmeticException e) { System. public class ExceptionTest { public static void main(String[ ] args) { int a=10.

println("hello there").lang.out.Exception handling public class ExceptionTest { public static void main(String[ ] args) { int a=10. //printStackTrace is a method of Throwable } System.main (ExceptionTest. c. System.out. b=0. try { c = a/b.println("hello").ArithmeticException: / by zero at ExceptionTest. } } Output: hello there Exception in thread ³main´ java.java:5) hello .printStackTrace( ). }catch(ArithmeticException e) { e.

i++) { b = r. b=0. }//for }//main }//HandleError .Random r = new java.Exception handling It is possible to recover from exception and resume execution±another example public class HandleError { public static void main(String[ ] args) { int a=0. i< 100.util. c=0.util. java. for (int i = 0.nextInt( ).println(³a = ³+ a).Random( ).nextInt( ). c = r. } System. try { a = 10/(b/c).out. }catch(ArithmeticException e) { a = 0.

out. } }//main }//MultiCatch . a = args. }catch(ArrayIndexOutOfBoundsException e) { e. try { b = 10/a.Exception handling Multiple catch blocks and finally block public class MultiCatch { public static void main(String[ ] args) { int a= -10. b=0. }catch(ArithmeticException e) { e. c[5] = 43.length.printStackTrace( ). int [ ] c = {15}.println(³this will always be printed´).printStackTrace( ). }finally { System.

println(³this will always be printed´). b=0.Exception handling public class CatchFinally { public static void main(String[ ] args) { int a= -10. } }//main }// CatchFinally The Exception block can handle ArithmeticException & ArrayIndexOutOfBoundsException. try { b = 10/a.out. a = args. (Super class reference can receive sub class objects) . c[5] = 43.length.printStackTrace( ). }catch(Exception e) { e. because both are sub class of the class Exception. }finally { System. int [ ] c = {15}.

try { b = 10/a. }catch(Exception e) { e. a = args.length. b=0.out. }catch(ArithmeticException e) { e.printStackTrace( ).printStackTrace( ).println(³this will always be printed´).Exception handling public class MultiCatch1 { public static void main(String[ ] args) { int a= -10. }finally { System. c[5] = 43. } }//main }//MultiCatch1 Will it compile? . int [ ] c = {15}.

.Exception handling The above code will not compile. See the next slide. The ArithmeticException and ArrayIndexOutOfBoundsException being a subclass of Exception. In order that the code compiles. all exception objects will be caught at the catch block that handles Exception object and control never reaches the ArithmeticException block leading to unreachable code which is a compile time error. you need to catch ArithmeticException object before catching Exception object. Reason Super class reference can receive sub class object.

}catch(ArithmeticException e) { e.length.println(³this will always be printed´). b=0.printStackTrace( ). a = args. }finally { System.printStackTrace( ).out. } }//main }//MultiCatch2 . int [ ] c = {15}. c[5] = 43. }catch(Exception e) { e.Exception handling public class MultiCatch2 { public static void main(String[ ] args) { int a=0. try { b = 10/a.

try { //outer try block //code try { //inner try block }catch(ExceptionType1 ob) { //exception handler } catch(ExceptionType2 ob) { //exception handler }//inner try ends } catch(ExceptionType3 ob) { //exception handler } catch(ExceptionType4 ob) { //exception handler }//outer try ends Any number of levels of nesting is possible.Exception handling Nested try Try blocks can be nested i. . you may have one try block inside another try block. but is nesting up to level two is recommended.e.

//implicit nested try }catch(Exception e) { //code } }//main }//X .Exception handling The nested try block may be implicit also. class X { static void f( ) { //code try { //code }catch(Exception e) { //exception handler } } public static void main( String [ ] args ) { try { f( ).

 It cannot be an object of arbitrary class.  It cannot be of primitive type.g. e.  It may also be an object of a user-defined exception class.  The expression must return an object of Throwable or any of its sub class. if(condition) throw new ArithmeticException(³Division by zero´ ). . if(condition) throw new NullPointerException( ). The throw statement facilitates throwing an exception forcibly.Exception handling Throw statement The throw statement has the following form: throw expression.

Exception handling public class ThrowTest { public static void main(String[ ] args) { int a=0. }catch(ArithmeticException e) { e.out. b = Integer. } }//main }//ThrowTest . b=0.println((double)a/b). a = Integer.printStackTrace( ). else System.parseInt(args[0]).parseInt(args[1]). try { if (b == 0) throw new ArithmeticException("Do not perform division").

printStackTrace( ).Exception handling Rethrowing an exception class X { static void f ( ) { //code try { //code if(condition) throw new NullPointerException( ). //rethrowing an exception } }//f public static void main(String[ ] args) { try { f ( ). else //do something else }catch(NullPointerException e) { e. }catch(NullPointerException e ) { //exception handler } }//main }//X . throw e.

NullPointerException(String s) Constructs a NullPointerException with the specified detail message. . Constructor NullPointerException() Constructs a NullPointerException with no detail message.  Accessing or modifying the field of a null object.Exception handling NullPointerException Thrown when an application attempts to use null in a case where an object is required. These include:  Calling the instance method of a null object.

Announcement
Quiz II March 8, 2010 (Monday) Portions Nested classes, String class, StringBuffer class, interfaces, packages, exception handling.

Exception handling
throws clause  The throws clause has the following form throws exception_list The exception_list is a list of exceptions separated by comma.  Used with a method declaration. [modifier] rtype methodname(arg-list) throws exception_list  The throws clause is an announcement.

Exception handling
class ThrowsTest { static void f( ) { //code throw new Exception( ); }//f public static void main(String[ ] args) { try { f( ); }catch(Exception e) { e.printStackTrace( ); } System.out.println("hello"); }//main } //ThrowsTest

Exception handling
class ThrowsTest1 { static void f( ) { //code throw new RuntimeException( ); }//f public static void main(String[ ] args) { try { f( ); }catch(RuntimeException e) { e.printStackTrace( ); } System.out.println("hello"); }//main } //ThrowsTest1

Exception handling
class ThrowsTest { static void f( ) { //code try { throw new Exception( ); }catch(Exception e) { e.printStackTrace( ); } } public static void main(String[ ] args) { try { f( ); }catch(Exception e) { e.printStackTrace( ); } System.out.println("hello"); } }

Exception handling
class ThrowsTest { static void f( ) throws Exception { //code throw new Exception( ); } public static void main(String[ ] args) { try { f( ); }catch(Exception e) { e.printStackTrace( ); } System.out.println("hello"); } }

Exception handling 
An exception is called checked exception if the compiler checks to find out whether the exception thrown by the method but not handled is declared.  An exception is called unchecked exception if the compiler does not check to find out whether the exception thrown by the method but not handled is declared.  The exception classes Error and RuntimeException and any of their sub classes are unchecked exceptions.  All other exception classes are checked exception classes

Exception handling
When to use throws clause? If not used in the following case, a compile time error occurs. If a method throws checked exception and the exception is not processed within the body of the method then this exception must be declared in the exception list of the throws clause. e.g. [modifier] rtype f(arglist) throws E1, E2 { //exceptions E1 and E2 are checked exceptions thrown but not //processed inside the body of the method }

class X { static void f( ) { //code throw new IllegalAccessException( ).printStackTrace( ). } public static void main(String[ ] args) { try { f( ).Exception handling The following code will not compile. }catch(IllegalAccessException e) { e. } } } .

} } } . }catch(IllegalAccessException e) { e.printStackTrace( ). } public static void main(String[ ] args) { try { f( ).Exception handling In order to compile the last code successfully make the following change: class X { static void f( ) throws IllegalAccessException { //code throw new IllegalAccessException( ).

. E2 and E3 are said to form a chain of exceptions. A chain of exceptions may have at least two exceptions involved in it.Exception handling Chained exception If one exception is the cause of the other then they are said to form a chain of exceptions. If an exception E1 is the cause of another exception E2 which in turn is the cause of another exception E3 then E1.

Exception handling Throwable class Constructors public Throwable( ) public Throwable(String msg) public Throwable(Throwable cause) public Throwable(String msg. Throwable cause) .

If there is no cause then null is returned. public Throwable initCause(Throwable cause) Associates cause with the current object. the cause of the exception). .e.Exception handling Some Methods public Throwable getCause( ) returns the underlying exception object (i. public void printStackTrace( ) displays the stack trace.

initCause(new ArithmeticException(³this is the cause´).printStackTrace( ).Exception handling Demonstration of chained exception public class ChainedException { public static void main(String[ ] args) { NullPointerException e = new NullPointerException(³You are using null reference´). } }//main }//ChainedException . }catch(NullPointerException e1) { e1.printStackTrace( ).getCause( ). try { throw e. e. e1.

. class MyException extends Throwable { //body of the class }  By convention.Exception handling Creating user-defined exception  Every user-defined exception must be a sub class of built-in exception class e.g.g. class MyException extends Exception { //body of the class }  Since Exception class is a checked exception. hence all userdefined exceptions are checked exceptions. Exception class is extended to develop user-defined exception class e.

} int getTemperature( ) { return temperature. TemperatureException(int t) { temperature = t. } } class TooColdException extends TemperatureException { //code } .Exception handling Example code class TemperatureException extends Exception { int temperature.

 An exception is called synchronous exception if it is thrown while executing instruction of the developers program. the instruction of the JVM also execute concurrently.  An exception is called asynchronous exception if it is thrown while executing instruction of the JVM.Exception handling Synchronous & asynchronous exception  When the instructions of the developer¶s program execute. .

Multithreaded programming A thread is a sub program that can execute independently sharing the same address space as the program. Processing critical section of a thread is cheaper than processing critical section of a process.e. . in an inter leaving fashion). When multiple threads share the same CPU among themselves they are said to execute concurrently (i. Inter-thread communication is cheaper than inter-process communication.

.Multithreaded programming Thread models  Cooperative thread model A running thread relinquishes the CPU. It is under the control of the JVM (and hence under the control of the Java application developer).  Preemptive thread model A running thread is forced to leave the CPU. This model is under the control of the OS.

Multithreaded programming State transition diagram New Ready Suspended Running Terminated .

The definition of the run method describes the work done by the thread.Multithreaded programming To develop a multi threaded program either (i) implement the Runnable interface (ii) use the Thread class or a sub class of the thread class If you implement Runnable interface then you must give the definition of the run( ) method of Runnable interface. . This method has following form public void run( ).

Multithreaded programming Thread class (package java. String name) .lang) public class Thread extends Object implements Runnable Constructors public Thread ( ) public Thread(String name) public Thread(Runnable work) public Thread(Runnable work. String name) public Thread(ThreadGroup group. String name) public Thread(ThreadGroup group. Runnable work. Runnable work) public Thread(ThreadGroup group.

Value 1 public static final int NORM_PRIORITY The default priority that is assigned to a thread. Constants defined inside the Thread class public static final int MIN_PRIORITY The minimum priority that a thread can have. Value 10 . Value 5 public static final int MAX_PRIORITY The maximum priority that a thread can have.Multithreaded programming A thread group is a data structure that controls the behavior of a collection of threads.

. A thread also has a name that can be changed. Priority of a child thread is the same as that of its parent. It is possible to modify the priority of thread.Multithreaded programming Priority of a thread refers to its relative importance with respect to other threads. A thread with higher priority executes more often than a thread with lower priority. Changing the priority and name of a thread is called configuring the thread. If a single thread is in execution then its priority makes no sense.

currentThread( ) public static void yield( ) Causes the currently executing thread object to temporarily pause and allow other threads to execute. . int ns) throws InterruptedException public static boolean interrupted( ) Returns true if the current thread has been suspended.g. e. The thread does not lose ownership of any monitors (locks). public static void sleep (long ms) throws InterruptedException Suspends execution of the currently running thread for ms milliseconds. Thread.Multithreaded programming Static methods public static Thread currentThread( ) returns a reference to the running thread. public static void sleep (long ms.

public final void setName(String name) alters the name of this thread object. . public final String getName( ) returns the name of this thread object. public final void setPriority(int newPriority) changes the priority of this thread object.Multithreaded programming Final methods public final boolean isAlive( ) returns true if this thread has not been terminated. public final int getPriority( ) returns the priority of this thread.

 public final void join(long ms) throws InterruptedException waits for at most ms milliseconds before terminating.g.join( ) then the method that contains this code will not terminate until t terminates.Multithreaded programming Final methods  public final ThreadGroup getThreadGroup( ) Returns the group this thread belongs to. .  public final void join( ) throws InterruptedException Waits for this thread to terminate e. if you use t. t being a thread object.

public boolean isInterrupted( ) returns true if this thread has been interrupted. public void run( ) Thread goes to ready state.Multithreaded programming Methods that are neither final nor static public void start( ) spawns a new thread. public void interrupt( ) interrupts a thread. Start method automatically calls run( ) method. .

e. use one of the following constructors public Thread(Runnable work) public Thread(Runnable work.Multithreaded programming  A thread object is an abstraction of a worker  A Runnable object (i. associate a work with a worker. Runnable work. the class that implements Runnable interface) is an abstraction of a work.e.  If you are implementing Runnable interface to create thread object then wrap the Runnable object inside the Thread class constructor i. String name) public Thread(ThreadGroup group. String name) .  To associate a work with a worker.

println(t2).getName( ) + ³ ³ + t. t.setName(³Main Thread´) .getPriority()).println(t.println(t1).setPriority(9). System. System. Thread t1 = new Thread( ).out.currentThread( ). System. } } .println(t).Multithreaded programming Example code public class ThreadTest { public static void main(String[ ] agrs) { Thread t = Thread. Thread t2 = new Thread( ). System.out.out.out. t.

50) t1.start( ) /* new Thread11("Java". private int delay. }catch(InterruptedException e) { } }//for }//run public static void main(String[ ] args) { Thread11 t1 = new Thread11("Java". Thread11 t2 = new Thread11("Programming".start( ). delay = d. int d) { word = str.start( ). 50).sleep(delay). 50).Multithreaded programming Extending Thread class public class Thread11 extends Thread { private String word.print(word+ " ").) { System. 50). new Thread11(³Programming".out.start( ). public Thread11(String str. t2. . } public void run( ) { for(. try { Thread. */ } } .

Multithreaded programming Using Runnable interface public class Thread12 implements Runnable { private String word. 50)). } public void run( ) { for(. } } .print(word+ ³ ³). private int delay.start( ). 100)).start( ).sleep(delay).) { System. int d) { word = str. . }catch(InterruptedException e) { } }//for }//run public static void main(String[ ] args) { new Thread(new Thread12(³Java´. public Thread12(String str. new Thread(new Thread12(³Programming´. delay = d. try { Thread.out.

t = new Thread(this). new Thread13("Programming".start(). }catch(InterruptedException e) { } } } public static void main(String[ ] agrs) { new Thread13("Java".print(word+ " "). . int d) { word = str.out. public Thread13(String str. t.sleep(delay). } } . } public void run( ) { for(. private int delay. private Thread t. 100). delay = d.Multithreaded programming Dropping Thread object inside constructor and using start method inside constructor public class Thread13 implements Runnable { private String word. 50). try { Thread.) { System.

start(). try { Thread.out.sleep(delay).print(word+ " ").) { System. delay = d. private int delay.Multithreaded programming using start method inside constructor public class Thread13 extends Thread { private String word. } public void run( ) { for(. int d) { word = str. . }catch(InterruptedException e) { } } } . public Thread13(String str.

Multithreaded programming public static void main(String[ ] agrs) { new Thread13("Java". new Thread13("Programming". } } . 100). 50).

new Thread(work).out. private int delay. int d) { word = str.) { System. public Thread14(String str. 100).sleep(delay).println(word+ " ").Multithreaded programming Using Anonymous inner class public class Thread14 { private String word. delay = d. Runnable work = new Runnable( ) { public void run( ) { for(. }//constructor ends public static void main(String[ ] agrs) { new Thread14("Java". 50). }catch(InterruptedException e) { } }//for }//run }. .start( ). new Thread14("Programming". try { Thread. } } .

Multithreaded programming Thread synchronization When multiple threads interfere with each other in executing a code segment then this execution of the code segment is called asynchronous execution and when they do not interfere then it is called synchronous execution. There are two different ways of implementing synchronous execution of code segment  Synchronized method  Synchronized block .

A method is declared synchronized using the modifier synchronized.g. synchronized void drop( ) { /*code whose execution must not be interfered by multiple threads */ } A synchronized method may be declared static. Constructors cannot be synchronized. e. .Multithreaded programming synchronized method use synchronized method and use the code segment to be synchronized inside this method.

X x = new X( ). synchronized(x) { x.g.f( ).Multithreaded programming Use synchronized block A synchronized block is declared as synchronized(expr) { //expr must evaluate to an object reference //code to be synchronized } e. //doing something on the object x one at a time by different //threads } synchronized(this) { //doing something on the current object one at a time by different //threads } .

bank account object) there exists a lock. .g. Before entering into synchronized code a thread requests the OS for the lock. enters into the synchronized code. In order to execute synchronized code on the object. a thread must acquire the lock of the object.Multithreaded programming  Synchronized method and synchronized block are called synchronized codes. and after it returns from the synchronized code it releases the lock. If the lock is available then the thread acquires the lock. A particular bank account is an object.  Synchronized block is also called synchronized statement  Associated with every object (e. If the lock of the object is already held by some other thread then this thread has to wait.g.  e. At a time only one teller (one thread) can alter the balance of the account.

public BankAccount(double d) { balance = d. } } .Multithreaded programming Banking example class BankAccount { private double balance. } public synchronized void getBalance( ) { return balance. } public synchronized void setBalance(double d) { balance = balance + d.

this. public Teller(BankAccount ba.getBalance( )).Multithreaded programming public class Teller implements Runnable { private BankAccount ba.out. private double d.start( ). t1. 3000). try { t1.d = d.ba = ba. double d) { this. }catch(InterruptedException e) { } System. Thread t2 = new Thread (new Teller(ba. Thread t1 = new Thread (new Teller(ba. 2000). } public static void main(String[ ] agrs) { BankAccount ba = new BankAccount(1000).println(ba.start( ). t2.join( ). t2.setBalance(d).join( ). } public void run( ) { ba. // o/p should be 6000 }//main }Teller .

Portions CAT II  Interfaces  StringBuffer class  Package  Access protection  Exception handling  Multithreaded programming (up to thread synchronization) .

e. These methods are useful in establishing communication among threads (called inter-thread communication). . it does not release the lock before going to sleep). inherited by the Thread class. notify and notifyAll method These are the declared methods of the Object class. If a thread goes to wait then it will first release any lock held by it before going to wait state (but it is not so with the sleep method i.  final void wait( ) throws InterruptedException Suspends execution of this thread until some other thread wakes it up invoking notify or notifyAll method.Multithreaded programming wait.

or a specified amount of time has elapsed.Multithreaded programming  final void wait(long ms) throws InterruptedException Causes current thread to wait until either another thread invokes the notify() method or the notifyAll() method for this object. int ns) throws InterruptedException .  final void wait(long ms.

It two threads t1 and t2 were waiting for the object`s lock then only one of them receives the notification and the selection of t1 or t2 is arbitrary and platform dependent.  final void notifyAll( ) All the waiting threads gets notification but only one of them gets the lock and the selection is arbitrary and platform dependent.Multithreaded programming  final void notify( ) It wakes up a single thread that was waiting for this object`s lock to be released. .

 ALL QUESTIONS ARE COMPULSORY.  TEST DURATION: 15 MINUTES  MAXIMUM MARKS: 10 .  DO NOT ANSWER QUESTIONS UNTIL YOU ARE ASKED TO.PROGRAMMING IN JAVA QUIZ II  WRITE YOU REGISTRATION NUMBER ON THE QUESTION PAPER AS SOON AS YOU RECEIVE IT.  DO NOT OVERWRITE ANYWHERE ON THE PAPER.  A QUESTION MAY HAVE MULTIPLE CORRECT ANSWERS.  ENCIRCLE THE CORRECT ANSWER(S).

 For simplicity we assume that the buffer size is one i. the producer has to wait after producing an item until the consumer picks up the item.e. notify and notifyAll methods.Multithreaded programming Inter-thread communication  Can be achieved using wait.  As long as the buffer is full the producer thread cannot produce items (i.  Producer produces items and keep the items in a buffer whereas the consumer picks up the items one at a time from the buffer. it waits indefinitely until the buffer is empty)  The consumer too waits until there is at least one item in the buffer.  Producer-consumer problem is an example of inter-thread communication where producer and consumer are threads. .e.

 How will the producer know that the item has been picked up?  After picking up the item the consumer issues notification using the notify method.  How will the consumer know that the item has been produced?  The producer after producing the item issues notification to the consumer using notify method.Multithreaded programming  The consumer is in indefinite wait until an item is produced. .  After producing the item the producer has to wait until the item is picked up (assuming that the buffer size is one).

Implementation of producer-consumer problem (buffer size = 1) class Data { private int data. notify( ). return data. }catch(InterruptedException e) { } }//while found = false. //this can be an array when the buffer size > 1 private boolean found = false. } . //no item found in the buffer synchronized int pickup( ) { //executed by the consumer thread while(!found) { try { wait( ).

found = true. }catch(InterruptedException e) { } }//while data = m.Implementation of producer-consumer problem (buffer size = 1) synchronized void drop (int m /*item to be dropped*/) { //executed by //the producer thread while(found) { try { wait( ). }//drop }//Data . notify( ).

} }//Producer .Random( ).util. Producer(Data d) { this.drop(r.util.Random r = new java. private java. } public void run( ) { d.d = d.Implementation of producer-consumer problem (buffer size = 1) class Producer implements Runnable { private Data d.nextInt( )).

println(dd.pickup( )). } public void run( ) { System.Implementation of producer-consumer problem (buffer size = 1) class Consumer implements Runnable { private Data dd. } }//Consumer . Consumer (Data dd) { this.dd = dd.out.

Implementation of producer-consumer problem (buffer size = 1) class InterThreadCommunication { public static void main(String [ ] args) { Data dt = new Data( ). } } . new Thread(new Consumer(dt)). new Thread(new Producer(dt)).start( ).start( ).

. If you have two threads And two objects with lock Then you may have deadlock.Deadlock It is difficult to develop a program that can deadlock.

//h( ) @ B } } .sleep(1000).Deadlock Code example class A { synchronized void h( ) { //h( ) @ A //code } synchronized void f(B b) { try { Thread.h( ). }catch(InterruptedException e) { } b.

h( ).Deadlock class B { synchronized void h( ) { //h( ) @ B //code } synchronized void g(A a) { try { Thread.sleep(1000). //h( ) @A } }//B . }catch(InterruptedException e) { } a.

g(a).f(b).start( ). } public static void main(String[ ] args) { new X( ). } public void run( ) { b. } } .Deadlock class X implements Runnable { A a = new A( ). Thread t. a. t. X(){ t = new Thread(this). B b = new B( ).

start( ) and so now it executes a. start calls run method which in turn execute (child thread is executing) b. Since f is a synchronized method. When the main thread was suspended last it had already executed t. since it contains sleep so the child thread t is suspended and CPU is switched to the main thread. 2. 4.f(a). After entering into the method f.Deadlock Trace 1. Thread t (a child thread of the main thread) is created using t = new Thread(this) and started using t. .g(b). Main thread comes into existence and calls X( ) using new X( ). 5.start( ) 3. the lock of b is required and so it is allocated to the child thread t.

8. So the main thread and the child thread are in a deadlock situation. 9.sleep(1000) inside g.Deadlock 6. But the lock of b is already held by the main thread.h ( ). After entering into method g the main thread is suspended again because of Thread. It now requires the lock of b to execute b. Since g is a synchronized method so its execution requires the lock of the object a and so the lock is allocated to the main thread (because it is not held by any other thread). So the CPU is now switched to the child thread t. When CPU is again switched to the main thread it requires the lock of a which is now held by the child thread t. 7. The child thread was suspended last and now gets the CPU. .

a private copy of the field is given to each thread and the threads modify this private copy. e. . If you want to keep the values of the master copy always updated whenever the private copy is updated then use the modifier volatile.Modifier µvolatile` When two or more threads share the same instance field. Apart from these private copies there is also maintained a master copy.g. volatile double x.

it still occupies memory. the garbage collector is used. .Garbage collection Any object that is no longer being referenced by the program is called a dead object (garbage). To reclaim memory occupied by the dead objects. Though there is no reference any more. the other objects are called live objects. To declare an object x as dead you may use the code x = null.

When the GC executes the application program is halted.  The application program and the GC run concurrently.gc( ) ACM Transactions on Programming Languages & Systems .  The garbage collector is called sporadically (irregularly) by the JVM. One of them is called mark-and-sweep (mark the live object and remove the dead object).  There are various algorithms for implementing garbage collection.Garbage collection  A garbage collector is a piece of software that reclaims the memory occupied by dead objects.  An application developer can call the GC using System.

class X { //code protected void finalize( ) { //code that de-allocates non-memory resources super. If you want to release any non-memory resources before the GC is called then override this method.g. } } .finalize method protected void finalize( ) @ Object class This method is called automatically just before the garbage collector is called. e.finalize( ).

Every output stream has a destination and it writes data to the destination . Every input stream has a source and it reads data from the source. When bits are interpreted as bytes the stream is called byte stream.Java I/O Java stream classes perform I/O in Java Stream classes are defined in the package java. An input stream allows a program to read data. When bits are interpreted as characters the stream is called character stream. An output stream allows a program to write data.io A stream is an ordered sequence of data (bits).

the value -1 is returned. the end of the stream is detected. . or an exception is thrown. Methods  public abstract int read( ) throws IOException Reads the next byte of data from this input stream.io) abstract class. If no byte is available because the end of the stream has been reached. The method blocks until input data is available. The value of byte is returned as an integer in the range 0 to 255. Byte oriented input stream class. A subclass must provide an implementation of this method.Stream classes InputStream class (java.

then no bytes are read and 0 is returned. If the length of b is zero. end of file is detected. . If no byte is available because the stream is at the end of the file. otherwise.InputStream class  public int read(byte[ ] b) throws IOException Reads some number of bytes from the input stream and stores them into the buffer array b. or an exception is thrown. The number of bytes actually read is returned as an integer. the value -1 is returned. This method blocks until input data is available. there is an attempt to read at least one byte.

The number of bytes actually read is returned as an integer. otherwise. or an exception is thrown. the value -1 is returned. This method blocks until input data is available. An attempt is made to read as many as len bytes. then no bytes are read and 0 is returned. int off. there is an attempt to read at least one byte. end of file is detected.InputStream class  public int read(byte[ ] b. If len is zero. but a smaller number may be read. int len) throws IOException Reads up to len bytes of data from the input stream into an array of bytes. If no byte is available because the stream is at end of file. .

for a variety of reasons. If n is negative. reaching end of file before n bytes have been skipped is only one possibility. This may result from any of a number of conditions. end up skipping over some smaller number of bytes.InputStream class  public long skip(long n) throws IOException Skips over and discards n bytes of data from this input stream. The skip method may. The actual number of bytes skipped is returned. possibly 0. . no bytes are skipped.

 public void close( ) throws IOException Closes this input stream and releases any system resources associated with the stream.InputStream class  public int available( ) throws IOException Returns the number of bytes still lying in this stream. The close method of InputStream does nothing. .

For this to happen the method markSupported should return true. Marking a closed stream should not have any effect on the stream. .  public void reset( ) throws IOException Repositions this stream to the position at the time the mark method was last called on this input stream.InputStream class  public void mark(int readlimit) Remembers readLimit number of bytes starting from the current position (where you call mark method) and may read these bytes again when reset is called. The mark method of InputStream does nothing.

InputStream class  public boolean markSupported( ) Tests if this input stream supports the mark and reset methods. The markSupported method of InputStream returns false. .

Methods  public abstract void write(int b) throws IOException Writes the specified byte to this output stream.OutputStream class public abstract class OutputStream (java.length bytes from the specified byte array to this output stream. The byte to be written is the eight low-order bits of the argument b.  public void write(byte[ ] b) throws IOException Writes b. .io) Byte-oriented output stream class.

If b is null.  public void flush( ) throws IOException Forces any buffered output bytes to be written out. a NullPointerException is thrown.OutputStream class  public void write(byte[ ] b. . int off. int len) throws IOException Writes len bytes from the specified byte array starting at offset off to this output stream.

There is no print or println method in this class .OutputStream class  public void close( ) throws IOException Closes this output stream and releases any system resources associated with this stream. The close method of OutputStream does nothing. N.B. A closed stream cannot perform output operations and cannot be reopened.

Reader class public abstract class Reader (java. Methods  public int read( ) throws IOException Read a single character and returns it as an integer between 0 to 65535 and returns -1 when there is no character to read.io) Character-oriented input stream. or the end of the stream is reached. an I/O error occurs. This method will block until a character is available. .

an I/O error occurs. The number of characters read is returned as an integer. The number of characters read is returned as an integer. int off. The method will block until some input is available. int len) throws IOException Read characters into a portion of an array.Reader class  public int read(char[ ] cbuf) throws IOException Read characters into an array. If there is nothing to read -1 is returned. or the end of the stream is reached. The method will block until some input is available. . an I/O error occurs. or the end of the stream is reached. If there is nothing to read -1 is returned.  public abstract int read(char[ ] cbuf.

 public boolean markSupported( ) Similar to the markSupported method of InputStream class . or the end of the stream is reached. May end up skipping less than n characters.  public boolean ready( ) throws IOException Tell whether this stream is ready to be read. an I/O error occurs.Reader class  public long skip(long n) throws IOException Skip the next n characters. The method will block until some characters are available.

however. . Closing a previously-closed stream. has no effect. mark( ). further read( ).Reader class  public void mark(int readAheadLimit) throws IOException  public void reset( ) throws IOException  public abstract void close( ) throws IOException Close the stream. or reset( ) invocations will throw an IOException. ready( ). Once a stream has been closed.

.Writer class public abstract class Writer Character-oriented output stream Methods  public void write(int c) throws IOException Write a single character. The character to be written is contained in the 16 low-order bits of the given integer value.  public void write(char[ ] cbuf) throws IOException Write an array of characters. the 16 high-order bits are ignored.

 public void write(String str) throws IOException Write a string. int len) throws IOException Write a portion of an array of characters.Writer class  public abstract void write(char[ ] cbuf. int len) throws IOException Write a portion of a string.Number of characters to write .  public void write(String str. Parameters: str . int off.Offset from which to start writing characters len . off .A String. int off.

 public abstract void close( ) throws IOException Close the stream. further write( ) or flush( ) invocations will cause an IOException to be thrown. Once a stream has been closed. has no effect. Closing a previously-closed stream. forces any buffered output characters to be written out.Writer class  public abstract void flush( ) throws IOException Flush the stream i. flushing it first.e. however. .

System.err e.out.g. use System. out and err in is of type InputSteam out and err are of type PrintStream.Pre-defined streams Inside the System class there are declared public static final stream objects called in. These objects can be accessed using System.print System.println System.err.out System.err when you want send error message.out.print Syste. .in System.println As a matter of convention.err.

err point to standard output device and the default standard output device is the display device.g.Pre-defined streams  System. System.out as well as System.in.in may be used as System.read( )).read( ) reads the next byte available in the stream and reruns an integer between 0 to 255.in. Syste.println(System.out.  System.in points to standard input device and the default standard input device is keyboard. e. .

g. image. use byte stream class. video). . If you want to perform I/O on character data (text based). audio. use character stream class.When to use byte stream class & when to use character stream class If you want to perform I/O on byte data (e.

For top efficiency. System. more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.out. .print(in.InputStreamReader class public class InputStreamReader extends Reader An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and decodes them into characters using a specified charset.readLine( )).in)). To enable the efficient conversion of bytes to characters. For example: BufferedReader in = new BufferedReader(new InputStreamReader(System. consider wrapping an InputStreamReader within a BufferedReader.

String charsetName) throws UnsupportedEncodingException Creates an InputStreamReader that uses the named charset.  public InputStreamReader(InputStream in. .InputStreamReader class Constructors  public InputStreamReader(InputStream in) Creates an InputStreamReader that uses the default charset.

InputStreamReader class Methods  public String getEncoding( ) Returns the name of the character encoding being used by this stream.  public int read( ) throws IOException Reads a single character. int length) throws IOException Reads characters into a portion of an array. .  public int read(char[ ] cbuf. int offset.

An InputStreamReader is ready if its input buffer is not empty.InputStreamReader class  public boolean ready( ) throws IOException Tells whether this stream is ready to be read. or if bytes are available to be read from the underlying byte stream.  public void close( ) throws IOException .

and lines. The default is large enough for most purposes.  public BufferedReader(Reader in.BufferedReader class  public class BufferedReader extends Reader Reads text from a character-input stream. arrays. int sz) Creates a buffering character-input stream that uses an input buffer of the specified size. The buffer size may be specified. . or the default size may be used. buffering characters so as to provide for the efficient reading of characters.

. Overrides read method of Reader class.BufferedReader class  public int read( ) throws IOException Reads a single character. int len) throws IOException Reads characters into a portion of an array.  public int read(char[ ] cbuf. Overrides read method of Reader class. int off.  public String readLine( ) throws IOException Reads a line of text.

BufferedReader class  public long skip(long n) throws IOException  public boolean ready( ) throws IOException  public boolean markSupported( )  public void mark(int readAheadLimit) throws IOException  public void reset( ) throws IOException  public void close( ) throws IOException .

A boolean. Parameters: out . or a newline character or byte ('\n') is written . This stream will not flush automatically.PrintStream class public class PrintStream extends FilterOutputStream Constructor  public PrintStream(OutputStream out) Create a new print stream. if true. boolean autoFlush) Create a new print stream. the output buffer will be flushed whenever a byte array is written. one of the println methods is invoked.  public PrintStream(OutputStream out.The output stream to which values and objects will be printed autoFlush .

PrintStream class  public PrintStream(OutputStream out. String charset) throws FileNotFoundException. one of the println methods is invoked. UnsupportedEncodingException . boolean autoFlush. Parameters: out .A boolean. or a newline character or byte ('\n') is written encoding . the output buffer will be flushed whenever a byte array is written. if true.The output stream to which values and objects will be printed autoFlush . String charset) throws UnsupportedEncodingException Create a new print stream.The name of a supported character encoding  public PrintStream(String fileName) throws FileNotFoundException  public PrintStream(String fileName.

PrintStream class  public PrintStream(File file) throws FileNotFoundException  public PrintStream(File file.  public void close( ) Close the stream.  public void write(int b) Write the specified byte to this stream. . int len)  public void print(boolean b) Print a boolean value. int off.  public void write(byte[ ] buf. UnsupportedEncodingException Methods  public void flush( ) Flush the stream.  public void print(char c) Print a character. String charset) throws FileNotFoundException.

.  public void print(double d) Print a double-precision floating-point number.  public void print(char[ ] s) Print an array of characters.  public void print(String s) Print a string.  public void print(Object obj) Print an object.  public void print(long l) Print a long integer.  public void print(float f) Print a floating-point number.PrintStream class  public void print(int i) Print an integer.

 public void println(String x) Print a String and then terminate the line. . public void println(double x) Print a double and then terminate the line.      public void println(Object x)Print an Object and then terminate the line.PrintStream class  public void println( ) Terminate the current line by writing the line separator string. public void println(char[ ] x) Print an array of characters and then terminate the line.  public void println(int x) Print an integer and then terminate the line.  public void println(boolean x) Print a boolean and then terminate the line.  public void println(char x) Print a character and then terminate the line. public void println(float x) Print a float and then terminate the line. public void println(long x) Print a long and then terminate the line.

args) A convenience method to write a formatted string to this output stream using the specified format string and arguments.PrintStream class  public PrintStream printf(String format. ... Object.  public PrintStream append(char c) Appends the specified character to this output stream.

PrintWriter class public class PrintWriter extends Writer Constructors PrintWriter(File file) PrintWriter(File file. boolean autoFlush) PrintWriter(String fileName) PrintWriter(String fileName. String csn) PrintWriter(OutputStream out) PrintWriter(OutputStream out. printf method and append method . String csn) PrintWriter(Writer out) PrintWriter(Writer out. boolean autoFlush) Methods Overloaded print and println similar to PrintStream class.

int sz) . PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo. Constructor BufferedWriter(Writer out) BufferedWriter(Writer out.BufferedWriter class public class BufferedWriter extends Writer Write text to a character-output stream.out"))).

int off. int off. int len) throws IOException public void write(String s. int len) throws IOException public void newLine() throws IOException Write a line separator. public void flush() throws IOException public void close() throws IOException .BufferedWriter class public void write(int c) throws IOException public void write(char[ ] cbuf.

out)).g. e. Writer out = new BufferedWriter(new OutputStreamWriter(System.OutputStreamWriter class public class OutputStreamWriter extends Writer An OutputStreamWriter is a bridge from character streams to byte streams: Characters written to it are encoded into bytes using a specified charset. .

Charset cs) OutputStreamWriter(OutputStream out. String charsetName) . CharsetEncoder enc) OutputStreamWriter(OutputStream out.OutputStreamWriter class Constructors OutputStreamWriter(OutputStream out) OutputStreamWriter(OutputStream out.

int off. int len) .OutputStreamWriter class Methods void close() void flush() String getEncoding() void write(char[ ] cbuf. int off. int len) void write(int c) void write(String str.

int offset.ByteArrayInputStream class public class ByteArrayInputStream extends InputStream ByteArrayInputStream(byte[ ] buf) ByteArrayInputStream(byte[] buf. int length) Methods of the InputStream class are defined here. .

ByteArrayOutputStream( ) ByteArrayOutputStream(int size) Methods from OutputStream class are defined here. .ByteArrayOutputStream class public class ByteArrayOutputStream extends OutputStream The data is written into a byte array.

int offset. . int length) Methods of Reader class defined here.CharArrayReader class CharArrayReader(char[ ] buf) CharArrayReader(char[ ] buf.

CharArrayWriter class CharArrayWriter( ) CharArrayWriter(int initialSize) Methods of Writer class are defined here .

int off. int len) throws IOException public long skip(long n) throws IOException public int available() throws IOException public void close( ) throws IOException .FileInputStream class public class FileInputStream extends InputStream A FileInputStream obtains input bytes from a file in a file system. Constructor public FileInputStream(String name) throws FileNotFoundException public FileInputStream(File file) throws FileNotFoundException Methods public int read() throws IOException public int read(byte[ ] b) throws IOException public int read(byte[ ] b.

boolean append) You will find write methods. boolean append) FileOutputStream(String name) FileOutputStream(String name. close method.FileOutputStream class FileOutputStream(File file) FileOutputStream(File file. .

FileReader class public class FileReader extends InputStreamReader public FileReader(String fileName) throws FileNotFoundException public FileReader(File file) throws FileNotFoundException Methods are inherited from super class .

FileWriter class class FileWriter extends OutputStreamWriter public FileWriter(String fileName) throws IOException public FileWriter(String fileName. . boolean append) throws IOException public FileWriter(File file) throws IOException public FileWriter(File file. boolean append) throws IOException Methods are inherited from super class.

read( )) != -1) System.readLine( )) !=null) System. while( (b=fis. String str.print((char)b). FileInputStream fis = new FileInputStream(³filepath´) int b.Code examples BufferredReader br = new BufferredReader(new InputStreamReader(new FileInputStream(³filepath´). . while((str=br.println(str).out.out.

fis. fos.read(bytes). FileOutputStream fos = new FileOutputStream(³output. int m = fis. byte[ ] bytes = new byte[m].dat´). .Code examples FileInputStream fos = new FileInputStream(³filepath´).available( ).write(bytes).

read( )) != -1) fw.write((char)ch). FileWriter fw = new FileWriter(³outputfile´). FileReader fr = new FileReader(³Inputfile´). int ch.Code examples If you want read characters from a file and write these characters to another file then use the following code. If you want to read lines from a file and write to another file then?? Try it out . while((ch = fr.

g. String relativePath) File(URI uri) e.g.File class public class File extends Object File(String path) File(String name. String getName( ) String getParent( ) boolean exists( ) boolean canRead( ). boolean renameTo(File newName) returns true if renaming succeeds String getPath( ). .list( ). String [ ] files = f. boolean canWrite( ).java´). File f = new File(³e:\´). boolean isFile( ) boolean isDirectory( ) String[ ] list( ) displays the files & directories in this File object e. File f = new File(³e:\dir1\dir2\prog. String getAbsolutePath( ).

g. File f = new File(³e:\dir1´).File class File [ ] listFiles( ) boolean mkdir( ) boolean mkdirs( ) e. f. . File f = new File(³e:\dir1\dir2\dir3\dir4´).mkdir( ). f.mkdirs( ).

then output operations are also available. input operations read bytes starting at the file pointer and advance the file pointer past the bytes read. There is a kind of cursor. public RandomAccessFile(String name. String mode) throws FileNotFoundException public RandomAccessFile(File file. String mode) throws FileNotFoundException . output operations write bytes starting at the file pointer and advance the file pointer past the bytes written. called the file pointer. If the random access file is created in read/write mode.RandomAccessFile class public class RandomAccessFile extends Object Instances of this class support both reading and writing to a random access file.

RandomAccessFile class Mode "r³ Open for reading only. Invoking any of the write methods of the resulting object will cause an IOException to be thrown. . "rwd" Open for reading and writing. and also require that every update to the file's content be written synchronously to the underlying storage device. "rws³ Open for reading and writing. "rw³ Open for reading and writing. as with "rw". and also require that every update to the file's content or metadata be written synchronously to the underlying storage device. If the file does not already exist then an attempt will be made to create it. as with "rw".

Associated with every service there exists a port number. A server is an entity that has sharable resource. email 25.myDomain. IP address comes in two forms namely. HTTP 80. FTP 21. A client is an entity that wants to access a server. domain name (www.xxx.net package provides the necessary API for writing networking program in Java.xxx. e. netnews 119.xxx) . Every computer has an IP address.com) & numeric IP address (xxx. Telnet 23.Java Networking java.g.

.Java Networking DNS maps the domain name to the IP address. The host name can be expressed by its domain name or by numeric IP address. A computer that has resource to share is called a host. If a domain name can be mapped to multiple numeric addresses then the host is called multi-homed host.

In Java a socket is an object that encapsulates this abstraction. Socket s = new Socket(www. int portno) throws UnkownHostException.ac.g.in.vit. . 80).Java Networking TCP Connection A socket is an abstraction of the end point of a connection. IOException e. A socket object is created using Socket class constructor Socket(String ipaddrr.

getInputStream( ). .getOutputStream( ). To obtain the input stream execute the code InputStream in = s. To obtain the output stream execute the code OutputStream out = s.Java Networking Associated with every socket there exists an input stream and an output stream. These are the streams to read data from and write data to the socket.

int port) throws IOException . public Socket(String host. A socket is an endpoint for communication between two machines. int port) throws UnknownHostException. IOException public Socket(InetAddress address.Socket class public class Socket extends Object This class implements client sockets (also called just "sockets").

public InputStream getInputStream() throws IOException Returns an input stream for this socket. public int getPort() Returns the remote port to which this socket is connected. public InetAddress getLocalAddress() Gets the local address to which the socket is bound. .Socket class Methods public InetAddress getInetAddress() Returns the address to which the socket is connected.

A new socket needs to be created. . can't be reconnected or rebound). it is not available for further networking use (i. Any thread currently blocked in an I/O operation upon this socket will throw a SocketException. Once a socket has been closed. public void close() throws IOException Closes this socket.Socket class public OutputStream getOutputStream() throws IOException Returns an output stream for this socket.e. If this socket has an associated channel then the channel is closed as well.

. e. ServerSocket ss = new ServerSocket(8189).g. //waits until a connection request comes in.Java Networking Inside the server program you create a server socket using constructor of ServerSocket class ServerSocket(int portno).accept( ). Socket s = ss.

public static InetAddress getByName(String host) throws UnknownHostException Determines the IP address of a host. given the host's name.InetAddress class It encapsulates IP address Methods public String getHostName() Gets the host name for this IP address public String getHostAddress() Returns the IP address string in textual presentation. .

. returns an array of its IP addresses public static InetAddress getLocalHost() throws UnknownHostException Returns the local host.InetAddress class public static InetAddress[ ] getAllByName(String host) throws UnknownHostException Given the name of a host.

use URL class constructor URL(String url) throws MalformedURLException Class URL represents a Uniform Resource Locator. An URL has the following form protocolname://hostname:portno/filepath In absence of the port no. such as a query to a database or to a search engine. a pointer to a "resource" on the World Wide Web.osborne. http://www.HTTP connection To establish HTTP connection with a host.com/index.g. or it can be a reference to a more complicated object.html Some of the methods of URL class are URLConnection openConnection( ) String getHost( ) String getProtocol( ) String getPort( ) . A resource can be something as simple as a file or a directory. it is assumed to be 8080 e.

opens a URL connection and reads data from this connection. URL url = new URL(http://www.HTTP connection The following code segment creates a URL object. int ch.out.html). InputStream is = urlcon.println((char)ch).osborne.read( )) != -1) System.getInputStream( ). URLConnection urlcon = url. while( (ch = is.openConnection( ).com/index. .

byte[ ] getData( ) . InetAddress iaddrr. DatagramPacket(byte[ ] data.UDP Connection A datagram is an independent packet. int portno) The first two constructors are used for receiving data and the other two are used for sending data. int sz. DatagramPacket class encapsulates a datagram. int sz. int sz) DatagramPacket(byte[ ] data. int off. int portno) DatagramPacket(byte[ ] data. InetAddress iaddrr. int sz) DatagramPacket(byte[ ] data. int off.

UDP connection DatagramSocket class DatagramSocket(int portno) throws SocketException Constructs a datagram socket and binds it to the specified port on the local host machine. InetAddress laddr) Creates a datagram socket. DatagramSocket(int port. bound to the specified local address. void send(DatagramPacket dp) Writes datagram packet to datagram socket void receive(DatagramPacket dp) Reads datagram packet from datagram socket .

.Remote Method Invocation Remote Method Invocation (RMI) facilitates object function calls between machines running JVM.

. Remote obj) throws AlreadyBoundException.rmi) public final class Naming extends Object public static Remote lookup(String url) throws NotBoundException. (rmi://host:port/name) public static void bind(String url. MalformedURLException.Naming class(java. RemoteException Returns a reference for the remote object associated with the specified url. MalformedURLException. RemoteException Binds the specified name to a remote object.

NotBoundException. Any existing binding for the url is replaced. MalformedURLException Returns an array of the urls bound in the registry. . Remote obj) throws RemoteException. MalformedURLException Destroys the binding for the specified url that is associated with a remote object. MalformedURLException Rebinds the specified name to a new remote object.  public static String[ ] list(String name) throws RemoteException.  public static void unbind(String url) throws RemoteException.Naming class  public static void rebind(String url.

A public default constructor in this class is mandatory. The interface should be developed in the local as well as in the remote machine.rmi).rmi.  Develop a class that implements this interface and extends the API class UnicastRemoteObject (java.server) in the remote machine.  Develop a class in the remote machine that creates an object of the class that implements the method interface and registers this object with the rmi registry using bind method or rebind method of the Naming class. . This interface must be an extension of the API interface Remote (java.What should you do to develop and test RMI application?  Develop an interface containing the method(s) to be invoked. This class facilitates export of object from the remote machine to the local machine.

1 ClassName_That_Implements_Interface  start rmiregistry  start java ClassName_That_Registers_Object_With_RMIRegistry  java Addition .  Create the class files from the source files in the local & remote machine.  Create the stub and skeleton using at the command prompt: rmic ±v1.RMI application  Develop a class inside the local machine that looks for the desired service using lookup method of the Naming class.

com  Core Java Volume II by Horstmann & Cornell .References  Thinking in Java.sun. Bruce Eckel  java.

In 1996. The JDBC driver manager (written in pure Java) manages the database drivers. they came out with two group of interfaces namely.Java Database Connectivity (JDBC) JDBC is a collection of classes & interfaces (java. In 1995. . Sun tried to expand the Java library for accessing SQL database. JDBC API and JDBC driver API. A database driver allows a program to talk to a database.sql) for accessing SQL database from Java program.

forName(³driver class file´).jdbc. For loading the driver use the following code Class.jdbc.odbc.Driver Each new connection needs the driver to be loaded.OracleDriver For connecting to Microsoft access database use the driver jdbc.oracle.JdbcOdbcDriver For connecting to MySQL database use the driver com. e.mysql.g the driver for connecting to Oracle database has the name com.JDBC For connecting to different database management systems you need different drivers. public static Class forName(String className) throws ClassNotFoundException @Class class .

url = protocol:subprotocol:dsn DriverManager class is declared in java.  public static Connection getConnection(String url. ³pwd´). String password) throws SQLException @DriverManager class Attempts to establish a connection to the given database URL.sql .sql Connection is an interface declared in java. ³user´.getConnection(³protocol:subprotocol:data source name´.JDBC For connecting to database use the following code Connection conn = DriverManager. String user.

. ³pwd´).getConnection(³jdbc:oracle://host/dbname´.getConnection(³jdbc:odbc://host/dbname´. ³user´.JDBC For connecting to MySQL database use Connection conn = DriverManager.getConnection(³jdbc:mysql://host/dbname´. ³pwd´). For connecting to access database use Connection conn = DriverManager. ³pwd´). ³user´. For connecting to Oracle database use Connection conn = DriverManager. ³user´.

getDouble(³sal´ ) ).createStatement( ).println(rs. . You may use column name or column number. The getXXX method of ResultSet is used to retrieve the value at the column. The next( ) method of ResultSet returns false when there is no more row in the cursor rs.JDBC For executing query on the database use the following code Statement stmt = conn. ResultSet rs = stmt. so also ResultSet.out.executeQuery(³select ename. while( rs. Statement is an interface (java. sal from emp where sal > 30000´).next( )) System.getString( ³ename´) + ³ ³ + rs.sql).

 boolean execute(String sql) throws SQLException Executes the given SQL statement (SQL query/ DDL /DML statement) . or DELETE statement or an SQL DDL statement. which returns a single ResultSet object.JDBC Statement interface  public ResultSet executeQuery(String sql) throws SQLException Executes the given SQL statement.  public int executeUpdate(String sql) throws SQLException Executes the given SQL statement. UPDATE. which may be an INSERT.

JDBC Connection interface  public Statement createStatement() throws SQLException Creates a Statement object for sending SQL statements to the database.  public PreparedStatement prepareStatement(String sql) throws SQLException Creates a PreparedStatement object for sending parameterized SQL statements to the database.  public void commit() throws SQLException  public void rollback() throws SQLException  public void close() throws SQLException .

 public int executeUpdate() throws SQLException Executes the SQL statement in this PreparedStatement object.JDBC PreparedStatement interface (A sub interface of Statement interface)  public ResultSet executeQuery() throws SQLException Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query. or a DDL statement. . UPDATE or DELETE statement. which must be an SQL INSERT.

which may be any kind of SQL statement. If the parameter is of type int then use setInt method. .JDBC  public boolean execute() throws SQLException ‡ Executes the SQL statement in this PreparedStatement object. if it is of type double then use setDouble method. Xxx value) methods that assign a value to a parameter. You will find setXxx(int index.

JDBC ResultSet interface  public boolean next() throws SQLException  public String getString(int colindex) throws SQLException  public String getString(String colName) throws SQLException  public int getInt(int colindex) throws SQLException  public int getInt(String colName) throws SQLException  public double getDouble(int colindex) throws SQLException  public double getDouble(String colName) throws SQLException  public float getFloat(int colindex) throws SQLException  public float getFloat(String colName) throws SQLException .

user_input).setInt(2. PreparedStatement pstmt = conn. //load driver Connection conn = //connect to database DriverManager. ³user´.setDouble(1. sal from emp where sal > ? and deptno = ?´).prepareStatement(³Select ename. ResultSet rs = pstmt. ³pwd´).getConnection(³protocol:subprotocol:data source name´. pstmt.forName(³driver class file´).JDBC If the query is of the form Select ename. //iterate through rs . user_input). sal from emp where sal > ? and deptno = ? then use PreparedStatement object as shown below: Class. pstmt.executeQuery( ).

pstmt. pstmt.executeUpdate( ).setXXX(1. //stmt.executeUpdate(³update emp set«´). Statement stmt = conn. stmt.JDBC DML statement Load the driver. connect to database.execute(³update emp set«´). pstmt. value1).setXXX(2. .prepareStatement(³DML statement´ ).createStatement( ). value2). you could also write this For parameterized SQL statement use PreparedStatement object: PreparedStatement pstmt = conn.

prepareStatement(³DDL statement´ ).executeUpdate(³create table «´). Statement stmt = conn.createStatement( ).execute(³create table «´). value1).JDBC DDL statement Load the driver. pstmt. pstmt. value2). connect to database.setXXX(2.executeUpdate( ). stmt. .setXXX(1. pstmt. you could also write this For parameterized SQL statement use PreparedStatement object: PreparedStatement pstmt = conn. //stmt.

JDBC  You may create & execute stored procedure & functions  You may create triggers in the database  You may manipulate meta data (result set meta data & database meta data) .

com  Core Java Volume II by Horstmann & Cornell .sun. Bruce Eckel  java.References  Thinking in Java.

2010 Portions Multithreaded programming Java I/O .QUIZ III Scheduled on April 12.

2010 Portions Java Networking JDBC RMI .QUIZ IV Scheduled on April 19.

It cannot keep control with itself for a prolonged interval. Whenever an event occurs.Console-based program vs.g. This is why if you want a window-based program to do a job repeatedly (e. When there is no event it waits for an event to occur. Window-based program A console-based program can prompt its user for input but a windowbased program cannot. takes necessary actions and immediately returns control to the runtime system. . animation) then you need to run an additional thread of execution. the program catches the event. All window-based programs are event-driven.

 They do not require main methods.  They are downloaded from the Internet onto client machine. .  Applets cannot run independently. automatically installed and execute in the client machine.Applets Definition An applet is a window-based small program that can run inside a browser / appletviewer.

Applets Applets are safe and secure because (i) they cannot access the file system of the client machine and (ii) cannot establish network connection with any host other than the one they are downloaded from. .

applet catches the event.g. take necessary actions and immediately return control to the runtime system. This is why if you want an applet to do a job repeatedly (e. animation) then you need to run an additional thread of execution. Whenever an event occurs. . It cannot keep control with itself for a prolonged interval.Applets Applets are event driven.

g. pubic class Applet1 extends Applet { Body of the class }. .applet) and this class must be declared public e.Applets Every applet that you develop must a sub class of Applet class (java.

Applets Object Component Container Panel Applet A panel is a surface without border and title bar .

public Color getForeground( ) The Color class is in the package java.awt.Component class  Component class (java.  public Color getBackground( ). .  public void setForeground(Color c) This method changes the fore ground color of this component.awt)  public void setBackground(Color c) This method changes the back ground color of this component. The default back ground color of a component is light grey and fore ground color is black.

. In its default implementation it calls paint method.Component class  public void paint(Graphics g) Draws this component.awt & it provides graphical context. The Graphics class is in the package java.  public void update(Graphics g) Redraws this component.

 public void repaint(long ms. int left. int w.Component class  public void repaint( ) redraws this component. int top. int h) draws a portion of this component defined by the top left corner and the width and height. int left. int w. calls update which in turn calls paint method.  public void repaint(int top. int h) .  public void repaint(long ms) ms is the delay that can be tolerated before update is called and if update is not called by ms milliseconds then it is not called at all this time.

ITALIC. e.setFont(f). Font.g.BOLD | Font. Font f = new Font(³Verdana´. this. 16).Component class  public void setFont(Font f) Changes the font of text displayed on this component. .

. method is called by the browser or the appletviewer only once when the applet class file is loaded.Applet class  public Applet( )  public void init( ) initialize the applet. If you minimize the applet window then the stop method is called and when you maximize the applet window the start method is called. Start and stop may be called more than once.  public void start( ) starts or resumes execution of the applet  public void stop( ) suspends the execution of the applet.

 public void showStatus(String msg) displays the msg in the status bar of the browser/appletviewer.  URL getDocumentBase( ) returns the URL of the document in which this applet is embedded. Before destroy is called stop is called. .Applet class  public void destroy( ) removes the applet from the client`s memory.  URL getCodeBase( ) returns the base directory of the applet class file.

.  String getParameter(³param name´)  void showDocument(URL url) requests the browser to display the document whose URL is passed as an object. This method does not work with applet viewer.Applet class  String getAppletInfo( ) returns the author`s name. of the applet. If it cannot show the document then no exception is thrown. version etc. The default implementation returns null.

‡ AudioClip getAudioClip(URL url) ± Returns the AudioClip object specified by the URL argument. The url that is passed as an argument must specify an absolute URL.Applet class AppletContext getAppletContext( ) returns the context the applet is running. ‡ void play(URL url) ± Plays the audio clip at the specified absolute URL . Image getImage(URL url) Returns an Image object that can then be painted on the screen.

Applet tag In its simplest form <applet code = appletClassFile width = « height = « > </applet> Detail of applet tag <applet code = appletClassFile width = « height = « codebase = baseDirectory hspace = no of pixels vspace = no of pixels align = MIDDLE| LEFT | RIGHT | TOP | BOTTOM | TEXTTOP alt =´text´ name = ³appletname´ > <param name = name1 value = value1> <param name = name2 value = value2> « <param name = namen value = valuen> </applet> .

. The attribute name is used for communication among applets running in the same context.Applet tag In case the browser is Java enabled but currently cannot display the applet then the alternate text (alt) is displayed.

One window cannot be attached to another window.Abstract Window Toolkit (AWT) AWT is a collection of classes and interfaces for developing GUI. Component Container Panel Applet Frame Window Dialog A window is a surface without title bar and without border. .

AWT Component Label Button Checkbox List Choice Scrollbar TextComponent TextField TextArea .

RIGHT. Label.LEFT. int align) Value of align may be Label.Label class Label( ) Label(String text) Label(String text.CENTER String getText( ) void setText(String newText) int getAlignment( ) void setAlignment(int align) . Label.

Button class Button( ) Button(String caption) String getLabel( ) void setLabel(String caption) .

CheckboxGroup cbg. CheckboxGroup cbg) Checkbox(String label. boolean checked. boolean checked) Checkbox(String label. boolean checked) boolean getState( ) void setState(boolean checked) String getLabel( ) void setLabel(String label) .Checkbox class Checkbox(String label) Checkbox(String label.

Choice class Represents a pop-up menu Choice( ) creates an empty list of items. To add item to the list void add(String item) Other methods String getSelectedItem( ) String getItem(int index) void select(int pos) void insert(String item. int index) void remove(int index) void add(String item. int index) int getSelectedIndex( ) int getItemCount( ) void select(String item) void remove(String item) void removeAll( ) .

Choice class The following code example produces a pop-up menu: Choice colorChooser = new Choice().add("Blue"). colorChooser.add("Red"). colorChooser.add("Green"). colorChooser. .

add("Mercury").List class List class The List component presents the user with a scrolling list of text items. List( ) List(int numRows) no.add("Venus").add("JavaSoft").g. lst. lst. lst. boolean multiselect) e. of rows visible at any time.add("Earth"). lst. . The list can be set up so that the user can choose either one item or multiple items. false). List(int numRows. List lst = new List(2.

int index) String getSelectedItem( ) String getSelectedIndex( ) String [ ] getSelectedItems( ) String [ ] getSelectedIndexes( ) int getItemCount( ) And other methods similar to the methods of Choice class .List class void add(String item) void add(String item.

String getSelectedText( ) . TextField( ) blank field of 20 columns TextField(int numChars) TextField(String text) TextField(String text. int numChars) String getText( ) void setText(String text) void setEditable(boolean editable) boolean isEditable( ) returns true if you can write text in the text field.TextField class An object of this class is a single-line edit control. void setEchoChar(char ch) boolean echoCharIsSet( ) char getEchoChar( ) retrieves the echo character.

int numlines.SCROLLBARS_VERTICAL_ONLY .SCROLLBARS_NONE(default) = TextArea. int numChars. int sbars) sbars = TextArea. int numChars) TextArea(String text. TextArea( ) TextArea(String text) TextArea(int numlines.SCROLLBARS_HORIZONTAL_ONLY = TextArea.SCROLLBARS_BOTH = TextArea.TextArea class An object of this class is a multi line edit control.

. int ei). int pos) void replace(String str.TextArea class String getText( ) void setText(String text) void append(String) void insert(String text. int si.

300). int max) int getMinimum() int getMaximum( ) int getValue( ) void setValue( ) void setUnitIncrement( int newValue) void setBlockIncrement(int newValue) e.HORIZONTAL. 0.Scrollbar sb = new Scrollbar(Scrollbar.HORIZONTAL.g. int min. . VERTICAL Scrollbar( ) Scrollbar(int style) Scrollbar. ScrollBar. int thumbSize. 0.VERTICAL Scrollbar(int style int initValue. 1.Scrollbar class HORIZONTAL.

A code example: .Frame class A Frame object is a surface with border and title bar. Frame( ) Frame(String title) A Frame object is a container and so it can hold components.

Window class A window is a surface without border and title bar. Window(Frame owner) A code example: .

Panel class An object of this class is a surface without border and without title bar. . Panel( ) Panel(LayoutManager lm) creates a panel with the specified layout manager.

grid layout. Each of these classes is an implementation of LayoutManager interface. border layout.Layout Managers Layout Managers lay out the components inside a container using algorithms. . GridLayout. There are different types of layout namely. flow layout. CardLayout classes respectively. card layout and these are implemented in FlowLayout. BorderLayout.

CENTER. int vgap) ± hgap .the vertical gap between components and between the components and the borders of the Container . FlowLayout. FlowLayout( ) FlowLayout(int how) how = FlowLayout.RIGHT FlowLayout(int how.LEFT. FlowLayout. int hgap. The default spacing between components is 5 pixels (both horizontal and vertical direction).FlowLayout class The flow layout manager lays out components from left to right and top to bottom.the horizontal gap between components and between the components and the borders of the Container ± vgap .

.BorderLayout class This layout manager lays out components at 5 different regions ± one large area at the center and four narrow fixed-width regions at the edges of the container.

int vgap) .BorderLayout class BorderLayout( ) BorderLayout(int hgap.

GridLayout class This layout manager lays out components in an invisible grid inside the container. GridLayout( ) GridLayout(int numRows. int numCols. int hgap int vgap) . int numCols) GridLayout(int numRows.

Changing layout of a container The default layout of a frame and window is border layout. The default layout of an applet and a panel is flow layout. use public void setLayout(LayoutManager lm) @ Container class. . To alter the layout manager of a container.

int pos) @ Container class . public Component add(Component cmp.Adding component to a container To add component to a container use one of the methods: public Component add(Component cmp) @ Container class.

A case study .

The event handling facilities are found in the package java. A source is an object that can fire an event. A listener is an object that can receive event. .awt. After receiving event notification the event handler handles the event and returns control to the runtime system.Event handling An event is an object that describes change of state of a source.event. In order that a listener can receive an event fired by a source it must registers itself with the source.

a source fires an event and sends it to one or more listeners. . The advantage of this design is that the application logic that processes the event is cleanly separated from the user interface logic that fires the event. the listener processes the event and then returns. A user interface element is able to delegate the processing of event to a separate piece of code.Delegation event model In this model. Once received. A listener must registers with a source in order to receive an event notification and thus notifications are sent only to listeners that want to receive them. The listener waits until it receives an event.

g.Event handling When you click on a button an ActionEvent is fired. The event handler (method that processes the event) is public void actionPerformed(ActionEvent ae) @ ActionListener interface. addActionListener(al). To register a listener with a button use the method public void addActionListener(ActionListener al) e. . b1.

. The method that can handle the event is public void itemStateChanged(ItemEvent ie) @ ItemListener interface The registration method is public void addItemListener(ItemListener il).Event handling If you click on a check box an ItemEvent is fired.

Event handling  If you click (single) on a choice item an ItemEvent is fired  If you double click on a list item an ActionEvent is fired.  If a text field has input focus and if you press the enter key then ActionEvent is fired. .

.Event handling When you edit a text field or a text area then TextEvent is fired. The method that handles the event is public void textValueChanged(TextEvent te) @ TextListener interface The method that performs the registration is public void addTextListener(TextListener tl).

.Event handling When you manipulate a scroll bar an AdjustmentEvent is fired The event handler is public void adjustmentValueChanged(AdjustmentEvent ae) The registration method is public void addAdjustmentListener(AdjustmentListener al).

The registration method is public void addKeyListener(KeyListener kl) .Handling key events A KeyEvent is fired when you press/release/type a key. The event handlers are public void keyPressed(KeyEvent ke) public void keyReleased(KeyEvent ke) public void keyTyped(KeyEvent ke) @KeyListener interface.

For each key there is defined a public static final identifier in the KeyEvent class and name of these identifiers starts with VK (virtual key) e.KeyEvent class Some of the useful methods declared in the KeyEvent class are int getKeyCode( ) returns an integer associated with the key char getKeyChar( ) returns the character associated with the key (character echoed) . VK_SHIFT . If there is no character associated with the key then CHAR_UNDEFINED us returned.g. VK_A. VK_B.

. keyTyped) then you find an adapter class for the interface. keyReleased.Adapter class If a listener interface has multiple methods (e. If you use adapter class you don`t have to define all the methods of the interface.g. KeyListener interface has 3 methods ± keyPressed. If you are implementing the KeyListener interface then you need to give the definition of all the methods (even an empty definition is mandatory). An adapter class is a default implementation of listener interface.

Code example: //listener registration addKeyListener(new KeyAdapter( ) { public void keyTyped(KeyEvent ke) { //code } } ).Adapter class The adapter class for the KeyListener interface is KeyAdapter. .

The event handling methods are public void mouseClicked(MouseEvent me) public void mousePressed(MouseEvent me) public void mouseReleased(MouseEvent me) public void mouseEntered(MouseEvent me) public void mouseExited(MouseEvent me) @MouseListener interface .Mouse event A MouseEvent is fired when a mouse is clicked/pressed/released/enters a component/exits from a component/moved/dragged.

Mouse event Two other event handling methods are public void mouseMoved(MouseEvent me) public void mouseDragged(MouseEvent me) @MouseMotionListener interface The methods that registers a listener to receive mouse event are public void addMouseListener(MouseListener ml) public void addMouseMotionListener(MouseMotionListener ml) .

Adapter class The adapter class for MouseListener is MouseAdapter for MouseMotionListener is MouseMotionAdapter .

The WindowEvent class encapsulates window event. The event handling methods are public void windowIconified(WindowEvent we) public void windowDeiconified(WindowEvent we) public void windowOpened(WindowEvent we) public void windowClosed(WindowEvent we) public void windowClosing(WindowEvent we) @ WindowListener interface .Window event A window event is fired when a window is iconified/deiconified/opened/cloded/closing/activated/deactivated/ gain focus/lost focus.

Window event public void windowGainedFocus(WindowEvent we) public void windowLostFocus(WindowEvent we) @ WindowFocusListener interface To find the order in which the event handling methods are called include an output message in each of the event handling methods. The registration methods are addWindowListener(WindowListener wl) addWindowFocusListener(WindowFocusListener wfl) .

Adapter classes WindowAdapter WindowFocusAdapter for for WindowListener WindowFocusListener .

. } } ).Dismissing a frame using closing button //registration addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { dispose( ).

.Menu bar. menus. menu items & check box menu items MenuCompnent MenuBar MenuItem Menu CheckboxMenuItem Since Menu class is a sub class of MenuItem class so a hierarchy of nested sub menus can be created.

Menu bar.g.g. boolean tearOff) e. MenuShortcut keyAccel) . MenuItem( ) MenuItem(String label) MenuItem(String label. menu items & check box menu items MenuBar( ) e. menus.MenuBar mbar = new MenuBar( ). Menu( ) Menu(String label) Menu(String label. Menu menu = new Menu(³Draw¶).

g.VK_L. new MenuShortcut(KeyEvent. menu items & check box menu items MenuShortCut(int key) MenuShortCut(int key. boolean checked) For adding a MenuItem object to a Menu object use MenuItem add(MenuItem item) @ Menu class Adds the item to this Menu object. true) CheckboxMenuItem( ) CheckboxMenuItem(String label) CheckboxMenuItem(String label.g.menu. MenuItem item = new MenuItem(³Line´.Menu bar. boolean shiftRequired) e. menus.add(item1) . e.

adds mbar to this object .g. mbar.Menu bar. For adding menu bar to the container use void setMenuBar(MenuBar mbar) @ Frame class e. menus.add(menu). e.g. menu items & check box menu items For adding Menu object to the menu bar object use Menu add(Menu menu) @ MenuBar class Appends menu to this MenuBar object. setMenuBar(mbar).

Menu bar. Add menu object to menu bar object. menus. Add men u bar object to the container. Add these items to the menu object. . When user clicks on a check box menu item an ItemEvent is fired. menu items & check box menu items Create menu items (and check box menu items). When user clicks on a menu item an ActionEvent is fired.

Sign up to vote on this title
UsefulNot useful