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

double (for floating point numbers. . signed and 32 bits). signed and 64 bits). long (for long integers. signed and 64 bits).Basic (primitive) data types char (unsigned and 16 bits). signed and 16 bits). int (for integer. signed and 32 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. ‡ The true and false are not converted into numeric representation. float (for floating point numbers. ‡ The true and false are known as boolean literals ‡ Can be assigned to boolean variables only ‡ Can be used in expressions with boolean operators. short (for short integer.

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

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

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

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

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

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

. Any mismatch between the type of formal and actual parameter(s) In function call is flagged as compile time error. e.Automatic type promotion Java is a strongly typed language. 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. Any type mismatch is flagged as compile time error.g.

g.Lexical elements (Building blocks of Java source code) ‡ ‡ ‡ ‡ ‡ White spaces Identifiers (name of a class. pkg1. string literals ³java´) Comments (// single line.pkg2. variable. ob. method. boolean logical operators) ‡ . 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 . bitwise operators.m) Operators (Arithmetic operators. ob.2. 45.(e. defining operator precedence. Used to terminate a statement Comma . interface. /* */ multi-line. 1. containing expressions in control statements. Used to separates consecutive identifiers in variable declarations and to chain statements together inside for loop Period .g. constant) Literals (true. numeric literals e. character literals e. false. Used to separate package name from sub package and to separate a variable or a method from a reference variable.g. relational operators. µj¶. /** */ documentation comment) Separators Parentheses ( ) Used to contain a list of parameters in method definition & invocation.f().

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

g.g. E. e. private native void method( ). C++. .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.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. Used as modifier in method declaration. assert expression.

char [ ] chrs = new char[20]. The array elements are initialized by blank space.  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 elements of String arrays are initialized by null. type arrayname [ ] = new type[size]. . The elements of boolean arrays are initialized by false. float [ ] x = new float[10].0f. int [ ] m = new int[10].  The identifiers m. e.Arrays 1-D Array type[ ] arrayname = new type[size].g. The array is created and all elements are initialized by 0. The array is created and all elements are initialized by zero. x and chrs are actually references.

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

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

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

i++) arrayname[i] = new type[size2].2D arrays type[ ] [ ] arrayname = new type[size1][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

//code third: for (.Labeled continue The following code will not compile.) {//inner loop //code if( condition) continue third. }//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..) {//outer loop //code second: for (. else continue third. first: for (..... .) {//inner most loop //code if( condition) continue second..

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

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

‡ Every Java source file is converted into a class file (. ‡ 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. ‡ There exists only one (the original) copy of a class field.Classes ‡ Fields can be static or non-static. ‡ The non-static fields are called instance fields. ‡ Static fields are called class fields because they belong to the class and do not belong to the object.class file) by the Java compiler . Each object of a class has a copy of each of its instance field.

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

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

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

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

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

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

Local variables ‡ Variables declared inside a method or inside a block of code e. void method(«) { boolean flag = true. . // x is local to this block « }//ends ‡ A block of code is defined by a pair of braces.67. «. // flag is local to the method int m = 10. } {//block of code starts double x = 4.g. ‡ 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.

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

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

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

X x4.Object creation X x1 = new X ( ). Object not yet created. 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 x2 = new X(4). No new object has been created.20). There is no compile time object . only a reference has been declared x4 = x3. All objects are created on the heap at the run time. X x3 = new X(10. x4 points to the same object as x3 points to.

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

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

Object cloning You may also use constructor for object cloning. } X x1 = new X(5. n = ob. X x2 = new X(x1). X (X ob) { m = ob. x2 is now a copy of x1. 10). .g. e.m.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. .  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.  Its return type is void and its argument is an array of strings.

The built-in classes will be referred to as the API (Application Programming Interface) classes.println or System. .Sending output to the standard output device (display screen) Use System.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.out. print and println methods can take any argument except of type void.out. print and println convert their arguments into string before sending them to the console (display screen).

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

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

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

Box. you need to type java BoxTest at the command line.class & BoxTest. To execute the program.class. .Some observations After compilation of this code two class files are created by the java compiler. 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.

.  The argument of java command must be the name of the class which you want the execution to start from.  This is useful for unit testing (Developing and testing each class separately).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.

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

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

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

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

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

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

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

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

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

Concrete class A class that is complete is called a concrete class. otherwise it is called a nested class. Abstract class An incomplete class is called an abstract 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. Incomplete class A class is called incomplete if its specification either has not been implemented completely or implementation is unknown.

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

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

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

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

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

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

Interfaces A partial syntax for implementing an interface: class ClassName implements I1 [.I3.«] { 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. I2 { //definition of the methods of I1 & I2 } . I2.

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.

inside constructor of the subclass. ‡ To call super class constructor use super(arglist).member ‡ `super` is available only to the non-static members of a class .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.

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

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

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

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

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

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

Announcement JAVA QUIZ I Scheduled on Jan. 22. 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

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

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

} class X implements A. } interface C { void f( ).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( ). void g( ). String g ( ).

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

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

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

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

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

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

‡ 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. .e. ‡ A nested class can be declared static or non-static ‡ To declare a static nested class. deep nesting is possible) but nesting up to level two is recommended. use the modifier static ‡ A nested class can extend some other class and can itself be extended.

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 is the enclosing (outer) class of Y and Z //code [static] class Y { // a nested class .

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

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

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

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

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

 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. . Feature Since it does not have a name so it cannot have a constructor.

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

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

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

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

 The super type may be either a class or an interface.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. .  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.

strictfp guarantees common behavior across platforms in the results of floating point arithmetic i. 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.e.Modifier strictfp Though Java is platform independent.

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

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

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

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

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

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

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

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. ‡ public byte[ ] getBytes(String charsetName) throws UnsupportedEncodingException Encodes this String into a sequence of bytes using the named charset. . storing the result into a new byte array.

.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 boolean equalsIgnoreCase(String anotherString) Compares this String to another String. ignoring case considerations.

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

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

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

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

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

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

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

String class ‡ public String replaceAll(String str. 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. The default locale of windows is English(US) ‡ public String toUpperCase() .

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

‡ public String toUpperCase(Locale locale) .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.

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

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

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

³Java language´.startsWith(³Java´). .g. e. int toffset) Tests if this string starts with the specified prefix beginning a specified index. 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. ‡ public boolean startsWith(String prefix.

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

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

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 .

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

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

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

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

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

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

‡ public StringBuffer append(char[ ] chrs. int len) Appends the string representation of a subarray of the char array argument to this string buffer. ‡ public StringBuffer append(char[ ] chrs) Appends the string representation of the char array argument to this string buffer.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. The subarray starts at offset and has len characters . int offset.

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

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

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

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

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

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

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

Exercise Develop a program to demonstrate the functionality of the constructors and the methods of the StringBuffer class. 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. .

but they cannot be declared public. You may have other classes and interfaces in the same compilation unit.  There is no restriction on the number of classes and interfaces that a compilation unit may have.package  A source file is called a compilation unit or translation unit. .  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.

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

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

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

 The classes and interfaces declared inside a package can talk to each other.  The classes and interfaces declared inside a package can talk to only public classes and interfaces declared in other packages each other. .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. even if they are declared inside a different compilation unit.

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

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

java  To execute the class file you need to go to the base directory (i. e:\java\08mca) and type java pkg1.Example  If you want to develop a package with name pkg1.e.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.

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.  How to add more classes and interfaces to the package pkg1?  Create another Java source file say.  At present the only source file which is inside the package pkg1 is Example. Example1. .Including more classes and interfaces into a package  Any number of compilation units may belong to a package.java.java with the package statement package pkg1.

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

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

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

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

util.event is a sub package of the package 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 is a sub package of the package java.awt.servlet. javax.lang.package  The packages are organized in the form of hierarchy.math.http  java. java. java.swing. javax.awt. java.awt.event.awt. java. java.

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

 The class pkg1.Example is different from the class pkg1.Example.Why package?  To guarantee uniqueness of class and interface name.Example and pkg2.ac.g.pkg2. 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. in. e.  To absolutely guarantee the uniqueness of class and interface name.vit may be the root of the all packages being developed at VIT .

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

The import statement import packagename1.  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. implies that the members of the package named packagename1.  The import statement is about availability only.packagename2 are available to this source file. implies that the class ClassName is available to this source file.ClassName. .import statement The import statement import packagename.*.

Z. Y.g.import statement e. 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. X. I1.*. if a package pkg1 has a number of public classes and interfaces say. .

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

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

*.sql. you find the Date class inside the package java.sql.  Two different packages may contain the same class/interface.e.util. you can write either java. import java.*.g.Date or java.  You may use the import statements import java.util and java. e. inside the same source file.Date .util.sql.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.

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

*.ClassName.import statement  An import statement of the form import pkg1. . is called single type import  Using import on demand is easier than single type import. 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. This is why it is preferable to use import on demand to single type import.

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

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

private (modifier used is private) ± least access package (no modifier is used. This is the default access).  There are four different levels of access namely.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 .

 If it is declared without any access modifier then it is visible throughout the package.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 private then it is visible only inside the class (least access).

//visible only inside this class protected double d. 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 . //visible inside this package & in a sub class in //other package void f( ) {//visible anywhere inside the package pkg1.Access protection (Example) package pkg1.

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 } . public class Y { //can access public members of X //cannot access protected members of X.Access protection (Example) package pkg2.*. import pkg1.

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 .

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

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

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

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

ArrayIndexOutOfBoundsException ---.IllegalArgumentException ---.NumberFormatException ---.ConcurrentThreadException .IllegalThreadStateException ---.StringIndexOutOfBoundsException ---.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 ---.Exception class hierarchy IOException ---.EOFException .

. . finally. catch. finally{ //code that must be executed before try block ends } .Exception handling Exception handling is performed using the keywords try. throw and throws. 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) } .

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.g.  If you need to release some resources (e. closing files. disconnecting from the database. .  The exception types in different catch blocks associated with a try block must be different. finally is optional.  If finally block is present then it will be executed even if no exception is thrown. releasing locks) even in the face of runtime errors then use finally block & write this code inside finally block.

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

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

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

}catch(ArithmeticException e) { a = 0.util.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. }//for }//main }//HandleError .Random r = new java.nextInt( ).Random( ). c = r.nextInt( ).out. c=0. java.println(³a = ³+ a). try { a = 10/(b/c). for (int i = 0. b=0. i++) { b = r. } System.util. i< 100.

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

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

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

.Exception handling The above code will not compile. you need to catch ArithmeticException object before catching Exception object. Reason Super class reference can receive sub class object. The ArithmeticException and ArrayIndexOutOfBoundsException being a subclass of Exception. 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. In order that the code compiles. See the next slide.

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

e. you may have one try block inside another try block. 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. . but is nesting up to level two is recommended.

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

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

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

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

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

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( ). }catch(IllegalAccessException e) { e.Exception handling The following code will not compile. } } } . } public static void main(String[ ] args) { try { f( ).printStackTrace( ).

}catch(IllegalAccessException e) { e.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( ). } } } .printStackTrace( ). } public static void main(String[ ] args) { try { f( ).

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

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

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

e.getCause( ). e1.printStackTrace( ). } }//main }//ChainedException .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´).initCause(new ArithmeticException(³this is the cause´). }catch(NullPointerException e1) { e1. try { throw e.

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

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

 An exception is called asynchronous exception if it is thrown while executing instruction of the JVM.  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.Exception handling Synchronous & asynchronous exception  When the instructions of the developer¶s program execute.

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

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

Multithreaded programming State transition diagram New Ready Suspended Running Terminated .

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( ). . The definition of the run method describes the work done by the thread.

String name) public Thread(ThreadGroup group. 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.Multithreaded programming Thread class (package java. Runnable work) public Thread(ThreadGroup group. Runnable work.

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.Multithreaded programming A thread group is a data structure that controls the behavior of a collection of threads. Value 10 . Value 5 public static final int MAX_PRIORITY The maximum priority that a thread can have.

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

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

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

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

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

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

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

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

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

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

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

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

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

There are two different ways of implementing synchronous execution of code segment  Synchronized method  Synchronized block .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.

Multithreaded programming synchronized method use synchronized method and use the code segment to be synchronized inside this method. Constructors cannot be synchronized. e. . 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.

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.g. X x = new X( ). synchronized(x) { x.f( ). //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 } .

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

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

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

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

These methods are useful in establishing communication among threads (called inter-thread communication).Multithreaded programming wait. . inherited by the Thread class. notify and notifyAll method These are the declared methods of the Object class.  final void wait( ) throws InterruptedException Suspends execution of this thread until some other thread wakes it up invoking notify or notifyAll method. it does not release the lock before going to sleep). 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.e.

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. or a specified amount of time has elapsed.  final void wait(long ms. int ns) throws InterruptedException .

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.

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

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

 After producing the item the producer has to wait until the item is picked up (assuming that the buffer size is one).Multithreaded programming  The consumer is in indefinite wait until an item is produced.  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.  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. .

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

notify( ).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( ). }catch(InterruptedException e) { } }//while data = m. found = true. }//drop }//Data .

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

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

start( ). new Thread(new Producer(dt)). } } .start( ).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)).

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( ).sleep(1000).Deadlock Code example class A { synchronized void h( ) { //h( ) @ A //code } synchronized void f(B b) { try { Thread. //h( ) @ B } } . }catch(InterruptedException e) { } b.

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

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

. 2. start calls run method which in turn execute (child thread is executing) b. Since f is a synchronized method. 4.start( ) 3. since it contains sleep so the child thread t is suspended and CPU is switched to the main thread. When the main thread was suspended last it had already executed t. the lock of b is required and so it is allocated to the child thread t. After entering into the method f. 5.start( ) and so now it executes a.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).f(a). Main thread comes into existence and calls X( ) using new X( ).

When CPU is again switched to the main thread it requires the lock of a which is now held by the child thread t. So the main thread and the child thread are in a deadlock situation. After entering into method g the main thread is suspended again because of Thread. So the CPU is now switched to the child thread t. 7.h ( ). It now requires the lock of b to execute b.sleep(1000) inside g. .Deadlock 6. 8. The child thread was suspended last and now gets the CPU. 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). But the lock of b is already held by the main thread. 9.

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

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

gc( ) ACM Transactions on Programming Languages & Systems .Garbage collection  A garbage collector is a piece of software that reclaims the memory occupied by dead objects. When the GC executes the application program is halted.  There are various algorithms for implementing garbage collection.  An application developer can call the GC using System.  The application program and the GC run concurrently.  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).

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

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

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

the value -1 is returned. or an exception is thrown.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. then no bytes are read and 0 is returned. If no byte is available because the stream is at the end of the file. If the length of b is zero. . otherwise. The number of bytes actually read is returned as an integer. This method blocks until input data is available. end of file is detected. there is an attempt to read at least one byte.

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

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

The close method of InputStream does nothing. .  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.

 public void reset( ) throws IOException Repositions this stream to the position at the time the mark method was last called on this input stream. Marking a closed stream should not have any effect on the stream. The mark method of InputStream does nothing. For this to happen the method markSupported should return true. .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.

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

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

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

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

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.Reader class public abstract class Reader (java. This method will block until a character is available. . an I/O error occurs. or the end of the stream is reached.io) Character-oriented input stream.

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

The method will block until some characters are available.  public boolean markSupported( ) Similar to the markSupported method of InputStream class . or the end of the stream is reached.  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. May end up skipping less than n characters.

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

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

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

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

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

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

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

more bytes may be read ahead from the underlying stream than are necessary to satisfy the current read operation.in)).print(in. consider wrapping an InputStreamReader within a BufferedReader.readLine( )). To enable the efficient conversion of bytes to characters.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. System. For top efficiency. For example: BufferedReader in = new BufferedReader(new InputStreamReader(System.out. .

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

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

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

 public BufferedReader(Reader in. The buffer size may be specified.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. or the default size may be used. The default is large enough for most purposes. buffering characters so as to provide for the efficient reading of characters. and lines.

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

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 .

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

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

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

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

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

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

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

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

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

.g.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. e.out)). Writer out = new BufferedWriter(new OutputStreamWriter(System.

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

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

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

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 length) Methods of Reader class defined here.CharArrayReader class CharArrayReader(char[ ] buf) CharArrayReader(char[ ] buf. int offset.

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

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. int off. 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.

close method. boolean append) FileOutputStream(String name) FileOutputStream(String name. boolean append) You will find write methods.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 .

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

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

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

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

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

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

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

"rws³ Open for reading and writing. "rwd" Open for reading and writing. 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". and also require that every update to the file's content be written synchronously to the underlying storage device. Invoking any of the write methods of the resulting object will cause an IOException to be thrown. as with "rw".RandomAccessFile class Mode "r³ Open for reading only. "rw³ Open for reading and writing.

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

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.Java Networking DNS maps the domain name to the IP address. If a domain name can be mapped to multiple numeric addresses then the host is called multi-homed host.

ac.g.in.vit.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. In Java a socket is an object that encapsulates this abstraction. . Socket s = new Socket(www. int portno) throws UnkownHostException. 80).

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

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

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

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

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

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. . given the host's name. public static InetAddress getByName(String host) throws UnknownHostException Determines the IP address of a host.

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

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

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

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

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. void send(DatagramPacket dp) Writes datagram packet to datagram socket void receive(DatagramPacket dp) Reads datagram packet from datagram socket . DatagramSocket(int port. InetAddress laddr) Creates a datagram socket. bound to the specified local address.

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

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

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

server) in the remote machine.What should you do to develop and test RMI application?  Develop an interface containing the method(s) to be invoked.rmi). This class facilitates export of object from the remote machine to the local machine. . The interface should be developed in the local as well as in the remote machine.  Develop a class that implements this interface and extends the API class UnicastRemoteObject (java.  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.rmi. A public default constructor in this class is mandatory.

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

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

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

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

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

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

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

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

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

UPDATE or DELETE statement.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.  public int executeUpdate() throws SQLException Executes the SQL statement in this PreparedStatement object. which must be an SQL INSERT. . or a DDL statement.

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

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 .

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

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

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

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 .References  Thinking in Java. Bruce Eckel  java.sun.

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

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

g. . the program catches the event. This is why if you want a window-based program to do a job repeatedly (e. It cannot keep control with itself for a prolonged interval. animation) then you need to run an additional thread of execution.Console-based program vs. All window-based programs are event-driven. Whenever an event occurs. takes necessary actions and immediately returns control to the runtime system. 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.

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

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

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

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

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)  public void setBackground(Color c) This method changes the back ground color of this component.  public Color getBackground( ).awt. The default back ground color of a component is light grey and fore ground color is black.  public void setForeground(Color c) This method changes the fore ground color of this component.Component class  Component class (java.

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

int w. int w. calls update which in turn calls paint method.Component class  public void repaint( ) redraws this component. 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. int left. int left. int h) draws a portion of this component defined by the top left corner and the width and height. int top.  public void repaint(int top.  public void repaint(long ms.

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

method is called by the browser or the appletviewer only once when the applet class file is loaded. 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.Applet class  public Applet( )  public void init( ) initialize 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.  URL getCodeBase( ) returns the base directory of the applet class file. .Applet class  public void destroy( ) removes the applet from the client`s memory.

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

The url that is passed as an argument must specify an absolute URL. ‡ void play(URL url) ± Plays the audio clip at the specified absolute URL . ‡ AudioClip getAudioClip(URL url) ± Returns the AudioClip object specified by the URL argument.Applet class AppletContext getAppletContext( ) returns the context the applet is running. 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> .

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

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

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

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

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

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

int index) void remove(int index) void add(String item.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) int getSelectedIndex( ) int getItemCount( ) void select(String item) void remove(String item) void removeAll( ) .

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

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

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.

TextField class An object of this class is a single-line edit control. 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. void setEchoChar(char ch) boolean echoCharIsSet( ) char getEchoChar( ) retrieves the echo character.

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

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

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

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

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

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.

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

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

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.

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

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.Changing layout of a container The default layout of a frame and window is border layout.

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

A case study .

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

Delegation event model In this model. The listener waits until it receives an event. Once received. 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. A user interface element is able to delegate the processing of event to a separate piece of code. . 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 processes the event and then returns. a source fires an event and sends it to one or more listeners.

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

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

g. VK_SHIFT . VK_A. 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) . If there is no character associated with the key then CHAR_UNDEFINED us returned. VK_B.

An adapter class is a default implementation of listener interface.Adapter class If a listener interface has multiple methods (e. keyReleased. If you use adapter class you don`t have to define all the methods of the interface. 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). .g. keyTyped) then you find an adapter class for the 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 .

Window event A window event is fired when a window is iconified/deiconified/opened/cloded/closing/activated/deactivated/ gain focus/lost focus. 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 . The WindowEvent class encapsulates window event.

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 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. . menus.Menu bar.

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

Menu bar. e. 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.add(item1) . menus.menu. new MenuShortcut(KeyEvent.g.VK_L. true) CheckboxMenuItem( ) CheckboxMenuItem(String label) CheckboxMenuItem(String label. boolean shiftRequired) e.g. MenuItem item = new MenuItem(³Line´. menu items & check box menu items MenuShortCut(int key) MenuShortCut(int key.

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).g. mbar.add(menu). menus.g. adds mbar to this object . For adding menu bar to the container use void setMenuBar(MenuBar mbar) @ Frame class e. e.Menu bar.

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

Sign up to vote on this title
UsefulNot useful