You are on page 1of 116
We VTU Heaven 7™ sem CSE/ISE IHOK KUMAR K : lob: 9742024066 E-mail: célestialcluster@gmail. com VTU B.E NOTES (ALL SEM and ALL BRANCHES) ARE AVAILABLE. FORE MORE INFORMATION VISIT w vtuheaven.50webs:com Administrator: ASHOK KUMAR K Please visit www.vtuheaven.50webs.com for more information regarding all the notes (source, profile of author etc). \We are working towards getting all the notes (all branches and all sem) into the catalog so that it may help many of the students from various branches. Vtuheaven welcomes any students or lecturers who are interested to provide their own notes (any sem, any branch, any jistrator or any subject) to the dealers. Please contact the adi member of our team for further details. Vtuheaven also welcomes other dealers who are interested in taking part in this action. Such dealers can contact the administrator or any member of our team for further details. Any inconvenience with any of our dealers can be notified to our team. Please give us your feed back through a phone call or through. an E-mail to our team members. Note: Source for Unit 1 and unit 2 notes is INTERNET, and they are not prepared by AAHOK KUMAR K UNIT INTRODUCTION TO JAVA: Java and Java applications; Java Development Kit (JDK); Java is imerpreted, Byte Coie, IVM3 Objectoriented programming; Simple Java programs. Data types and other tokens: Boolean variables, int, tong, char, operatars, arrays, white spaces, literals, assigning values; Creating and destroyingobjects; Access specifiers. Operators and Expressions: Arithmetic Opesttors, Bitwise rators, Relational operators, The Assignment Operator, The? Operator; Operator Precedence; TOU RASARHRRTIpS casting, Stings Contol Statements: Selection statements eration statements, Jump Statements. 1. Java Development Kit (JD. that conform to, the Java Coré over versions. ‘The Java Development Kit lets us write applets and applicatior API. ILincludesimprovernents in functionality, performance, and qu The Java Development Kit (JDK) is 2 Sun Microsystems product aimed at Java developers. Since the Introduction of Java, t has been by far the most widely used Java SOK, Sun announced that it would be released under the GNU General Public License (GPL], thus makingit free software. ‘The 3DK has asits primary components a selection of programming tools, including: java ~ The loaider for J9va applications. This tool is an interpreter and can interpret the class files» Benerated ly the javic compiler. Now a single launcher is used for both development and deployment. The old deployment launcher, jre, no longerlupdate} comes with Sun JOK. Javac~ The compiler, which converts source code into Java bytecode jar ~ The archiver, which packages related class libraries into a single JAR file. This tool also heips manage JAR files. javadoc ~ The documentation generator, which automatically generates documentation from source code comments jdb —The debugger Jrunscript ~ Java command line script shel, ‘There other various other components which are described in many versions. 2. Java is interpreted, Byte Code, JVM Jevois Interpreted 2 foot caalinetion '> > standalone nrmatagn that executes using the java interpreter. “Sra enais ne creation of erossplatform royale compat Se at nt bytecode. This Cove can be inkrpreted on any system that ove a Leva Vitus Machine. Most previous attempts ‘at crossplafore solutions have done So atthe expense of performance. wile Rise that Java Was engineered fr interpretation, the Java bytecode wat carehily designdd so that t would be éasy to translate direct ito ative machine code for very high perlormanos by using @ joskinime compile. Java run-ime systems that prove tis {eal tose none of the benefits ofthe platform independent code. “High-Perlormance cross-patfornis no longer 2h oxymaran. The Bytecode ‘The key thal alows Java a sake beth the securly and the porabiliy problems just descabes fs that me output of 3 ave compiler Is not executable code. Rather, «is bytecode. Eyrecode ie a highly optimized 2 ok strocvons ‘esigned to be executed by the Java runwime system, which © ealed te vaya Vitval Machine (VAN. Thats, 6s ‘stand fim, te JVM an preter fr bytecode, JVM The JVM is an abstract computing machine, having an instruction set that uses memory. Virtual machines are often wsed to implement a programming language. The SVM 4s the comerstone of the Java peogramsning language. It is responsible for Java's cross-platform portability and the small size of its compiled code. The Solaris SVM is used to execute Java applications. The Java compiler, javac, outputs bytecodes and puts them into a .class file. The JVM then interprets these bytecodes, which can. then be executed by any JVM implementation, thus providing Java's cross-platform portability. The next two figures illustrate the traditional compile-time environment and the new portable Java compile-time environment. 3. Objectoriented programming Object-oriented programming is at the core of Java. In fact, all fava programs are objectoriented— this isn’t an option . ‘The Three OOP Principles All object-oriented programming languages provide mechanisms that help us implement the object-oriented model, They are encapsulation, inheritance, and polymorphism. ee a. Encapsulation Encapsulation is the mechanism that binds together code and the dat both safe from outside interference and misuse. manipulates, and keeps. Jn Java the basis of encapsulation is the class. A class defines the structure and behavior (data and code) that will be shared by a set of objects, Each object of 3 given class contains the structure and behavior defined by the class, as if it were stamped out by a mold in the shape of the class. For this reason, objects are sometimes referred to as instances of a class. Thus, a class is a logical construct; an object has physical reality When we create a class, we will specify the code and data that constitute that class. Collectively, these elements are called members of the class. Specifically, the data defined by the class are referred to as member variables or instance variables. ‘The code that operates on that data is referred to as member methods or just methods. Example : consider the automatic transeaission on an autotnabile. ft encapsulates hundreds of bits of information about your engine, such as how much you are accelerating, the pitch of the surface you are on, and the position of the shift lever. You, as the user, have only one method of affecting this complex encapsulation: by moving the gear-shift lever. You can’t affect the transmission by using the tum signal or windshield wipers, for example. Thus, the gear-shift lever is a well-defined (indeed, unique) interface to the transmission. Further, what occurs inside the transmission does not affect objects outside the transmission. For example, shifting gears oes not tum on the headlights! Because an automatic transmission is encapsulated, dozens of car b. Inheritance Inheritance is the process by which one dbject acquires the properties of another object Example: Child inheriting the properties of the parent. © Polymorphisms Polymorphism (from the Greek, meaning “many forms”) is a feature that allows one interface to be used for a general class of actions. Consider a stack (which is a last-in, first-out list), We might have a program that requires three types of stacks. One slack is used for integer values, ‘one for floating-point values, and one for characters. The algorithm that implements each stack is the same, even though the data being stored differs. By polymorphism, in Java we-can specify a general set of stack routines that all share the same names. More generally, the concept of polymorphism is often expressed by the phrase “one interface, multiple methods.” 4. Simple Java programs e : ‘This is a simple Java program. Call this file "Pate.java". oT class Pate { : 1 Your program begins with a call to main(). public static void main(String args[J) { System.out.printin("Welcome to Pate and Java classes.” } } Compiling the Program execute the compiler, javac, specifying the name of the source file on the command line, as shown here: ‘Coejavac Pate java. ‘The javac compiler creates a file called Pate.class thet contains the bytecode version of the Program. To actually run the program, we must use the Java interpreter, called java. To do so, we pass the lass name pate as a command-line argument, as shown here: Cabjava Pate ‘When the program is run, the following output is displayed: Welcome to Pate and Java classes ‘The Java program above is stored as Pate,java also known as source file. \ 5. Data types and other tokens There are four grdups of Data Types: a. Integers Java defines four integer types: byte, short, int, and long. All of these are signed, positive and negative values. Java does not support unsigned, positive-only integers. * The width and ranges of these integer types vary Widely, as shown in this table: Name Width Range Long 64 _ ~9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 int 32 -2,147,483,648 to 2,147,483,647 short 16 ~32,768 to 32,767 byle 8-128 t0 127 byte : The smallest integer type is byte. This is a signed 8-bit type that has a range from ~128 to 127, Variables of type byte are especially useful when yoir're working with a stream of data from a network or file. Syntax: byte variablename; short : This isa signed 16-bit type. 1 has a range Srox~32,768 ta 32,767. This type is mostly applicable to 16-bit omputers, Syntax: short variablename; Int: The most commonly used inteyer type is int It a signed 32-bit type that has @ range from ~2,147,483,648 to 2,147,483,647. In addition to other uses, variables of type int are commonly employed to control toops and to index arrays. Syntax: int variablenames Tong Jong is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. Syntax: long variablename; Example : 1/ Compute distance area of a rectangle. class Rectangle { public static void main(String args(]) { int length=57; No int height=32; double area=0.5" length* height System.out.print(" Area of a Triangle is :" + double); b, Floating-point numbers This group includes float and double, which represent numbers with fractional precision. float: This specifies a single-precision value that uses 32 bits of storage. Variables af type float are useful when you need a fractional component, but don’t require a large degree of precision. ‘Syntax: float variablename; Double precision, as denoted by the double keyword, uses 64 bits to store a value. Syntax: double variablename; Example: i Compute the area of a circle. class Circle { public static void main(String args(}) { double pi, ra; 0.8; // radius of circle 3.14165 // pi, approximately pir *15// compute area Syster.out.printin(” Area of circle is" + a}; } ©. Characters This group includes char, which represents symbols in a character set, like letters and numbers Java char is a 16-bit type and the range of a ehar is 0 to 65,536. Since Java is designed to allow applets to be written for worldwideuse, it makes sensé that it would use Unicode to represent characters. ‘Syntax: char variablename; Examples 1/ Demonstrate char data type. class HelldJava { public static void main(String argsf)) { char cht = ‘hello’ char ch2 = Java's ‘System.outprintln(chl + "" + ch2}; ) 6. Boolean This group includes boolean, which is a special type for representing true/false values. this is the ype returned by all relational operators, such as a b) System.out.print(“The greatest is 2” 3}; else Sysiem.outprint(“The greatest is 2” +b); ‘A nested if is an if statement that is the target of another if or else. Example: inti=l; int j=; iti) ¢ if j == 1) System.out print(“equal :” + j); Else System.out print(*Not equal :” + j); j else { System.out print(-Not equal :” - ) op equal: 1 we can also sequence of nested ifs which is an if-else-if ladder. sffeondition) statement: else if(condition) statement; . * else statement switch Statement : ‘The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the valwe of an expression. As such, it often provides a better altemative than a large series of if-else-if statements. Here is the general forrh ‘of a switeh statement: : switch (expression) { : case value!’ 1/ statement sequence ’ break; case value2: statement sequence break; ase valueN: // statement sequence - break LJ default: : 1 default statement sequence ‘The switeh statement works like this: The value of the expression is compared with each of the literal values in the ease statements. 1f a maich is found, the code sequence following that case statement is executed, If none of the constants matches the’ value of the expression, then the default statement is executed. However, the-default statement is optional. If no case matches and no default is present, then no further action is taken. The break statement is used inside the - switch to terminate a statement sequence, When a break statement is encountered, execution branches to the first line of code that follows the entire switch statement. This has the effect of “jumping out” of the switeh, Here isa simple example that uses 3 switeh statement: 11 A simple example of the switch, class SampleSwitch { public static void main(String args{)) { = fortint switehG) { case I: Systern.out.printla” break; case 2: System.out.printin("i is equal to two 2") brea defauit: System.out.printin("i is equal to three which is taken as default"); } 3 is equal to one."); t + ob 1 js equal to one 2 is equal to two 2 is equal to three which is taken as default b. Iteration statement . | Java's iteration statements are for, while, and do-while. These stateménis create what we commonly call loops. while ‘The white 1oop is Java's most fundamental Tooping statement, It repeats a statement or block while its controlling expression is true. Here is its general Form: while(condition) { a Mody of loop The condition can be any Boolean expression. The body of the foop will be executed as long as the conditional expression is true. When condition becomes false, control passes to the next line of code immediately fallowing the loop. 1 Sum of N Numbers. class Average ( 7 public static void mnain(String args{)) { System.out printin("Sum of Nembers is " + sum); } J ofp : Sum of Numbers is 6 dowhile "*S ‘The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop. Its genera) form is dot II body of ) while (conditions Each iteration of the do-while loop first executes the body of the toup and then evaluates the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with ait of Java's loops, omndition must be a Boolean expression Example : class Dowhile { public static void main(String args{)) { int i=l; dof System.out println("Numbers is "+ i); ey Jwhile(i>=3); ofp : Numbers is $ for ‘The general form of the for statement: for(initialization; condition; Iteration) ( A body 3 ‘The for loop wperates as follows. When the loop first stars, the initialization portion of the leop is executed. Generally, this is an expression that sets the value of the loop control variable, ‘which acts as a counter that controls the loop . Next, condition is evaluated, This is a Boolean expression. It usually tests the loop control variable against a target value. If this expression is. true, then the body of the loop is executed. If it is false, the loop terminates. Next, the iteration portion of the loop is executed. This is usually an expression that increments or decrements the loop control variable..The loop then iterates, first evaluating the conditional expression, then execnting the body of the loop, and then executing the iteration expression with each pass. This process repeats tntil the controlling expression is false. {7 Sum of N Numbers. class Averige { public static void main(String args(3) { int sum=0; forfint i=L5i<=3,i+4) sum=sum tis ‘System.out printin("Sumn of Numbers is + sums o/p : Sum of Numbers is 6 8. Jump Statements There are three types of jump statement break, continue, and return, These statements transfer control to another part of your program. weak to Exit'a ce By using break, we can force immediate tetmination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When @ break statement is encountered inside a loop, the loop is terminated and program control resumes, at the next statement following the loop. Here is a simple example: 1 Linear search class Search { public static void main(String args{l) { int al}=(3,6,9); int key=6; Boolean b=false; forlint 0513554) { break; betru; } ) Ite) System.out printin("Element Found "); Else System. out printIn("Element Not Found "); } } O/P : Element Found In the above example the loop terminates as soon as the element is found, Using continue Sometimes.it is necessary to force an early iteration of a loop. That is, we might want to continue running the loop, but stop processing the remainder of the code in its body for this particular iteration. This is, in effect, a goto just past the body of the loop, to the loop’s end. The continue statement performs such an action, Here is an example program that uses continue to cause two numbers to be printed on each line: 1/ Demonstrate continue. class Continue { public static void main(String argsf) { . forfint i=0; 1<10; 1449 { System.out.prini(i +"): if (%2 == 0) continue; System out printin("); ) This code uses the % operator to check i newline, Here is the output from this program: or 23 45 . 67 89 ever. If it is, the loop continues without printing 9 rn; ‘The last control statement is return, The return statement is used to explicitly return from a method, That is, it causes program control to transfer back to the caller of the method. Thus, the return statement immediately terminates the method in which it is executed, The following example illustrates point. Here, M Demonstrate continue, class Continue { public static void max (ed) retum a else return bt : a,int b) { public static void main(String argsf) { int m=(2,3); ‘System.outprintia("The Max is" +m); UNIT-2 CLASSES, INHERITANCE, EXCEPTIONS, APPLETS: Classes: Classes in Java; Declaring a class; Class name; Super classes; Constructors; Creating instances of class; Inner classes. Inheritance: Simple, multiple, and multilevel inheritance; Overtiding, overloading. Exception handling: Exception handling in Java. The Applet Class: Two types of Applets; Applet basics; Applet Architecture; An Applet skeleton; Simple Applet display methods; Requesting repainting; Using the Status Window; The HTML APPLET tag, Passing parameters to Applets; getDocumentbase() and getCodebase(); ApletContext and showDocument(); The AudioClip interface; The AppletStub Interface; Output to the Console. 1. Classes in Java: A class is a template for an object, and an object is an instance of a class. A class is declared by use of the class keyword. The classes that have been Used up to this point. are actually very limited examples of its complete form. Classes can (and usually do) get much more complex. The general form of a class definition is shown here: ass classname { type instance-variable 1; type instance-variable2; a type instance-variableN: type methodname (parameter-list){ 1/ body of method } ype methodnamea(parameter-ist) { 1! body of method } Wane type methodnameN(parameter-list) { body of method 3 } Methods: Here, type specifies the type of data retismed by the method. This can be any valid type, including class types that we create. If the method does not return a value, its retum type must be void. The name of the method is specified by name. This can be any fegat identifier other than those already used by other items within the current scope. The parameter-list is @ sequence of type and identifier pairs separated by commas. Parameters are essentially variables that receive the value of the arguments passed to the method when it is called. If the method has no parameters, then the parameter list will be empty. Methods that have a retuca type other than void return a value to the calling routine using the following form of the return statement: return value; ‘The data, or variables, defined within a class are called instance variables. The code is contained within methods. Colfectively, the methods and variables defined within a class aré called members of the class, In most classes, the instance variables are acted upon and accessed by the methods defined for that class. Thus, it is the methods that determine how a class’ data can be used. Variables defined within a class are called instance variables because each instance of the class (that is, each object of the class) contains its own copy of these variables. Thus, the data for one object is separate and unique from the data for another. All methods have the same general form as main( ), which we have been using thus far. However, most methods will not be specified as static or public A Simple Class Here.is a class called Box that defines three instance variables: width, height, and depth. Currently, Box does not contain any methods (but some will be added soon). class Box ( double widtns double height; double depths } As stated, a class defines a new type of data. ih this case, the new data type is called + Box. We will use this name to declare objects of type Box. It is important to remember that a class declaration only creates a template; it does not create. an actual object. Thus, the preceding code does not cause any objects of type Box to come into existence. To actually create a Box abject, we'will use a statement like the following: Box mybox * new Box(); // create a Box object called mybox After this statement executes, mybox wilt be an instance of Box. Thus, it will have ‘physical’ reality. To access these variables, we will use the dot (:} aperator. The dot operator links the name of the object with the name of an instance variable. mybox.width = 100; class Box { double width: - double height; double depth; J/ display volume of a box void volumet) { System.out.print ("Volume is "); System.out.printin(width * height * depth); 1 i class BoxDemo { public static void main(String args[]) { Box myboxl = new Box(); Box mybox2 = new Box (); // assign values to myboxl's instance variables myboxi.width = 10; myboxl.height = 20; myboxl.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 37 mybox2.height = 6; mybox2.depth = 9; // display volume of first box mybox1. volume () ; // display volume of second box mybox2 -wolume () ; } fp: Volume is 3000.0 Volume te4162.0 2. Declaring a class when we create a class, we are creating a new data type. we can use this type to” declare objects of that type. However, obtaining objects of a class is'a two-step process. First, we must declare a variable of the class type, This variable does not define an object. instead, it is simply a variable that can refer to an abject. Second,we must acquire an actual, physical copy of the object and assign it to that variable. We can do this using the new operator. The new operator dynamically allocates (thatis, allocates at. run time) memory for an object and ceturns a reference,to it. This reference is, more or less, the address ih memory of the object allocated by new. As explained above, the new operator dynamically allocates mernory for an object. It has this general form: class~var = new classname); Here, class-var is a variable of the class type being created. The classname is the name of the class that is being instantiated. The class name followed by parentheses specifies the constructor for the class. A constructor defines what occurs when an object of a class is created. Example: Box mybox = new Box ()i It can also be defined as Box mybox; // declare reference to object mybox = new Box(); // allocate a Box object The first line declares mybox as a reference to an object of type Box. After this line executes, mybox contains the value null, which indicates that it does not yet point to an actual object. Any attempt to use mybox at this point will result in a compile-time error. The next line allocates an actual object and assigns a reference to it to mybox. After the second line executes, we can use mybox as if it were a Box object. But in reality, mybox simply holds the memory address of the actual Box object. The effect of these two lines of code is depicted in Figure below Setment ict ox on eal spybot Bot 3. Constructors A constructor initializes &n object immediately upon creation. It hag the same name as the class in which it resides and is syntactically similar to a method. Once defined, the Constructor is automatically called immediately after the object is created, before the new operator completes. Constructors look a litle strange because they have ne return, type, not even void. This is because the implicit retum type of a class’ constructor is the class type itself. It is the constructor’s job to initialize the internal state of an object 50 that the code creating an instance will have a fully initialized, usable object immediately. /* Here, Box uses a constructor to initialize the dimensions of 4 box. / class Box { double width; Souble height; double depth; // This is the, constructor for Box. Box() { . System, out.printin ("Constructing Box"); width = 10; heignt = 10; depth = 10; G H // compute and return volume double volume() 4 return width * height * depth; ; . y class BoxDemo { public static void main(string args{]) ( // declare, allocate, and initialize Box objects Box myboxl = new Box ()z Box, mybox2 = new Box()}; double vol; // get volume of first box vol = fybox1. volume () 7 i system,out.printin(*Volume is " + vol); 11 get volume of second box vol = mybox2.volume (); system,out.printin("Volume is " + vol); ' } ‘When this program is run, it generates the following results: Constructing Box Constructing Box Volume is 1000.0 Volume is 1000.0 Parameterized Constructors. c While the Box( ) constructor in the.preceding example does initialize a Box object, not very useful—all boxes have the same dimensions. What is needed is a way to construct Box objects of various dimensions. The easy solution is to add parameters to the constructor. As we can probably guess, this makes’ them much more useful. For example, the following version of Box defines a parameterized constructor which sels the dimensions of a box as specified by those parameters. Pay special attention to how Box objects are created. /* Here, Box uses a parameterized constructor to initialize the dimensions of a box. / i class Box { double width; double height; double depth; // This is the constructor for Box. Box {double w, double h, double d) [ width = w, height = hs y depth = a; ) // compute and return volume : double volume() { return width + height * depth; } , class Roxpemo { public static void main(String args{]) { // declare, allocate, and initialize Box objects Box myboxl = new Box(10, 20, 15); Box mybox2 = new Box (3, 6, 9); doub}e vol; a2 // get volume of first box vol » mybox1.volume(); System.out.printin("Volume is " + vol); ff get volume of second box yol = mybox2.volume() 7 System.out.printin ("Volume is " + vol): } ; “ The output from this program is shown here: Volume is 3000.0 Volume is 162.0 The this Keyword Sometimes a method will need to refer to the object that invoked it. To allow this, Java defines the this keyword. this can be used inside any method to refer to the current: object. That is, this is always 4 reference to the object on which the method was invoked. We can use this anywhere a reference to an object of the current clase’ type is permitted. To better understand wnat this sefers to, consider the following version of Box( ) 1 ® redundant use of this. Box (double w, double h, double d) { this.width = wr tbisvheight = hy this.depth = di ) The finalize( ) Method Sometimes an object will need to perform some action when it is destroyed. For example, if an object is holding some non-Java resource such as a file handle or window Character font, then we might want to make sure these resources are freed before an object is destroyed. To handle such situations, Java provides a mechanism called finalization. By using finalization, we can define specific actions that wil occat when an object is just about to be reclaimed by the garbage collector. To add a finalizer to a class, we simply define the finalize( ) method. The Java run time calls that method whenever it is about to recycle an object of that class. Inside the finalize( ) method we will specify those actions that must be performed before an object ig destroyed. The garbage collector runs periodically, checking for objects that are.no longer referenced by any running state or indirectly through other referenced objects. Right before an asset is fredd, the Java run time calls the finalize( } method on the object. The finalize( ) method has this general form: protected void finalize, ) { IIinalization code here » 4, Inner Classes The most important type of nested class is the inner class. An inner class is a nion-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the, sare way that other non-static members of the outer class do. Thus, an inner class is fully within the scope of its enclosing class. The following program illustrates how to define and use an inner class. The class named Outer has one instance variable named outer_x, one instance method named test( ), and defines one inner class called Inner. // Demonstrate an inner class. class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); ) // this is an inner class class Inner { void display() { System.out.printIn("display: outer_x =" + outer_x); i ) class InnerClassbemo { public static void main(String args(]) { E Outer outer = new Outer(}; . outer. test ()7 } a } Output from this application is shown here: display: outer_x = 100 A lass that is inherited is called a superclass. we §. Inheritance Basics To inherit a class, we simply incorporate the definition of one class into another by using the extends keyword. To see how, let's begin with a short example. The following program creates a superclass called (A and a subclass called \B, Notice how the keyword extends is used to create a subclass of A. // B simple example of inheritence. // Create a superclass. class A { int i, 37 _ woid showij() { System.out.printin(*i and J: "+i +" "+ 3)7 J J J/ Create a subclass by extending class A. B extends A [ 7 int ke void showkt) 1 system.out.printin("k: "+ k); void sum) { System.out-printin("itjtk: "+ (itjtk))s ) Simpletoheritance ( pubic static void main(strihg args (1) ( Ob = new AC: bob = new BO)? superclass may be used by itself. pecOb.i 10; ‘ superdb.j = 207 System.out.printin ("Contents of superdb: *)> superdb, showi3 (07 systemayt -printin() 7 /* The subclass has access to all public members of its superclass. */ ‘ subd. = 7; ‘ Ob.5 = 8; subOb. k= 97 system.out.printin("Contents of subOb: svb0b. showis () 5 Bubb. showk () ; System.out.printin(); System.out.printIn("Sum of i, 3 and k in subob’ SubOb. sum() 7 } The output from this program is shown here: Contents of superOb: i and j: 10 20 Contents of subdb: iand 3:78 k: 9 Som of i, j and k in subOb: ivi+k: 24 Member Access and Inheritance Although a subclass includes all of the.members of its superclass, it cannot access those members of the superclass that have been declared as private. For example, consider the following simple class hierarchy: /* In a class hierarchy, private members remain private to their class This program contains an error and will not compile, " // Create a superclass. class A { int i; // public by default private int 3; // private toa void setij(int x, int y) [ ie x; oy] } ) 7/ B's 4 is not accessible here. class B extends A { int total; void sum() { total = i + 4; // ERROR, j is not accessible here } } ‘class Access ( public static void main(String argsi1) i B subOb = new B(); sub0b-setij (10, 12); subOb. sum(); System. out.print1n("Total is " + sub0b.total); } . } a ‘This program will not compile because the reference to j inside the sum( ) method of B causes an access violation. Since j is declared as private, itis only accessible by other members of its own class. Subclasses have no access to il. super Whenever @ subclass needs to refer to its immediate superciass, it can do so by use of the keyword super. super has two general forms. The first calls the superciass’ constructor. The second is used to access a member of the superclass that has been hidden by a member of a subclass. Each use is examined here. super to Call Superciass Constructors ‘A subelass can call @ constructor method defined by its superclass by use of the ‘oilowing form of super: supes(perameter-list): Here, parameter-ist specifies any parameters needed by the constructor in the superclass. super( ) must always be the first statement executed inside a subclass’ constructor. To see how super( )is used, consider this improved version of the BoxWeight{ ) class: fivight now uses super to initialize its Box attributes. class BoxWeight extends Box. { double weight; // weight of box J/ inibielize width, height, and depth using super () HoxWeightidouple w, double h, double d, double m) { super (w, hy d); // call superclass constructor Second Use for super ‘The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used, This usage has the following general form: super.member Here, member can be either a method o¢ an. instance variable, This second form of ‘super is most applicable to situations in which member names of a subclass hide members by the same name in the superclass. Consider this simple class hierarchy: // Using super to overcome name hiding. class A [ int i; 1 // Create a subclass by extending class aA. class B extends A { int i; // this i hides the i in A B(int a, int b) { super.i =a; // i ina i=b; //i ine void show() ( system.out.printin("i in superclass: "+ super.i); System.out.printin("i in subclass: “+ i); S ) a i class UseSuper { public static void main(string args{]) { B sub0b = new BI, 2); sub0b. show () ; } , This program displays the following: i in superclass: 1 iin subclass Multilevel Hi Given three classes called A, 8, and C, C can be a subclass of B, which is a subclass of A. When this type of situation occurs, each subclass inherits aif of the traits found in “ all of its superclasses. In this case, C inherits all aspects of B and A. This scenario of inheriting classes in multilevel hierarchy is known as Multilevel inheritance. To see how. a multilevel hierarchy can be useful, consider the following program. In it, the subclass BoxWeight is used as a superclass to create the subclass called Shipment. Shipment inherits all of the traits of BoxWeight and Box, and adds a field called cost, which holds the cost of shipping such a parcel, // Extend BoxWeight to include shipping costs. // Start with Box. class Box { private double width; private double height; private double depths // construct clone of an object Box (Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; astructor used when all dimensions specified Box {double w,, double h, double d) { /é constructor used when no dimensions specified Boxt) { // use -1 to indicate // an uninitialized J box ctor used when cube is created bie len) { height = depth = len; // compute and return volume Souble volumeQ { return width * height * depth; : ‘ i S /7 Add weight. Class Boxieight extends Box { double weights // weight of box // construct ‘clone of an object BoxWeight (BoxWeight ob) { // pass object to constructor super (ob); ob.weight; // constructor when all parameters are specified BoxWieight (double w, double h, double d, double m) { superiw, h, d)z // call superclass constructor weight = m; y // default constructor BoxWeight () [ super (); weight = } // constructor used when cube is created BoxWeight (double len, double m) { super (len); weight = mz } ) /f Add shipping costs class Shipment extends Boxiteight { double cost; 71 constract clone of an object Shipment (Shipment ob) { // pass object to constructor super (ob) ; ; cost = ob-costs ) // constractor when all parameters are specified Shipment (double w, double h, double a, G double m, double c) { super(w, h, d, m; // cali superclass constructor cost = c; : y // default constructor | Shipment () { \ super (); cost ) t // constructor used when cube is created Shipment (double len, double m, double c) { super (len, m); cost = c7 1 1 class DemoShipment { Public static void main(String argsi}) { Shipment shipment1 = new Shipment (10, 20, 15, 10, 3.41); Shipment shipment? = new Shipment(2, 3, 4, 0.76, 1.28)7 double vols vol = shipment1.volume(); System.out.println{*Volume of shipmentl is " + vol); System.out.printin("Weight of shipmentl is * a + shipment .weight) ; system.out.print1n ("Shipping cost: §" + shipmenti.cost); System. out.printin(); vol = shipment2.volume(); System.out.printin("Volume of shipment2 is " + vol); i System.out.printIn("Weight of shipment2 is " + shipment2.weight) ; System. out .printin("s ) } hipping cost: $" + shipment2,cost); ‘The output of this program is shown here: Volume of shipment is 3000.0 Weight of shipment1 is 10.0 Shipping cost: $3.41 Volume of shipment2 is 24.0 Weight of shipment2 is 0.76 Shipping cost: $1.28 6. Method Overriding lo @ class hierarchy, when @ method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. When an overridden method is called from witht a subclass, it will always rater to the version of that method defined by the subsiass. i The version of the method defined by the superclass will be hidden. Consider the following: // Method ovtbviding. class A ( int i, 5; Aint a, int b) t tea; jab: \ // display i and 5 void show() { System, out.printin("i and ) } made a gs class B extends A [ int kz Blint a, int b, int c) ( super la, ); kec // display k - this overrides show() in A void show() { System.out.println("k: " + k); ) ) class Override { public static void main(String args{]) { B subdb = new B(1, 2, 3)7 subOb.show(); // this calls show() in B i ) When show{ ) is invoked on an object of type B, the version of show( ) defined within B is used. That is, the version of show ) inside B overrides the version declared in A. ‘Method overriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded. For example, consider this modified version of the preceding example: /{ Methods with differing type signatures are overloaded ~ not // overridden. class A { int i, 37 A(int a, int b} 4 3 // display i and 3 void show() { System.out.printin("i and 5 ) } // Greate a subclass by extending class A. class B extends A [ int k; + B(int a, int b, int c) { super (a, b)7 kao; ) // overload show() void’ show (String msg) ( System. out.print1n(msg + k); ) Sa ) class Override { public static void main(String args{]) { B subob = new B(1, 2, 3); bab eS): subOb.show("This is k: "); // this calls show() in B subdb.show(); // this calls show() in A ) ) The output produced by this program is shown here: This is k: 3 and j: 12 The version of show( ) in B takes 4 string parameter. This makes its type signature different from the one in A, which takes no parameters. Therefore, no overriding (or name hiding) takes place. Applying Method Overriding Let’s look at a more practical example’ that uses method overriding. The following program creates a superclass called Figure that stores the dimensions of various two- dimensional objects, It also defines a method called area( ) that computes the area of an object. The program derives two subclasses from Figure, The first is Rectangle and the second is Triangle. Each of these subclasses overrides area( ) so that it retums the area of a rectangle and a triangle, respectively. // Using run-time polymorphism. class Figure { double dim; double dim2; Figure(double,a, double b) ieee dim2 = by . double areat) { system. out.printIn ("Area for Figure is undefined."); return ) class Rectangle extends Figure { Rectangle(double a, double b) { soper(a, b) } // override area for rectangle double areat) 4 System.out.printin("Inside Area gor Rectarigle-")7 return dimi * din2; ) } class Triangle extends Figure ( angle(double a, double b) ( super (a, b)i } // override area for right triangle double area() { System.out -printin("Inside Area. for Triangle."); return diml * dima / 2; y ) Glass FindAreas { public static void main(String args{1) { Figure f = new Figure(10, 10); Rectangle r = new Rectangle (9, 5}; Triangle t = new Triangle(10, 8); Figure figref; figref = x7 System.out.println("Area is " + figref.area()): figref = t; System.out.println("Area is " + figref.area()); figref = £; System.out.printin("Area is " + figref.area(}); ) ) : The output fram the pragram is shown here: Inside Area for Rectangle. Area is 45 Inside Area for Triangle. Area is 40 Area for Figure is undefined. Area is 0 Through the dial mechanisms of inheritance and sur-time polymorphism, it is possible to define one consistent interface that is used by several different, yet related, types of objects. In this case, if an object is derived from Figure, then its area can be obtained ‘by cafling area ). The interface 10 this operation is the same no matter what type of figure is being used. 7. Overloading Methods Overloading is a concept where two or more methods within the same class share the same ‘name, and their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java implements polymorphism. method overloading is one of Java’s most exciting and useful features. When an overloaded method is invoked, Java uses the type and/or number of arguments as its guide to determine which version of thie overloaded method to actually call. Thus, overloaded methods must differ in the type and/or number of their parameters. While overloaded methods may have different return types, the return type alone is insufficient to distinguish two versions of a method. When Java encounters a call to an overloaded method, it simply executes the version af the method whose parameters match the arguments used in the call. Here is a simple example that illustrates method overloading: // Demonstrate method overloading: rout -printla("No parameters"); // Overload test for one integer parameter. void test (int a) { system.oat.printin("a: " + a); 1 // Overload test for two {int a, int b) { printin("a and b: “+ a+" " +b); teger parameters. oad test for a double parameter st (double a) { system.out-printin ("double a: "+ ali return ata; ) i class Overload { public static void main(String args{]} { OverLoadDemo ob = new OverloadDemo(); ry = double regult; // call all versions of test () ob:test 10; ob. test (10) 7 eb-test (10, 20); result = ob.test (123.25); system-out.printIn("Result of ob. test (123.25): " + result); ) This program generates the following output: No parameters a: 10 a and b: 10 20 double a: 123.25 sult of, ob.test (123.25): 15190.5625 8. Exception-Handling ‘A Java exception is an object that describes an exceptional (that is, error) condition that has occurred in a piece of code. When an exceptional condition arises, an object, representing that exception is created and thrown in the metfiad that caused the error. ‘That method may choose to handle the exception itself, or pass it on. Either way, at some point, the exception is caught and processed, Exceptions can be generated by the Java run-time system, or they can be manually, generated by our code. Exceptions thrown by Java relate to fundamental errors that violate the rules of the Java language or the constraints of the Java execution envionment. Manually generated exceptions are typically used to report some error condition to the caller of a method. Java “exception handling is managed via five keywords: try, catch, throw, throws, and finally. Briefly, here is how they work. Program statements that we want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it js thrown. Qur code can catch this exception (using catch) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause, Any code that absolutely must be executed before a method returns is put in a finally block. This is the general form of an exception-handling block; try JI block of code to monitor for errors 1 y catch (ExceptionTypet exOb) { JH exception handler for ExceptionTypet } catch (ExceptionType2 ex0b) { 1 exception handler for ExceptionType2 + M.. finally { it block of code to be executed before try block ends } Here, ExceptionType is the type of exception that has occurred. The remainder of this chapter describes how to apply this framework. Exception Types All exception types are suiciasses of the builtin class Throwable. Thus, Throwable is at the top of the exception class hierarchy. Immediately below Throwable are two subclasses: that partition exceptions into two distinct branches. One branch is headed by Exception. This class is used for exceptional conditions that user" programs should catch. This is also the class that we will subclass to create our own custom exception types. There is an important subclass of Exception, called RuntimeException. Using try and catch Ahough the defauit exception handler provided by the Java runsime eytem is usefi for debugging, we. will usually wart {o handle an exception ourself. Doing so provides two benefits. First, it allows we to fix the error. Second, it prevents the program from automatically terminating. Most users would be confused (to say the least) if our program stopped running and printed: a, stack trace whenever an error occurred! Fortunately, it is quite easy to prevent this. To guard against and handle a run-time error, simply enciose the code that we want to monitor inside a try block. Immediately following the try block, include a catch clause that specifies the exception type that we wish to catch. To illustrate how easily this can be done, the following program includes a try block and a catch clause which processes the ArithmeticException generated by the division-by-zero error: class Bxc2 { public static void main(String args{]) ( int d, a try ( // moniter a block of code a= 05 a= 42/4, system.out.println ("This will not be printed."); ch (ArithmeticException ¢) {| // catch divide-by-zero error m.out.printin ("Division by zero"): ystem.out.printin ("After catch statement."); i This program generates the following output: Division by zero. After catch statement. Notice that the call to printin( ) inside the try block is never executed. Once an exception is thrown, program control transfers out of the try block into the catch block,” Put differently, catch is not “called,” so execution never “returns” to the try block from a catch, Thus, the line “This wil not be printed.” is not displayed. Once the catch statement has executed, program control continues with the next line in the. program. following the entire try/catch mechanism. Multiple catch Clauses In some cases, more than one exception couid be raiséd by a single piece of code. To handle this type of situation, we can specify two or more catch clauses, each catching a different type. of exception. When an exception is thrown, each catch statement is inspected in order, and the first one whose type matches that of the exception is execuled. After one catch statement executes, the others are bypassed, and execution continues after the try/catch block. The following example traps two different exception types: // Demonstrate multiple catch statements. class Multicatch { public static void main(String axgs{}) { try { int a = args.length; System.out.printin("a =" + a); int b= 42 / a; int cl) = {1}; e142} = 99; }. catch (ArithmeticException e) { System.out.printin("Divide by 0: " + e); } catch (ArrayIndexOutofBoundsException e) { System.out.printin("Array index cob: "+ e); } System.out-println("After try/catch blocks."); ) ) throw So far, we have only been catching exceptions that are thrown by the Java run-time system. However, it iS possible for our program to throw an exception explicitly, using the throw statement. The general form of throw is shown here: "throw Throwabletnstance; Here, Throwableinstance must be an object of type Throwable or a subclass of Throwable. Simple types, such as int or char, as well as non-Throwable classes, such as String and Object, cannot be used as exceptions. There are two ways we can obtain a Throwable object: using a parameter into a catch clause, or creating one with the new operator. The flaw of execution stops immediately after the throw statement; any ‘subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of the exception. Ifit does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and s0’on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace. Here is a sample program that creates and throws an exception. The handler that catches the exception rethrows it to the outer handler. // Demonstrate throw. class ThrowDeno { static void demoproct) i try { throw new NullPointerException ("demo"); } catch (NuliPointerException e) { System.out-printIn("Caught inside demoproc. throw e; // rethrow the exception os } ) public static void main(String args{}} ( try [ demoproc() } catch (MulleointerException ¢) {* System.out.printin("Recaught: " + e+ 's Built-in Exceptions ie the standard package java.lang, Java defines several exception classes. A few have been used by the preceding examples. The most general of these exceptions are subclasses of the standard type RuntimeException. Since Javatang is implicitly imported into all Java programs, most exceptions derived from RuntimeException are automatically available, Furthermore, they need not be included in any method's throws list. In the language of Java, these are called unchecked exceptions because the compiler does not check to see if a method handles or throws these exceptions. The unchecked exceptions defined in java.tang are listed in below Table Excentlon vaning ArknoneticException Asie ror, ech a8 “ividey-zeo. Armand OuOfBoyndsEsception Ama index's ourofbounds, “ArrayStoreExcepion » Assignment wo sn srry denen ofan ineompanble ype, CiaseCastEaception Invotid cas. egetdgument Exception Ig sant ao vo leg onitonsateBxception egal monitor operation, such as ‘waking on an unlocked trend. Heston Environment or pplication sin iscorectsate, Megat ThvenStateBbeeption Requested operation not compatible wwihearent head state, IndexOuOrBoundsEreeption Some ype of indexsoutotbounds NegotiveAraySize Exception ‘cay created witha negative size Applets 1. Applet Basics Ait applets are subclasses of Applet. Thus, all applets must import java.applet. Applets must also import java.awt. AWT stands for the Abstract Window Toolkit. All applets run in a window hence it is necessary to include support for that window. Applets are not executed by the console-based Java run-time interpreter. Rather, they are executed by either a Web browser or an applet viewer. But we can use any applet viewer or browser we fike. Execution of an applet does not begin at main( ). Actually, few applets even have matn( ) methods. Instead, execution of an applet is started and controlled with an entirely different mechanism, which will be explained shortly. Output to our applet’s window is not performed by System.outprintia( }. Rather, it is handled with various AWT methods, such as drawString( ), which outputs a string to a specified X,Y location, Input is also handled differently than in an application, ‘Once an applet has been compiled, it is included in an HTML file using the APPLET tag. The applet will be executed by a Java-enabled web browser when it encounters the APPLET tag within the HTML file. To view and test an applet more conveniently, simply include a comment at the head of our Java source code file that contains the APPLET tag. This way, our code is documented with the necessary HTML statements needed by ‘our applet, and we can test the compiled applet by ie */ This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels wide and 60 pixels high. Since the inclusion of an APPLET command makes testing applets easier, all of the applets will contain the appropriate APPLET tag embedded in a comment. 2. The Applet Class 1 The Applet class defines the methods shown in Table below. Applet provides all necessary’ support for applet execution, such as starting and stopping, It alsb provides methods that load and display images, and methods that load and play audio clips. ‘Applet extends the AWT-class Panel. In turn, Panel extends Container, which extends Component. These classes provide support for Java's window-based, graphical interface. Thus, Applet provides all of the necessary support for window-based Method void desroyt) AccessbContet getAcorsibleComtert) AppletContext gerapplerContext() String gevdpptesingo AudioClip gerAudioCp(URL wrt) AudioClip getAudioclip(URL url, ‘SteingelipSli) URL gerCodeBase) URL gexPocumersBase) Deseiiption Called by the browse just before ‘an applet is terminated. Your ‘apple wil overide this method iFit needs to perform any deanup price ins destruction. Returns the accesibilty context forthe evoking object Returns the context associated with the applet. Returns a string that describes the apple RRetuens an AudioClip object that encapsulates the audio clip found atthe location specified by ut. Returns an AudioClip ohjecethat encapsulates the guio eli fund a the location specified by url and having the ame specified by cipName. ‘Retumne the URE. sociated with the ‘nwobing applet «Returns the URL of the HTML document that invokes the applet. Locale getLocale() Stoing geParemeten Sting, pram eme) String! 1L] geParameteringol) vod fn» boolean isActivet) asic Gat Ad ‘new AudioClip(URL wr) Description Returns an Image object det encapsulates the image found st the location specified By uk. Retuens an lage object that ‘encapsulates the image found at whe ‘ocation specified by ur and having the name specified by imageName. Retuons a Locale object tht is uses! by various locale-eenstive classes and methods. Returns the parameter associated with paremdeme nul i serumed ifthe Specified parameter isnot found. Returns a String table that deseribes the parameters recognized by the ‘applet. Each entry inthe table mist ors of sree stings thas convain the ‘ane of the parameter, a description of tseypeand/or earge, an an planation ofits purpose, Called when an applet begins ‘execution, Jes the Bist method called for any applet. Returns tue if the applet has bees. started. Irretumns false ithe applet has been stopped. Revornsan AudioClip cbject har encapsulates the aucho clip found a the location specified by url, This method is similar to getAudioClip) excepe that it Is guatic and oan be executed without the need for an Applet object. (Added ‘by va) oy Mothod Deseription void play(URL wnt) an audio clip is found atthe location + specified byt, the clip is played. ‘void plat URL we StekagctipNome) _1Fan audio clip is found at the location ‘specified by wel with the mame specified Uy apne he lp played Resies the applet according to the dlenensians oped by dm enalon ia las ore inside Javaawt I containe wo lege elds ‘widihand height ol enti it, elt) Resies the applet according 0 the dimensions specified by wth and hah | final void setStub(AppletStub siubOb) Makes stabObj the stub for the apptet. . i “This mathod i wed by dhe run-time { system and wot usualy called by F your applet. Atubie a smal piece of Soden provides he linkage Beiveen ; Jourappketand the rownee | void showStanagsuing st) Digplystin the eats window ofthe browser or applet viewer. the Bromser doesnot suppor a tates i Window then no action kes pce. wo stat) CCl by the browser when an app nN, should star (or reeuste) execution. I is . ‘automatically eallad after) when an applet fist begins. void stopt) Catied by the browser to suspend execution ofthe applet. Once stopped, sanappltfrectated when the browwsce Calls staat) 3. Applet Architecture An applet is a window-based program. As such, its architecture is different from the so- called normal, console-based pragrams. Applets are event driven. An applet resembles a set of interrupt service routines. Here is how the process works. An applet waits until an event occurs. The AWT notifies the applet about an event by calling an evént handier'that has been provided by the applet. Once this happens, the. applet must take appropriate action and then quickly return control to the AWT. This is a crucial point. For the most part, our applet should not enter a "mode" of operation in which it maintains control. for an extended period. Instead, it must perform specific actions in response to events and then return control to the AWT run-time system. In those situations in which.our applet needs to perform a repetitive task on its own (for example, displaying a scrolling message across its, ‘window), we must start an additional thread of execution. ‘The user initiates interaction with an applet—not the other way around. As we know, in a nonwindowed program, when the program needs input, it will prompt the user and then call some input method, such as readLine( ). This is not the way it works in an applet. Instead, the user interacts with the applet as he or she wants, when he or she wants. These interactions are sent to the applet as events to which the applet must respond. For example, when the user clicks @ mouse inside the applet’s window, a mouse-clicked event is generated. If the user presses @ key while the applet’s window has input focus, a keypress event is generated. Applets can also contain various controls, such as push buttons and check boxes. When the user interacts with one of these controls, an event is generated. While the architecture of an applet is not as easy to understand as that of a console-based program, Java’s AWT makes it as simple as possible, If we have written programs for Windows, we know how intimidating that environment can be. Fortunately, Java's AWT provides a much cleaner approach that is more quickly mastered. 4. An Applet Skeleton All but the most trivial applets override a set of methods that provides the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution, Four of these methods—init{ ), start( ), stop( ), and destroy( )-—are defined by Applet. Another, paint( ), is defined by the AWT Component class. Default implementations for all of these methods are provided. Applets do not need to override those methods they do not use. However, only very simple applets will not need to define all of them. These five methods can be assembled into the skeleton shown here: // Bn Applet skeleton. import java.awt.*; import java.applet.*; ys +7 public class AppletSkel extends Applet ( // Called first. public void init) [ // initialization ) /* Called second, after init(), Also talled whenever the applet is restarted. */ public void start{) { // start or resume execution ) // Called when the applet is stopped. \- public void stop() I { Am // suspends execution ) 7* Called when applet is terminated. This is the last method executed. */ : public void destroy() { // perform shutdown activities // Called when an applet's window must be restored public void paint (Graphics g) { 11 redisplay contents of window } } 5. Applet Initialization and Termination It is important to understand the order in which the various methods shown in the skeleton are called. When an applet begins, the AWT calls the following methods, in this sequence: 4. init( ) 2 start() : 3. paiat() When an appiet ig torminated, the following sequence of method calls takes piace: testop() "5 2. destroy() Let's look more closely at these methods. ini( ) : The init{ ) method is the first method to be called. This is where we should initialize variables. This method is called only once during the run time of our applet. start( J; The start( ) method is called after init( ). It iS also called to restart an applet after it has been stopped. Whereas init( } is called once—the first time an applet is loaded—start( ) is called each time an applet’s HTML document is displayed onscteen: So, if a user leaves a web page and comes back, the applet resumes execution at start() paint( ): The paint( ) method, is called each time our applet’s output must be redrawn. ‘This situation can occur for several reasons. For example, the window in which the applet is running may be overwritten by another window and then uncovered. Or the applet window may be minimized and then restored, paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output fo the applet is required. stop( ) : The stop( ) method is called when a web browser leaves the HTML document containing the applet—when it goes to another page, for example. When’ stop( ) is cated, the applet is probably cunning. We should use stop( ) to suspend threads that don't need to run when the applet is not visible. We can restart them when start( } is, called if the user returns to the page. destroy( ): The destroy( ) method is called when the environment determines that our applet needs to be removed completely from memory. At this point, we should free up any resources the applet may be using. The stop{ ) method js always called before destroy( ). 6. Simple Applet Display Methods The following general form of the simple applet display method is: void drawString(String message, int x, int y) Here, message is the string to be output beginning at xy. in @ Java window, the upper- left corner iS location 0,0. The drawString( ) method will not recognize newline characters. if we want to start a line of text on another line, we must do so manually, specifying the precise X,Y location where we want the line to begin. (As we will see ia, later chapters, there are techniques that make this process easy,) To set the background color of an applet's window, use setBackground( ). To set the foreground color (the color in which text is shown, for example), use setForeground{ ). These methods are defined by Component, and they have the follawing general forms: void setBackground(Colar newColor) Void setForeground(Color newColor) Here, newColor specifies the new coor. The class Color defines the constants shown here that can be used to specify colors: Color-black Color.magenta Color.blue Color. orange * Color. cyan Color.pink . Color.darkGray Color.red Color.gray Color.white Color.green Color.yellow Color.lightGray For example, this sets the background color to green and the text calor to red: setBackground (Color. green); set Foreground (Color. red); course, we can change these colors as often as necessary during the execution of our applet. The default foreground color is black. The default background color is light gray. We can obtain the current settings for the background and foreground colors by calling getBackground( ) and getForeground( ), respectively. They are also defined by ‘Component and are shown here: Color getBackground( ) Color getForeground } Here is a very simple applet that sets the background color to cyan, the foreground color to red, and displays a message that illustrates the order in which the init( ), start( ), and paint( ) methods are called when an applet starts up: J* ® simple applet that sets the foreground and background colors and outputs a string. */ import java.awt.*; import java.applet.*; -? public class somple extends Applet( String msg? // set the foreground and background colors. public void init) { setBackground (Color. cyan) + set Foreground (Color. red) ; msg = “Inside init( ) --", 1 // Initialize the string to be displayed. public void start() { msg Inside start( ) --"; } // Display msg in applet window. public void paint (Graphics g) | : msg #2" Inside paint( ). g.drawStiing (msg, 10, 30); J ) 7. Requesting Repainting Whenever an applet needs to update the information displayed in. its window, it simply calls repaint{ ). The repaint( ) method is defined by the AWT. It causes the AWT run-time system to ‘execute a call to our applets update( ) method, which, in its default implementation, callls paint( ). Thus, for another part of our applet © output to its window, simply store the output and then call repaint( ). The AWT will then execute a call to paint( ), which can digplay the stored information. For example, if part of our applet needs to output a string, it can store this string in a String variable and then call repaint). Inside paint( ), we will output the string using drawString( ). The repaint( ) method has four forms. Let's look at each one, in tum. The simplest version of repaint( is shown here: void repaint( ) This version causes the entire window to be repainted. The following version specifies a region that will be repainted: void repaint(int left, int top, int width, int height} Here, the coordinates of the upper-left comer of the region are specified by left and top, and the width and height of the region ere passed in width and height. These dimensions are specified in pixels. We save time by specifying a region to repaint. Window updates are costly in terms of time. If we need to update only a small portion of the window, it is more efficient to repaint only that region. Calling repaint( ) is essentially a request that our applet be repainted sometime spon. However, if our system is slow of busy,’ update( ) might not be called immediately. Multiple requests for repainting that occur ‘within 2 short time can be collapsed by the AWT in a manner such that update( ) is only called sporadically. This can be a problem in many situations, including animation, in which a consistent update time is necessary. One solution to this problem is to use the following forms af repaint( ): void repaint(long maxDelay) void repaint(long maxDelay, int x, int y, int width, int height) Here, maxDelay specifies the maximum number of milliseconds that can elapse before update( ) is called. Beware, though. If the time elapses before update( ) can be called, itisn’t called. There’s no return value or exception thrown, so we must be careful. 8. Using the Status Window ‘An applet can also output a message to the status window of the browser or applet viewer on which it fs sunning is known as status window. To do so, call showStatus( ) with the string that we want displayed. The status window is a good piace to give the user feedback about what is occurring in the applet, suggest options, or possibly report i & some types of errors. The status window also makes an excellent debugging aid, because it gives we an easy way to output information about our applet. The following applet demonstrates showStatus( ): (/ Using the Status. Window. import java.awt.*; import java.applet.*; fe / public class StatusWindow extends Applet public void init() ( setBackground (Color. cyan): , // Display msg in applet window. public void paint (Graphics 9) { g-drawString("This is in the applet window.", 10, 20)7 showStatus("This is shown in the status window."); } : 1 9. The HTML APPLET Tag ‘The APPLET tag is used to start an applet from both an HTML document and from an applet viewer. (The newer OBJECT tag also works, but this book will use APPLET.) An applet viewer will execute each APPLET tag that it finds in a separate window, while web browsers like Netscape Navigator, internet Explorer, and HotJava will allow many applets on a single page. So far, we have been using only a simplified form of the, APPLET tag. Now it is time to take a closer look at it. The syntax for the standard” APPLET tag is shown here. Bracketed items are optional. < APPLET [CODEBASE = codebaseURL} CODE = applotFile : [ALT = alternate Text) [NAME = appletinstanceName] TALIGN. [VSPACE = pixels] [HSPACE = pixels} [< PARAM NAME = AttributeName VALUE = AttributeValue>}, [< PARAM NAME = AttributeName2 VALUE = AttributeValue>] IHTML Displayed in the absence of Java) Let's take a jook at each part now. CODEBASE CODEBASE is an optional attribute that specifies the base URL of the applet code, which is the directory that will be searched for the applet’s executable class file (specified by the CODE tag). The HTML document's URL directory is used as the CODEBASE if this attribute is not specified. The CODEBASE does not have to be on ‘the host from which the HTML document was read, CODE CODE is a required attribute that gives the name of the file containing our applet's compiled .class file. This file is relativé to the code base URL of the applet, which is the directory that the HTML file was in or the directory indicated by CODEBASE if set. ALT The ALT tag is an optional attribute used to specify a short text message that should be displayed if the browser understands the APPLET tag but can't currently run Java applets. This is distinct from the alternate HTML we provide for browsers that don't support applets, NAME NAME is an optional attribute used to specify a name for the applet instance. Applets must be named in order for other applets on the same page to find them by name and communicate with them. To obtain an applet by name, use getApplett ), which is defined by the AppletContext interface. WIDTH AND HEIGHT WIDTH and HEIGHT are required attributes that give the size (in pixels) of the applet display area. ALIGN ALIGN is an optional’ attribute that specifies the alignment of the applet. This attribute is treated the same as the HTML IMG tag with these possible values: RIGHT, TOP, BOTTOM, MIDDLE, BASELINE, TEXTTOP, ABSMIDDLE, and ABSBOTTOM. VSPACE AND HSPACE These attributes are optional. VSPACE specifies the space, in pixels, above and below the applet. HSPACE specifies the space, in pixels, on each ‘side of the applet. They're treated the same as the IMG tag’s VSPACE and HSPACE attributes. PARAM NAME AND VALUE The PARAM tag allows we to specify appletspecific arguments in an HTML page. Applets access their attributes with the getParameter{ ) method. HANDLING OLDER BROWSERS Some very old web browsers can't execute applets and don't recognize the APPLET tag. Although these browsers are now. nearly extinct (having been replaced vy Java-compatible ones), we may need to deal with them occasionally. The best way to design our HTML page to deal with such browsers is to include HTML text and markup within our tags. If the applet tags are not recognized by our browser, we will see the alternate markup. If Java is available, it will consume all of the markup between the tags and disregard the alternate markup, Here's the HTML to start an applet called SampleApplet in Java and to display a message in older browsers: If we were driving a Java powered browser, we'd ‘see Squote;A Sample Appletgquote; here,

-

10. Passing Parameters to Applets To retrieve a parameter in applets we use the getParameter( ) method. It returns the value of the specified parameter in the form of a String object. Thus, for numeric and Boolean values, we will need to convert their string representations into their internal formats. Here is an example that demonstrates passing parameters: // Use Parameters import java.awt.*; import java,applet.*; i noes “ & public class Parambemo extends Applet{ String fontName; int fontSizes float leading; boolean active; // Initialize the string to be displayed. public void start(} { String params fontName = getParameter("fontName”); if(fontName == null} fontName = “Not Found"; param = getFarameter ("font$ize"); try { if(param != null) // if not found fontSize = Integer.parseint (param); else fontSize = 0. } catch (MumberFormatException @) { fontSize = ~1; } param = getParameter ("leading"); ery ( ‘ Af(param t= null) // if not found Jeading = Float.valueds (param) .floatvalue(); else : leading = 0; } catch (NumberFormatException e) { leading = ~17 ) Param = getParameter ("accounténabled") + if (param != null) active = Boolean. valueOf (param) -booleanValue() ; } // Display parameters. public void paint (Graphics g) { Q.draxString("Font name: " + fontName, 0, 10); g-drawString(*Font size: "+ fontSize, 0, 26): G.drawString("Leading: * + leading, 0, 42); G.drawString ("Account Active: " + active, 0, 58); Hl , 11. getDocumentBase( ) and getCodeBase( ) we will create applets that will need to explicitly load media and text. Java will allow the applet to load data from the directory holding the HTML file that started the applet (the document base) and the directory from which the applet’s class file was loaded (the code base). These directories are returned as URL objects by getDocumentBase( ) and getCodeBase( ). They can be concatenated with a string that names the file we want to load. To actually load another file, we will use the showDocument( ) method defined by the AppletContext interface, discussed in the next section, The following applet ilustrates these methods: import java-awt.*7 import java-appiet.*; . import java.net.*; lt ae public class Bases extends Applet( // Display code and document bases. ee public void paint (Graphics g) { String msg? ORL url = getCodeBase()/ // get code base msg = "Code base: " # url.toString(); g.drawString(msg, 10, 20: url = getDocumentBase(); // get document base msg = “Document base: " + url.toString(); g-drawstring (msg, 10, 40); } 12,AppletContext and showDocument{) One application of Java is to use active images and animation to provide a graphical means of navigating the Web that is more interesting than the underlined blue words used by hypertext. To allow our applet to transfer control to another URL, we must use the showDocument{ ) method defined by the AppletContext interface. AppletGontext is an interface that lets we get information from the applet’s execution environment. The context of the currently executing applet is obtained by.a call to the getAppletContext( ) method defined by Applet. Within an applet, once we have obtained the appl&t's context, we can bring another document into view by calling showDocument( ). This method has no return value and throws no exception if it fails, so use it carefully. There are two showDocument( ) methods. The method showDocument(URL) displays the document 9 an applet context, getCodeBase(), owDocument() to display an ATML file. import java.aut.*; import java.applet.*7 import java.net.*; ye of public class ACDemo extends Applet public void start() ( Apple ext ac = getAppletContext (); URL uzl = getCodeBase(); // get url of this applet try { ac.showDocument (new URL(url+"Test.htmi")) 7 ) catch (Mal formedURLException e) { showStatus ("URL not found"); } i 13.The AudioClip Interface The AudioClip interface defines these methods: play( ) (play a clip from the beginning), stop( ) (stop playing the clip), and loop() (play the loop continuously). After we have loaded an audio clip using getAudioClip( ), we can use these methods to play it. 14. The AppletStub interface ‘The AppletStub interface provides the means by which an applet and the browser (or applet viewer) communicate. Our code will not typically implement this interface. 15. Outputting to the Console Although output to an applet's window must be accomplished through AWT methods, such as drawString( ) itis stil possible to use console output in our applet—especially for debugging purposes. In an applet, when we call a method such as ‘System.out.printin{ ), the output is not sent to our applets window. Instead, it appears either in the console session in which we launched the applet viewer or in the Java console that is available in some browsers. Use of console autput for purposes other than debugging is discouraged, since it violates the design principles of the ‘graphical interface most users will expect. an corer wn Canara Bank JatE OVERVIEW, DATABASE Access UNITE? Syllabus + overview Of JEFF § JASE ¥ Concapt of IDBE ¥ TDBE deiver types + TBE packsges a Brie} Overview Of JDBC process 4 Database connectton & Ascocsating the IDRC fobbe bridge with “the Database ye Stokereent Objects } fesunser” ¥ Transact lee 7 at MetexData at Darter yes “ p Ecce pprons 2 j ] ~ 6 thurs, ° ASHOK KUMAR. & a . VAIT d & e@eeect OVERVIEW OF J2EF § J2SE + me development tam of Java grouped together features of Java inte ‘three edifims, each having @ Sof tare Devabepment fit (spr) so —> original Sedition 4 Jove Is called sfava Stardard Edition (JASE) , Ib consists of APIs needed fo build a Java. applicahon ov Applet. =~ Jove 2 mobile, Editon (J2ML) Lomtatns “the AP) Used fo create Wireless Java Applicatrens —p Sova Enterprise Edittm (JREE) conbuns me AP) Used fo emeabe build Applicat ons fer 4 multrter Archikenie . [tf an enhanced version gq JOSE. ge (95 Wok t probleen faced by Suh micynsyticms 1m late te wrk ~«, to develop a woe sfor Java develo pers high le vel code thot atcecses al] popular DBMSs Selution: creation of JpRE Driver and TPR APle , we delevelsped by Sun Miewsytkom — watlnt 1 wag a” Specipitatn that + eC de = a dviver at all, described the deter! funeHen ality of a JDBC Dnver. rams monnpactu rere and third party vendors were encourages! fo build JDBC Detvers that conformed to gpecepreation , Sun ricw By shems! 1 ag Therefore fava. progrermreers conld use high-level date olyects depined inthe JDEC APT +o weit. a routing trat wkracted wilh the BEMS | Java bb dain objec Convert ‘the woutthe Mtoe low-lene) mecsages “Hrat conform to the TDEC diver specication and send Hrer othe JDBC ceiver, The JDBC dviver Panslate the ” * yourtne Into low lew) mest whet are understood and precesred by “he DRMs, ° ” “ ‘ Premera % : Dyivers 9 (TDEC heads created by dems monupa chute have i o 2. Translate low lew! equivalents } SQL statements ant by the REF Sorpoue nt lo meseay ee aap can be provesseel 4 tthe Dems , Pg. Return dada thet conforms forthe nec Specipeatan > fe the JDRe deer, y. Return ingatmation SUK OL eBror mesrager “Hep conforms jo tre TDBC specie” te “the IDSC daee, a provide brandachan ma ent = YOu hes tha © fo ty JDBC Apeaiticaten , 6. chose ma conniction be huen the DEMS and the JBEE component, TBC Driver TYPES. —> [pet PBC HeOPBC Driver, > Type Java | Nate. code Drive wr, = TyPe BIDBC Paver —> Type F TEBE Driver, Se aan ype! JDBC te OPBc Prives . ee Mierosopt cleniced 4 oy fo creak Dams ~ inde pendent data base. program Called Open DataBate Connech on Cove) From the. basia > OPEC, SUN Ms Creal IPEC , Hh UDB fo DPBC ariver (5 pscfopee Badge) 18 Used do tala Dams Gills blw JDBC SpecPeahen and 7 *P poate 4 he open a Connesiton pefiween he DEMS and JReE ¢ pe Larne abort de $s Canara Bank vee E 5 4% The JDBC toe ORE driver Vecelvec messages fom a 5 (QFE Component that conforms to the JDBC Specppeaivo 7 and. Panslake them tnto @R OpBe message foomat a whieh If then Hrantlatd ite Me message oom ap ._o unde retoogl _ sthe DEMS | . Type 2 A ava[Netve code Driver. + It uses Jove clascee fo: generak speupe Dems ~ plattemn Specie Code , The manufachirer of the DEMS peovides beth the J ava] Nottve, 4 APL tosses Ao the JREE Component code deiver an can generate the platform Specite code. t Disodar ! [otss of porta bili by > code | Foe one Dever, (ov Tava Protocol) ~ commonly used, & th converts SQL Queriee Into JDBC ~ formatted statements | whith ate inhurn feantlated rats the formar requ ved by the DBAS . i Fed ToC DIET (oF Type y DateBase profecel ) 4 tt ts Similar te Types JOBE diver €x cept SRL queries are transloted inte the format required by tthe RBIS | a SBL gueriee do not neod fe be convevkd to JDBC — ated Sustems . ¥ TAK IS eset oy to communicak. SQL Queries to the Rems & : -6- JDBC pACtAgES 2 mt 4 JDBC APL 1s contained in fue packages Ie Java. sgt compaing core Java clata Chjeche Of tha IBC API, TMese Include Java data objects that provide ' ~ the basletjor conmecting fe the DBMS and interacting ‘ 3 with the data Stored in the Dems, Java-sq) is Park gy TRSE. : : - Q. daYax.se) IS INJAEE and exkude Jovansgl ip t | VAR. $4, I [neludes Jova data objects “herr inferack hui hr Java Narn. and directory iakyjace INDI) Prd dara lata oppeots Hrett tan je Connection pockeg , meet other advanud ¢ TDBC faolaves . . ¢ a BRIEF OVERVICIN OF THE JDBC PROCESS + This process 18 divided inte pre "utres + ‘ Le Leading he JDBC Aaiver, a Connecting tothe DBM, 2 Creating and executing a statement 4) Processing, clin ratumed by whe D&M 5. Teeroinating ‘tra convection with “he DiMot , wnlecestng The JDBC Denar ATDBC driver rust be Loaded before the JOBE Component Can connect te the DBRS | ste Class. -forNarre (3 method 1 used to load IDRC driver, Elase.forhlame ( " gun. jdbc. odbc » Tdbo OdbeDriver" ) ; home oy the’ sD 7 Se wart to ZA Canara Bank Connect te tre PBMS # use Driver Manager « gekConnection () roctned | +H Java.sy). briverManager 14 Me hyghest ease 11 the Java.sg) hierarchy 16 Tespenible for Man aang dvver infomation , 4 Driver Manager. @tConnech an ¢) takes three arp roth ts PURL.24 Ihe database > user ID Ie Teguiredd “the DEMS, see pea It repurns @ Connection .mmerpa ce that 1S Used Phrough out jhe process te véperence the database. J avaSgt. Connector inte ycice manages COmmunicahon - pw axiver the J IEE fo mponent a Shing Gt! = ® Jdbesodbe: CustormerZ nemo m" + Stang userlp = “Jim” 5 Strin password = Keogh” ; ° Statement DateReguest; Do private Connection Db; yy a 1 4 5 Claes. jooName Cisun Jabe. odbe, JbbeddbeDavver" ] ; db = Dwveranger« gKonrection (an, user, password ) ® y ° . cette Creake and fxecuk a SQL Statement + Connect creak Statement () method 16 uted ‘to creak a Slatement Object » whieh IS Ustad do CKe Cuda @ quew eind return % ResultSet olyect « Hrat contains “tise yee pouse fiom the PRmE Cone or more. ws Oh injorrnntton Btortement DataRequest; Resunser Results ; +y etnp gue = "SELECT # FROM customer”; DateRequest = Dotabase , creakStatement (>> DataRespest = Db. creatStadement C9; Resulte = DatcReqpeast execute Query CG “yy: DaRequest. clore CJ! iz $e. prcess Data vetumed by Hre PBMms Regulbser Recut: Sting FintNany} String LastNa re; Shing printRew > : boolean Records Resets, MextO); ip ¢ [Resords) a Ss Qut intl Coto coe b J deta returned”) ; eb bor do ZA Canara Bank [] att on 2 A. ee Z cee e | doy 5 : @ Fittlayoce Resue.getSng (| vetName ) } LostNames Results. Sheng CLestName) 7 : wintrow = FirstName +" " 4 Latitlame ' System « outs PovetnCprintron ), , @ bonita C Results. next 0-3 how do PAbrte ne ° Atte eo a J } thtore lishing he result set. ermipale ne_cormestion fe the BE : “oT ipinate tht 22" shows aa a 6 5 - DAS : pe thall See. cack gf these oul ne, 5 tn detal, 5 c a . ~ me @ “DATABASE CoNWeEcTION % JQEE Component connect wih “the IDRe Drive, aio o C thet Is aSSoaated with the pems. (+ Met direcay “ Refore this Connecti 19 made ) the JDBC daner ‘ SC mush be | Is wit the DrveeManager, 4 whose purpose 16 te Brine tye. NDEC diver torte 4 4 NVM « q a) Class forname (isunydbe edhe JancOlbedmner’) fa @ Catch €.ClassNotFourdEreeptt etre) System. err, potion Cunable te Load "op <7rOr. geyfMecope Sysemvenrecryy . a. SS then, Use Drnee Manager. pGnnectin?) bo Conny. nto the database eres iF Yahes” Farge: pus) a —Suyr id Spasewera J OPMeaL RL_congiata three pons lL Idbe, which indrealee thar the JDBC probeo! wto be Used jo read the URL 3. TN ~Comtuin ang data that Meads te be passed tb Atoved polo Ms value is "sed ear SERRE) Metro | > our - acntams Value wetumed by ‘the Stored medure.. th must be repistered eping rag tsteDarformeter 0 médthed A lar ts rebneved ty JOE Component 1494 “PINOUT © IA a tingle Aramekr US do boty te Shrred procadux 4 refnen 89 been) method POSS Imfoonan on Nfetrostion fmt -< trred Prevedun” using Iho lechnaier desemked abe, —- bore do ZA Canara Bank : og: Calling a Bored predure : ; Spring url= "Jake dhe :Customer nfmeniadt en” : Starny uaerEd =" jam” ( Striny passion = " Reogh! Stoing Lasiordernos Connachon Db; . : te ” TF ssp que =e CALL LaptOnderShumier (7) CallableGhitement cghatemant = Db.prepare Cal (query) eaieterents riginierOutfara nuter C1, Types , VARCHAR ») catolement. execule 0) LeseDrde A) Oadme = cotalentent . petting (19: 7 cé&tatement. close 0); + a spy pP IE Sitodement tn : Hine Gloved procedure arameler reprerentect by gps mark ty Hoek cvedles a quer tre calls Lastorderdumber , th requires ong placeholder . o This 1g OUT porarver, 5 Nest, Prepercal U) metied gc onnechn object 16 called pts pacsed the qery. gine OUT Parenter 4 cant by “tered predure, ke 1K HteoOutParamelerO- LallableGatemen es eared whiny 29 fa 4 me onset e ‘ a we Updating values tn stow | Ay thete ace eccomplished by > deteping 4 cow waing methods y the ) Unserbing a new nw. Hatement yet . Updara ble f¢subbter 7 Bo updatersa() method. 1 used te ¢hornge he value of 4 colvron | tn the wurrent bow of Resuipter xx 19 Hea Updatersxls jt - Feplared with whe Aorta type t/ the column Tat 20 to be updated , Fie babes Pwo" paramefers . = fst Me ertaer re. br nome ke Column Jemng- updated a Sema tthe value at wu Hp ltce Be Value in te Column E © A volute ina Column Can be TY laced be vilth NULL Value by a | yaseing the column no. as ary¥mert “ip updakMULL 6) memod - & updatepwl) 6 Called asker al) che Updakxxs C) metrode ore Colle, bes te change the values sn osfumns af CYMER row ? Reba) Hep based on te values } the updak xxx)" metrod | ed : Z 7 ~ Be borer wr Canara Bank ‘ tomes “ne . “pp . delete Row 19 the ResuitSet y 4 deleteRovse) Mithod 15 Utkd fe Hemera row from . the Recuirset . TS alse eletes ik Jom rhe : underlying database + a ~ wy deleteRowe) takes the number 4 the row ‘te be deleted ¢ 3 as argument. ‘ “Po RestismtetetePanttay ; : Resutts, dekteRow (0)! P Current ww 16 deleted Insert Bow in the fecutesee t After updating te Resuitser Using yprlakxrr C1 metnod , : mneertRowe) method ke called to update HAC charges tn tHe uaaeriyig databace. ‘Sy. sac.atie seer , a . a Canara Bank _- wring tant “TRANSACTION PRECERING _ eesti fA Banco cto may twelve. Several Faths dirmlar do he fashs tet are , repuired bo compléte tne francacHon In a Supermarker tT 4 database transaction consite 4 Lee g SOL Statement ath wintch must be Suceetsyully COmPlebeH for rhe francachen to be completed, i one galls, deetmees 59 Otalerrenk that enetu hed Suecesipaly ype tha peran in the fransatton mubt be. “elled bach | + Commit ¢) eee Cone Hon ayer is called fy complih the bransacHon, one , 1h Is Coleg ney THE SRL Statement Can be rolled Sate | 0900 ) igen steer : st wo necatrsines sua fgg sinner we nua 9) seeice abe oy . a borat tes rn cedu ral) e pitatiecc, Result See Metabarte Sek Poetabate | a 7 Mere ore to types ¥f Mtledaly Yat con be relieved poms tye deme. lamed bo ve PP rreteclats thet deserises "tee datebare’—y pore OP > Metadata tat Arter Pe Rebultsep. Pepe wed ty ailing aeettet bata ty gp Petuitderobject., 9! ResuttsesMebdatn rm = Recure [PPtsDabs ty Ms Jivs metnede are : JtGlurntoung ¢ J Pt GlomaName (ink umber ) FOlurantype (it Pum ber) “ SEcceprioné er tn YOEC mehodr, Theie are 3 hinds y excephons 4 # a te SOLExeeptions Yellect a SQL yn ha 2 a ty, tory), : be a 2. SgLamnys fuey ey ae : 3 date Pruneation I ayy, Pee ie Mte He o « Tele “Oran | HE ety "sg Paros warring fecerred py og Conn Hen Br the pam, 1 PE (8 rmetiroas 4 : ie . Pitesti, 5 wm ey “Astek HUmPR-K 2 a unit 62. SERVLETS Ss yliabus + Zackground > Te liye cycle + Ung Tomcat gor servile # A simple servlet Spy me servlet API » he Javax servlet pathage » Readn servlet parameters +4 The Javax.serviet HEP poctage ¥ Handling BTTp requesis and 7ISponses ¢ Using coobes. : e SeSst0n Tracking : - 7 tours ye servlet ¢ developrnent Be Astiok Kumar k YO servlets are small programs that exeuites on the server side aan Juste as applets tpn arm cally extend the L go web ConnecHon , functionality gy a web browser, Serv|ets dynamically extend the puncteonality of web Server, C4 I vercus servlets, disadvantages op 662 ' Expensive in terms of protecsor anal memo resources to creak a siparate process Jor each clrent request Expensive to open ae tlose clatabose Comnechons por each clrent request. COL programs were nor plaspsteo independent dvantagec of servlets mnereaced perpormance . servile eXecute within a addrug “pace , if a web carver. it Met necessary fo create a separate process to handle éach etllent reguet+. Sarvieys Ore Platform indgendent pacaute they ase written in fava. java security maenager on the Server énporces a seb of eectrictons te protect the resources 07 A Server Machine Fun punchonalities of whe Java class fibrar nes & availabe fo a Servlet. : aoe . : owner to LN Canara B aan ank a THE LIFE CyeLé OF 4 SERVIET 2 [ire methods ave Centro] to “we lye cycle of a serviep mit O sere t) destooye) may are unplemented by every servlet and are invoked a4 specyre times by the server, ¥ let ws Consider typital user Scenario te -understand when these rnethods are called. Frias , assume that a user enters @ URL fo a web browser | Tie browser then generate an HTTP request for tn URL | E thes request Hen sent te the appropriate seaver , Second, this HTTP reyuest is received ty web server. he server map th reyuest fo a parbeulag servlet, Be cervied is aynarncaly Tetriered and loaded into the addres space of rerver Prod, the server lovokes the (1b C) method af tre servlet when the seriler is first loeded rate mm Res method (6 tnvoked onl: umbializatiin pararebers (to Compigure USE) may be passed | Riuarth, me: caver iavoteg the SERVICE) rotthool oy the Be rvlen (is method (s Called to process the HTTP Pequess me service () method is Called for each HTTP reguect, ae Finally , the Server moy decide tp unload the Serviep prom tts mlm Me server Calls the destroy method to detengetieh Fling uth any recourceg Guth as fle handles that are allocated for we servlet. . S——— A SIMPLE SERVLET ESP SERVLET 4 Steps involved in building and cea C9? eannirg ) a servlet: 1 Create and compile simple servlet source code Teen, Copy the servlep’s clase file to the proper directory | and add tre servlets Mame and mappings to whe Propes webxm) Jile, 2 Start Temeat. &. Statt a web brouser and reguet a servlet. Sirmple_servler coune code ( telloServlet. Java_) —— eee Pmpork Java.to.¥ 3 import Javax servlet. # publee class HeloServlet extends SenerieServlet pubic vord service (Servletheguece request , ~lorvlerRecponse response.) throws Seevlerbeayption , LOE uphen response. setConterntlype text] amy” di; PunWy tee pos eesponse. getlriterl) ; po-priniln ("BS Helo! "); e pur closet); yf Explanations , F favax. servlet Package Contains the classes and tegured to build cerrlete, F GenericSerybt class Provedes fenetionalry that seenpliyics the cheation of a Seovlee, gi 1 Provides twe versions op “rnrtt) and destroy whith ony be used aris, You need Sepely ong Servicer ~mtthod- wnterpaces -5- servicet) mettre — ynrhertted i handles reguetss ingyade Helloservier , tre is overerdden ¥ prin Ganene Servet gee, a Chent. Fleth argumene 1s a tearlerkeguerr objet, Ut enables the gervieh to otad data Provided via clemt regucst. Lecond argument as ServletResporse Serve to forrmutata & reponse jor the chert. ¥ De tay to stbContentpe () C&tablishes the IOE type gy he ITP response, pprier 6) metned obtains a Pringhietter 9, Ary thing -weitten steeam tc sent to chent aca Part of H7%p response « ATM fource code object’ Ph-enables the * 9 po thts me prinths 1s use to, write Some simple atthe TIP wesporse.e How fo run th} + compile this source code proper tomcat Arrectory . gle 4 start Temtat. fomeat mush be Purning byore ye ty geto Clecure a Servlet wy mee, Start a woth brmwser and request the Servlet . and place Helloseavier. elas pile Also, add HelleServiep fo thre pteps 11 localhost: 8080 [serv/ets-exarnples se ovle /Heltaservles , or. pep: 127. 0+ 0, 18080] serviets-exarmphs |servled |Helte cor utt , WHE SERVLET APL. + foo patkages wotwin the classes and interfaces tat are required to bulld” rervlets, mere are yavarserviee and favar servket. htep Prey conthitate he servles MT ¢ hese pacages ave Standard extensiong proveded by Tomiar and paeg are nok part of fave core. pacsage. fhe _favax.cerviet package ¥ mee package contams pumber of interfaces and dasces that ectablsh pre fromenserk (7 whieh serviets operate. lntexjace L Descripron. Ser vlek | peclarec ye eyile rethods for & VIE — Survie teonfeg Allows serves bo get Toral sanon pararnt hrs ne Enables Serilile Ye lig @verbs avid ARTF — igormation abour porie environment, sforvle EReg nese le used to rend data from a chent weg use ServleeResponse used 10 wrige cake Te a client Pegponse , class | Description Generaservler jmplemens Servlet & SeletGnfig evaces, | 7 RrvleeDpunl ream | provides an rmpuk erearn for Peading Fagen eee [from a eltent provides an oudput Strearo for earthing respons | fs a clent Unditates a. server error accurred , erorvarta bre Excep Hon | inotrcates a Servier (fF a val la be. The Servlet Intgoface 4 All Servlers oust Implement wervicec) , and destroy 6) metrods that are called 4y the server Servier interface. le Aleclares the nik 0, ole ing te ye cyte 7 a servlet. + Mttoods depined by Seovler are: ~ cayed when we server ws unlooded, y= atburns an Objet Prat cintarnt ang tnialyation pasomett rs re Yotd destroy C) a ServlerCongey pittovtectongig String phere Enge © - reharne a thring descorbing the serve Ay votd init CSersliGr}y asc) throws ServletException 5. vord Service (Servdedbequett rep , Lervirhespente oes) throws LervlesRuphon , TOExc«s+on . the SeevlerCot Interface yt altows a servlet Fo oblain Configuratnn data. when It is loaded , me metrods declared 4 this interface are - 1 ServletContext perGervietGntert C) ~reburne Context fo bots serve, ae String get in fararacter Chuy para) - Hilts Yalu y the mitalyation ber named param, 3. Lyumeration git Tnebaramneter Mares 0 ~ relurns an enumeration 4 all vatkalyation Parancter Names, a. Sting getlerviedlame ts = returns the name qv invekreg sect, the Se wleContert _Inter}ace + tb enables Servlets ty Dita Jnformaton About Hhe/r enur annie”, Ys meineds are~ 1. Object LAdtrebupe (trim Atte = tepurne value op the vf vs ‘ Server attribute Parned attr, a String perPrenrly pe (firing pled = requried PaMe type gthe fle 2. Girteg getReajta rh (String ypath) ~ rtdarrs the real path teat Covres pot af ee eee 4 perks 4 String gerServerInjo (J ~ rehuot info. about the server 9 - Strieg vod Jog (Steg £) - writes sto geryler leg . 6 vord tog( string £, Throwable e) ~writts § and ine Shack trac for e fo re cervley log, sr votd. etn bute (hey atar, Obyeck vay) « me ServietReguitt Lrter}ace pipenables Q series to obtain wnpwrreanen about a clent Peguess ae Severad opits Mmeteds are: 1. Object gepirerbuts (cHeg attr) : oo Striog ebtharacher Enesding C) _ a. yar get Gontent le mee : 4. Strieg get@nrentiype ed . 5. ServlerInparSiram gerdepuriveam 0) throws LOExcphon, g. Siena fifaranatter (sireg Praree 7. Enumexaton getaremneterNa nes Yo a shieg ra erp rate Valuec (Strig name ) 4. Stree: pPropacolc) — dercripien % powoeol . vemuras string ee, of clrent OP addirse « —- host name to. Stra getkerateAddr tse ne Stren getRemate tht 0 - o- S#etog gab Lohuned. _ returns teansenisren Stheme of URL ALA fob 19. St Ee : ia shieg gerne weg ues tg: Bele, beep) Jy 19k poser Pt Zy == me ServietResponse _Inteeface + lb -emables a Sexvie+ to formulate a response jor a cheng. ¥ Several Of tts methods are - returns “tne character encoding be Stung gerChavacterEr coding () ~ jer the response . 2. ServletOutpunsiream —getOutpurseream () throws LO Exce pron, 2. Printhoriber gitlnter’) tbrowe [2 Exception , vod -setContentlength (ie see) “Ss. voto Se Grtently pe (ebreag type) a READIN SERVLET PARAMETERS Postparameters. Atrok < body >
" » Opyse a < form names Form)" roethed= “Post” actlon= "http: / localhost: 8080) Servlets -examplas/cente + /Postparans berce les © 7 Emploge + phone Slept types Submit values “tabrat” > PostParameteesferviet, Java Sie AeA ReLeeeen, impork Javato. #3 smpott Java ut). #} impork javax servlet. 3 puble class Postbarametersstrviet extends SenereSe rvlet parle verd service (ServlerReguess reqiiese , ServieHtesponse reyonte ) throws ServiebExceptton , LOFxcepron Powthrtter pus = teeponse, pebtdriber 2 Enumeration @ = request. getlar ameter Names Os While ( ¢, hasMore Elements ¢) ) ® ctuing prames (String) €: nextElement 0). pe print (pname +" =" J; Shiny pale = veguest. gtipararnther Cprarn) ; purpriotin Cpwalue J; 4 pw. close C)} pope RA borer do wf Canara Bank 4 tt Contains a number x inteopaces ard classes that ave ie commonly used by oa developers, is fundeonality makesseaty Ho build servlets frat Work With HTTP Tequects and responses, FOE snterfaces tear are provided tn thea Package arm: nterg ace Dé seription, Huse rvierkea west Enables sesvieis to read data prom ay 2 ATTP request “nity Serrpthesponse — Enables fervlers te weite data to am TTP response Hp Sess1on Allows session data fo ba read ard written , 2 HagpsrasvonBind ng ingerms an oljech that It 1¢ beucrd fo tite Ustener abound from a session Te core classes that are provided im rhe Packages are! clate beseriphon Gokre Allows State leysrmation fo be stored ona client machine HetpServlet provides woethocdla te handle HT7P Teguesss and pesponses . tipSessinE rent Encaptulatee a ceseren-changed event HitpSesstonbindi wndrcates when a listener ts bound ty ot unkound event ‘? dex book vehet ay les tex! -la- | Ik beret wr Canara Bank HANDLING HT7P REQUESTS AND RESPONSES +e HiepSerrr clace Provedes spectalyed metseds that handle the various types of HTTP requests, A server developer typically overrides one af these methods, Tece mitthode are dodbelete 6), SeGekO , dotjead es , FeOpsins cy, doforr ed, delutty, and deTracets, Yandting HFIP GET Requests gS Cole r§er.H toy < body > Seenter >
color!

You might also like