You are on page 1of 18

Model Paper -1 I. One Mark Questions: 1. What is Byte code?

The java Byte code is a machine instruction for a java processor chip [ Java Virtual Machine]. The Byte code is independent of the computer system it has to run upon. 2. How are object declare in Java? Objects in Java are created using new operator. The new operator creates an object of the specified class and returns a reference to that object. Object creation consists of 2 steps, declaration and instantiation. g! Triangle p:
P= new Triangle ();

The first statement declares a variable to hold the object reference. The second statements assign the object reference to the variable. The variable p is an object of Triangle class. 3. What is constructor and its significance? "s a special type of member method. "t is e#ecuted automatically whenever an object scope starts or created an object. "t is used to initiali$e the object at the time of its creation. 4. What are Wra er classes? !ive "#a$ le. %rimitive data types may be converted into object types by using the wrapper classes, contained in the java.lang pac&age. The following table shows the simple data type and their corresponding wrapper class types. Simple type Wrapper classes boolean Boolean 'har 'haracter "nt "nteger float (loat long )ong *ouble *ouble string +tring , +tringBuffer %. &efine 'trea$. The wrapper classes have a number of uni0ue methods for handling primitive data types and objects.

+tream is just a flow of data from input device to memory or memory to output device.
(. How are thread created in java?

They are two ways to create a thread in java a. ,sing a class e#tends from Thread class. b. ,sing a class implements from -unnable interface. ,sing import statement.
i port Pac!age"a e . #lass"a e; i port Pac$age"a e . %;

). How to i$ ort java ac*ages?

.g. !

i port $ava . util . &ate.

/hich imports the class *ate and we can use *ate class methods directly in your program.

i port $ava . util . %;

This imports every class definition in the util pac&age. +. What are the different ways of initiali,ing an array? "nitiali$ation is to put values into the array elements "nitiali$ing an array elements using assignment operator or dynamic read statement. 1. arra+na e ,su'script] = value; .g. nu 'er,-] = ./;
nu 'er,0] = 0-;

2rrays are also initiali$ed by writing a list of values separated by commas and surrounded by curly braces and then no si$e is given. The compiler allocates enough space for all the elements specified in list. .g. 2. int nu 'er,] = )1230-313//344*; "n Java it is possible to assign an array object to another. .g. int a,] = ) .3130*
int ',]; ' = a;

Both the arrays will have the same values. -. .ention the *eywords used in e#ce tion handling. Java e#ception handling is managed viva file &eywords! 1. try 2. catch 3. throw 4. throws 5. finally. 1/. &efine .ultithreading. The modern operating systems such as /indows675 may recogni$e that they can e#ecute several programs simultaneously. This ability is &nown as 8 Multitas!ing. "n system terminology, it is called 8Multithreading. II. Three Marks Questions. 11. Write a note on access s ecifiers. 1. ublic access specifires: 2ny variable or method is declared as public then it is visible to the entire class in which it is defined and also it is visible to all the classes outside the class in which it is declared. "t has Eg: pu'lic int a; the widest possible visibility and accessible everywhere. 2. 0riendly access specifier! when no access modifier is specified, the member defaults to a limited version of public accessibility &nown as friendly level access specifiers. The difference between the public access and the friendly access is that the public modifier ma&es fields visible in all classes, regardless of their pac&age, while the friendly access ma&es field visible only in the same pac&age, but not in other pac&age. . protected access specifires: The visibility level of a protected field lie in between the public access and friendly access. That is, the protected modifier ma&es the field visible ant only a super class and subclass in the same pac&age but also the sub class in other pac&ages. 9ote that non6sub class in other pac&age can:t access protected members!
pu'lic void (ind( ) ) : ; g! int ' } void su () ) * =

g! protected int a ; protected void displa+() ) = *

!. rivate1 The field is accessible only within its own class. That means, to its member function of class. The private field enjoys the highest degree of data protection. "f the member functions are declared private then they are of no use at all, since they cannot be accessed outside the class. They cannot be inherited by subclasses and therefore not accessible in subclasses. g! private int nu . 12. "# lain static variable and static $ethod. a. static "aria#le : To define a member that is common to all the objects that can be accessed without using a particular object. That is, the member belongs to the class as a whole rather than the object created from the class, such a members are called static variables; class variable. +ynta#! static datat+pe var5na e; /here static is a &eyword, datatype is any valid java datatype, var6name is a valid identifier. e.g. static int count; #. static methods : )i&e static variables, static methods can be called without using objects. <ethods that are of general utility but don:t directly affect an instance of that class are usually declared as class method or static method. Java class libraries contain a number of class methods. (or e#ample, the <ath class of java library defines many static methods to perform <ath operation that can be used in any program. .g. (loat 6 = Math.s7rt(12);
int + = Math.a's(52); int 8 = Math.a's(0-5/9);

The method s0rt=> is a class method or static method defined in <ath class. 9ote that the static methods are called by class name. "nfact, no object has been created for use. +tatic methods have several restrictions. 1. They can only call other static methods. 2. They can:t refer to this or super &eyword in any way. 13. &ifferentiate function overloading and function overriding. O"erloadin$ "t deals with multiple methods with the same name in the same class, but with different argument list. *efine a similar operation in different ways for different parameters. These methods are invo&ed depending on the type of the arguments. O"erridin$ "t deals with 2 methods, one in a parent class and another in child class that have the same name and arguments. *efine a similar operation in different ways for different object type. These methods are invo&ed depending on the type of the objects.

14. .ention the different ty es of o erators in java. 1. 2ssignment operator[?@ 2. 2rithmetic operators [A, 6, B, ;, C@ 3. ,nary Operators [A, 6, AA, 66, D@ 4. The -elational operators [E, E?, F, F?, ??, D?@ 5. The )ogical operators [GG, HH, D@

I. The 'onditional Operator [J!@ K. Bit wise operators[G, H, L, M, FF, EE, EEE@ N. +pecial Operators [instanceof operator and member selection operator =.>@ 1%. &ifferentiate labeled brea* and labeled continue state$ent. Java support labeled brea& statement. The label is any valid java identifier to give a label to loop and place it before loop with colon at the end. :+nta6 : la'el"a e : loop;state ent /e want to jump outside nested loop or continue the outside loop, then we have to use labeled brea& and labeled continue statements 1(. "# lain any % string handling functions.
.ethod 2all + = 6.to<ower#ase() = = 6.to>pper#ase() s..e7uals(s1) s..e7ualsAgnore#ase(s1) s..length() #=strc p(s.3s1) s..concat(s1) 3as* erfor$ed #onverts the :tring 6 to all lowercase #onverts the :tring 6 to all >ppercase ?eturns @true i( s. is e7ual to s1 ?eturns @true i( s. = =s13 ignoring the case o( characters Bives the length o( s. ?eturns 5ve i( s.Cs23 Dve. A( s.Es13 and 8ero i( s. == s1 #oncatenates s. and s1

1). "# lain 'trea$to*eni,er class. "t brea&s up the "nput+tream into number of to&ens that are delimited by a set of characters. "t has the following constructor! StreamTokeni%er&'eader o#(). .g +treamTo&eni$er st ? new +treamTo&eni$er=new "nput+tream-eader=>>. +treamTo&eni$er class defines several methods! 1. eolIsSi$nificant&#oolean eolfla$) ! This method to ensure that new line characters will be delivered as to&en, so we can count the number of lines in the given file. "f eolflag is true, the endof line characters are returned as to&en otherwise, ignore the eol character. 2. "oid *ordchars&int start+ int end) ! This method is used to specify the range of characters that can be used in words. +tart and end specifies the range of valid characters. 3. "oid *hitespace,hars&int start+ int end): Oere start and end specifies the range of valid white space characters. 4. ne-tToken&) ! "s obtained from the "nput+tream depending +treamTo&eni$er method and it returns the type of To&ens. +treamTo&eni$er defines 4 integer constants, they are ! TT./O0 + TT./O1+ TT.WO'2+ TT.34M5/'. 1+. "# lain how thread is created using e#tending the thread class. 2 class is created by e#tending the class java.lang.Thread, which can be implemented as a thread. This gives us access to all the thread methods directly. "t includes the following steps. 1. *eclare the class as e#tending the Thread class. class ThreadF e6tends Thread

) *

"mplement the run => method that is responsible for e#ecuting the se0uence of code that the thread will e#ecute. class ThreadF e6tends Thread The run => method has been ) inherited by the class Thread2. we pu'lic void run () have to override this method in ) order to implement the code to be : e#ecuted by our thread. * * 3. 'reate a thread object and call the start => method to initiate the thread e#ecution. ThreadF p = new ThreadF (); p.start (); GG invo!es run() ethod. (irst line, instantiates a new object of class Thread2. 9ote that this statement just creates the object. The thread that will run this object is not yet running. The Thread is in a 8new'orn state. The second line, calls the start => method causing the thread to move in to the 8runna'le state. 9ow, the thread is in its 8runna'le state. 1-. "# lain any one loo ing construct with an e#a$ le. /hile loop is used to e#ecute the statements as long as the condition is true. The main use of while loop is un&nown times of repetition. "t is also called as re4tested looping construct. <inimum while (e6pression) ) number of e#ecution is $ero. "t is an entry6control loop. :tate ent5.; .g. while (a F? .-) : ) :tate ent5n; :+ste .out.println (a); * aDD; * 2/. "# lain structure of java rogra$. 2 Java program may contain one or more sections as shown in the figure. &ocu entation :ection Pac!age :tate ent A port :tate ent Anter(ace state ent #lass de(initions Main ethod class ) ain( ) ethod de(inition ) 5555 :uggested Hptional Hptional Hptional Hptional Issential

2.

* *

55555

2ocumentation Section: The documentation section comprises a set of comment lines giving the name of the program, the author and other details. Java allows 3 different styles of comment entries. They are #5:t+le 5E 56 Multi line co ent 65 #DD :t+le 5E 55 :ingle line or part o( line Java :t+le 5E 566 Multi line and generate docu entation auto aticall+ 65 Packa$e Statement: The first statement allowed in Java file is a pac&age statement. This statement declares a pac&age name and informs the compiler that the classes defined here belong to this pac&age. .g. pac!age student; The pac&age statement is optional. Import Statement: 2 number of import statements are used after pac&age statement but before any class definition. This is similar to Pinclude statement in '. .g. i p o r t $ a v a . i o . % ; Interface Statements: 2n interface is li&e a class but includes a group of method declarations. This is also an optional section and is used only when we wish to implement the multiple inheritance features in the program. ,lass 2efinition: 2 Java program may contain multiple class definitions. 'lasses are the primary and essential elements of the Java program. Main Method ,lass: +ince main => method is the starting point of a Java program, this class is the essential part of a Java program. 2 +imple Java program may contain only this part. The main method creates objects of various classes and establishes communication between them. On reaching the end of main, the program terminates and the control passes bac& to the operating system. 0irst 6pplication Pro$ram:
#lass +ashu ) pu'lic static void ain(:tring agrs,]) ) :+ste .out.println (J#o puters 5 :cienceK); * *

:ave the (ile as yashu.java 758 1 #o puters 5 :cience

III. Se"en Marks 7uestions. 21. What is the use of su er *eyword in java? "# lain with an e#a$ le. super key*ord is applied to invo&e override super class methods, invo&e override super class fields and also to invo&e super class constructors. The sub class constructor uses super &eyword. +uper &eyword to invo&e the constructor method of the super class. The &eyword super is used subject to the following condition! 6 6 The super &eyword may only be used within a sub class constructor The call to super class constructor must appear as the first statement within the subclass constructor.

The parameteri$ed constructors;methods, the parameters in the super call must match the order and type of the instance variable declared in the super class. In"oke super class constructor: super (); super (arg);

a.

+ynta#!

The first format is used to call ; invo&e default super class constructors. The second format is used to invo&e parameteri$ed base;super class constructor, the super class constructor with a matching arguments.
b. 6ccess super class instance method: "f your method overrides one of its super class methods , you can invo&e the overridden method through the use of &eyword super. class one ) void call e() ) :+est .out.println(JhelloK); * * class de o ) pu'lic static void ain(:tring a,]) ) two p = new two(); p.call'oth(); * * class two e6tends one ) void call e() ) :+ste .out.println(JhaiK); * void call'oth() ) super.call e(); call e(); * *

22. #plain the hierarchy of the java pac&ages. #plain any one pac&age. 922. "# lain Java :8; ac*ages. 8a"a 6PI packa$e

)ang

util

awt

io

net

applet

The above figure shows the functional brea&down of pac&ages that fre0uently used in the program. The pac&age name should be uni0ue for classes and interfaces in the pac&ages. The following table shows the classes that belong to the each 2%" pac&ages! Packa$e 3ame Java.lang ,ontents )anguage support classes. These classes are automatically imported. They include classes for primitive types, strings, mathematical functions, Threads and e#ceptions.

Java.util Java.io

)anguage utility classes such *ate, -andom number, +tac&. "nput ; output support classes. They provide facilities for the ";O operation on the data. "t consists of enhanced version of ";O operations. +et of classes for implementing graphical user interface. They include classes for windows buttons, list , menu:s etc., 'lasses for networ&ing. They include classes for communicating with local computer [)29@ as well as with internet servers.

Java.awt Java.net

Java.applet

'lasses for creating and implementing applets. "t allows the user to create website and run on any internet web browser. The default browser is 2pplet Qiewer. Java uses simple data types, such as int and char for performance reason. These data types are not the part of the object hierarchy. %rimitive data types may be converted into object types by using the wrapper classes, contained in the (a"a.lan$ packa$e. The following table shows the simple data type and their corresponding wrapper class types. Wrapper classes Boolean 'haracter "nteger (loat )ong *ouble +tring , +tringBuffer The wrapper classes have a number of uni0ue methods for handling primitive data types and objects.

Simple type boolean 'har "nt float long *ouble string

,on"ertin$ primiti"e num#ers to o#(ect num#ers usin$ constructor method ,allin$ constructor 2escription Anteger p = new Anteger(i) 5E Pri itive integer to Anteger o'$ect. Lloat 7 = new Lloat(() 5E Pri itive (loat to Lloat o'$ect. <ong <= new <ong(l) 5E Pri itive long to <ong o'$ect. &ou'le d = new &ou'le(!) 5E Pri itive dou'le to &ou'le o'$ect. ,on"ertin$ o#(ect num#ers to primiti"e num#ers usin$ ty e<alue method Method ,allin$ 2escription int i = p.intValue() 5E #onverting Anteger o'$ect to pri itive int value. (loat ( = 7.(loatValue() 5E #onverting Lloat o'$ect to pri itive (loat value. long l = <.longValue() 5E #onverting <ong o'$ect to pri itive long value. dou'le ! = d.dou'leValue() 5E #onverting &ou'le o'$ect to pri itive dou'le value ,on"ertin$ a num#er to strin$ usin$ to'tring&) method Method ,allin$ 2escription :tr = Anteger.to:tring(i) 5E #onverting pri itive int to string. :tr = Lloat.to:tring (() 5E #onverting pri itive (loat to string. :tr = <ong.to:tring(l) 5E #onverting pri itive long to string. :tr = &ou'le.to:tring(d) 5E #onverting pri itive dou'le to string. ,on"ertin$ strin$ to numeric o#(ect usin$ the static value7f= > method Method ,allin$ 2escription

P = Anteger . value o( (str); 7= Lloat . value o( (str); <= <ong . value o( (str); d= &ou'le . value o( (str); ,on"ertin$ numeric strin$ arsety e &) functions Method ,allin$ int i = Anteger. parseAnt (str) long l = <ong.parase<ong(str)

5E converting string to integer o'$ect 5E converting string to (loat o'$ect 5E converting string to long o'$ect 5E converting string to &ou'le o'$ect to primiti"e num#ers usin$ a static method 5E 5E 2escription #onverting string to pri itive int value. #onverting string to pri itive long value.

23. "# lain life cycle of thread with $e$ber functions. 2 Thread has a life cycle consisting of the following events! 1. 9ewborn state 2. -unnable state 3. -unning state 4. Bloc&ed state 5. *ead state 2 Thread is always in one of these five states. "t can move from one state to another via a variety of ways.

3e*#orn state: /hen it instantiates a new object of class *emoThread. "t just creates the objects. The thread is in a newborn state. 'unna#le state: /hen the start => method is called upon the thread object, the thread is in the runnable state. 2 runnable thread joins the collection of threads that are ready for e#ecution. 'unnin$ state: 2 Thread currently being e#ecuted by the '%, is in the running state. 5locked state: 2 Thread is said to be bloc&ed when it prevented from entering into the runnable state and subse0uently the running state. This happens when the thread is suspended, sleeping or waiting in order to satisfy certain re0uirements. 2 bloc&ed thread is considered Rnot runna'leS but not dead and therefore fully 0ualified to run again. 2ead stare: very thread has a life cycle. 2 running thread ends its life when it has completed e#ecuting its run => method. "t is a natural death. /e can &ill it by sending the stop message to it at any state thus causing a premature death to it. 2 thread can be &illed as soon it is born or while it is running or even when it is in R not runna'leS =bloc&ed> condition. .ethod &escri tion void sleep(long sec) #auses the currentl+ e6ecuting thread to sleep (te poraril+ cease e6ecution) (or the speci(ied nu 'er o( illiseconds.

Void start()

void +ield() void suspend() Void wait() Void resu e() Void noti(+()

>sed to 'egin e6ecution o( a thread. The $ava virtual achine calls the run ethod o( the thread in which this ethod is called. >sed to pause te poraril+ to currentl+ e6ecution thread o'$ect and allow other thread to e6ecute. Mloc!ed until (urther orders Mloc!ed until certain condition occurs Move the thread (ro 'loc!ed state to running state3 which are 'loc!ed '+ suspend () ethod. Move the thread (ro 'loc!ed state to running state3 which are 'loc!ed '+ wait() ethod

24. "# lain the *eyword try? catch and finally. Try and catch: The try bloc& can have one or more statements that could generate an e#ception. "f any one statement generates an e#ception the remaining statements in the bloc& are s&ipped and e#ception jumps to the catch bloc& that is placed ne#t to the try bloc&. The catch bloc& can have one or more statements that are necessary to process the e#ception. very try statement should be followed by at least one catch statement, otherwise compilation error will occur. 'atch statement wor&s li&e method definition. The catch bloc&s receive a single parameter, which is reference to the e#ception object thrown by the try bloc&. "f the catch parameter matches with the type of e#ception object, then the e#ception is caught and statements in the catch bloc& will be e#ecuted. Otherwise, the e#ception is not caught and the default e#ception handler will cause the e#ception to terminate.
tr+ ) GG 'loc! o( code to onitor (or errors * catch(I6ceptionT+pe. e.) ) GG I6ception handler (or I6ceptionT+pe. * catch(I6ceptionT+pe1 e1) ) GG I6ception handler (or I6ceptionT+pe1 * (inall+ ) ;;bloc& of code to be e#ecuted compulsory T

finally key*ord: This can be used to handle an e#ception that is not caught by any of the previous catch statements. (inally bloc& can be used to handle any e#ception generated within a try bloc&. "t may be added immediately after the try bloc& or after the last catch bloc&. /hen a finally bloc& is defined, this is guaranteed to e#ecute, regardless of whether or not an e#ception is thrown. 2s a result, we can use it to perform certain house &eeping operations such as closing files and releasing system resources.

2%. "# lain any ) features of java. 1. Simple and po*erful: Java is a simple language since many features of ' and 'AA are not used in Java. .g. Java does not use pointer, preprocessor header files and goto statements. 2lso it eliminates operator overloading, hybrid and multiple inheritances. 9. O#(ect-Oriented: Java is a true Object6Oriented language. 2lmost everything in Java is an object. Java uses e#tensive set of classes arranged in pac&ages and used in our programs. The object model is simple and easy to e#tend. 3. ,ompiled and Interpreted: ,sually a computer language is either compiled or interpreted. Java combines both these approaches thus ma&ing java a two6stage system. (irst, Java compiler translates source code into 8 M+te code instructions. Byte codes are not machine instructions. "n second stage, java interpreter generates machine code that can be directly e#ecuted by the machine that is running the java program. /e can say that, Java is both a compiled and interpreted language. !. Platform independent and porta#le: Java programs can be moved from one computer to another anywhere and any time. 'hanges and upgrades in O+ processors and system resources will not ma&e any changes in Java programs. 2lso we can download Java applet from a remote computer onto user local system via "nternet and e#ecute it locally. Java compiler generates byte code instruction that can be implemented in any machine. Oence Java is portable. :. 'o#ust and Secure: Java is a robust language it provides many safeguards to ensure reliable code. "t has strict compile time and runtime chec&ing for data types. Java also incorporates the concept of e#ception handling, which captures serious errors and eliminates any ris& of crashing the system. There is no threat of viruses since no viruses are communicated with Java applet. ;. 2istri#uted: Java is designed as a distributed language for creating applications on networ&s. "t has ability to share both data and programs. <ultiple programmers at multiple remote locations can wor& together on a single project. <. Multithreaded: Java supports multithreaded programs i.e., handling multiple tas&s simultaneously. This means we need not wait for application to finish one tas& before beginning another. This feature greatly improves the interactive performance of graphical applications.
8.

2ynamic: Java is a dynamic language since it lin&s new class libraries methods and objects. Java programs support functions written in other languages such as ' G 'AA. These functions are called native methods and lin&ed dynamically at runtime.

Multithreaded Pro$rammin$ Thread! 2 basic unit of '%, utili$ation. "t is a se0uential e#ecution of a series of instructions "t shares its code and data sections with the other thread of the same process. 2 process can perform more than one tas& at a time if a process has multiple threads. )ogical unit of programUs e#ecution ach program is a thread and a process 2 program can create multiple threads Thread startup is faster than a process startup Threads of the same process share code and memory =to a certain e#tent>. 5enefits &1) -esponsiveness! 2llow a program to continue running even if part of it is bloc&ed or is performing a lengthy operation. -esource sharing! several different threads of activity all within the same address space. conomy! 2llocating memory and resources for process creation is costly. "n +olaris, creating a process is about 3V times slower than is creating a thread -emar&! ,sing threads, conte#t switches ta&e less time. ,tili$ation of multiprocessor architecture! +everal thread may be running in parallel on different processors. Of course, multithreading a process may introduce concurrency control problem that re0uires the use of critical sections or loc&s. The 8a"a Thread Model Thread %riorities +ynchroni$ation <essaging The Thread 'lass and the -unnable "nterface Thread Priorities Java assigns to each thread a priority that determines how that thread should be treated with respect to the others. Thread priorities are integers that specify the relative priority of one thread to another. 2 threadUs priority is used to decide when to switch from one running thread to the ne#t. This is called a context switch. The rules that determine when a context switch ta&es place are simple! A thread can voluntarily relinquish control. This is done by e#plicitly yielding, sleeping , or bloc&ing on pending ";O. "n this scenario, all other threads are e#amined, and the highest6priority thread that is ready to run is given the '%,. A thread can be preempted by a higher-priority thread. "n this case, a lower6priority thread that does not yield the processor is simply preempted, no matter what it is doing, by a higher6priority thread. Basically, as soon as a higher6priority thread wants to run, it does. This is called preemptive multitasking.

The Main Thread == ,ontrollin$ the main Thread. class 'urrentThread*emo W public static void main=+tring args[@> W Thread t ? Thread.currentThread=>. +ystem.out.println=X'urrent thread! X A t>. ;; change the name of the thread t.set9ame=X<y ThreadX>. +ystem.out.println=X2fter name change! X A t>. try W for=int n ? 5. n E V. nY> W +ystem.out.println=n>. Thread.sleep=1VVV>. T T catch ="nterrupted #ception e> W +ystem.out.println=X<ain thread interruptedX>. T T T O4TP4T: 'urrent thread! Thread[main,5,main@ 2fter name change! Thread[<y Thread,5,main@ 5 4 3 2 1

Implementin$ 'unna#le
class Thread*emo W public static void main=+tring args[@> W new 9ewThread=>. ;; create a new thread try W for=int i ? 5. i E V. iY> W +ystem.out.println=X<ain Thread! X A i>. Thread.sleep=1VVV>. T T catch ="nterrupted #ception e> W +ystem.out.println=X<ain thread interrupted.X>. T +ystem.out.println=X<ain thread e#iting.X>. T T "nside 9ewThreadUs constructor, a new Thread object is created by the following statement! t ? new Thread=this, X*emo ThreadX>. %assing this as the first argument indicates that you want the new thread to call the run=> method on this object. Thread defines several constructors. The one that we will use is shown here! Thread=-unnable threadOb, String thread ame!

'hild thread! Thread[*emo Thread,5,main@ <ain Thread! 5 'hild Thread! 5 'hild Thread! 4 <ain Thread! 4 'hild Thread! 3 'hild Thread! 2 <ain Thread! 3 'hild Thread! 1 #iting child thread. <ain Thread! 2 <ain Thread! 1 <ain thread e#iting. What is 6pplet 6 small pro$ram *ritten in 8a"a and included in a >TM1 pa$e. It is independent of the operating system on which it runs 2 small computer program that can be transmitted from a server to a client computer and e#ecuted on the client. 2 small program that can be sent along with a /eb page to a user. Java applets can perform interactive animations, immediate calculations, or other simple tas&s without having to send a user re0uest bac& to the server. 2n applet is a special Java program that can be embedded in OT<) documents. "t is automatically e#ecuted by =applet6enabled> web browsers. 2ppletviewer is a program that can run "n Java, non6applet programs are called applications. 0eatures of 6pplet -un inside web browser or 2ppletQiewer Zraphical Java programs %latform6neutral

/-ceptions
,sers have high e#pectations for the code we produce. ,sers will use our programs in une#pected ways. *ue to design errors or coding errors, our programs may fail in une#pected ways during e#ecution "t is our responsibility to produce 0uality code that does not fail une#pectedly. 'onse0uently, we must design error handling into our programs.

/rrors and /rror >andlin$ 2n rror is any une#pected result obtained from a program during e#ecution. ,nhandled errors may manifest themselves as incorrect results or behavior, or as abnormal program termination. rrors should be handled by the programmer, to prevent them from reaching the user. +ome typical causes of errors! <emory errors =i.e. memory incorrectly allocated, memory lea&s, Rnull pointerS> (ile system errors =i.e. dis& is full, dis& has been removed> 9etwor& errors =i.e. networ& is down, ,-) does not e#ist> 'alculation errors =i.e. divide by V> /rrors and /rror >andlin$ Traditional rror Oandling 1. very method returns a value =flag> indicating either success, failure, or some error condition. The calling method chec&s the return flag and ta&es appropriate action. *ownside! programmer must remember to always chec& the return value and ta&e appropriate action. This re0uires much code =methods are harder to read> and something may get overloo&ed. /here used! traditional programming languages =i.e. '> use this method for almost all library functions =i.e. fopen=> returns a valid file or else null> /-ceptions 2n exception is an object that describes an unusual or erroneous situation #ceptions are thrown by a program, and may be caught and handled by another part of the program 2 program can be separated into a normal e#ecution flow and an exception execution "low 2n error is also represented as an object in Java, /-ception >andlin$ Java has a predefined set of e#ceptions and errors that can occur during e#ecution 2 program can deal with an e#ception in one of three ways! ignore it handle it where it occurs handle it an another place in the program The manner in which an e#ception is processed is an important design consideration "f an e#ception is ignored by the program, the program will terminate abnormally and produce an appropriate message

2n e#ception can be caught to handle it or pass it on #ceptions can be generated by the Java run6time system, or they can be manually generated by your code /-ception->andlin$ 0undamentals Java e#ception handling is managed by via five &eywords! try, catch, throw, throws, and finally %rogram statements to monitor are contained within a try bloc& "f an e#ception occurs within the try bloc&, it is thrown 'ode within catch bloc& catch the e#ception and handle it +ystem generated e#ceptions are automatically thrown by the Java run6time system To manually throw an e#ception, use the &eyword throw 2ny e#ception that is thrown out of a method must be specified as such by a throws clause 2ny code that absolutely must be e#ecuted before a method returns is put in a finally bloc& ?eneral form of an e-ception-handlin$ #lock ;; bloc& of code to monitor for errors

tryW

T catch =#xceptionType$ exOb>W ;; e#ception handler for #xceptionType$ T catch =#xceptionType% exOb>W ;; e#ception handler for #xceptionType% T ;;[ finallyW ;; bloc& of code to be e#ecuted before try bloc& ends T

/-ception Types
2ll e#ception types are subclasses of the built6in class Throwable Throwable has two subclasses, they are #ception =to handle e#ceptional conditions that user programs should catch> 2n important subclass of #ception is -untime #ception, that includes division by $ero and invalid array inde#ing rror =to handle e#ceptional conditions that are not e#pected to be caught under normal circumstances>. i.e. stac& overflow To handle an e#ception in a program, the line that throws the e#ception is e#ecuted within a try block 2 try bloc& is followed by one or more catch clauses ach catch clause has an associated e#ception type and is called an exception handler /hen an e#ception occurs, processing continues at the first catch clause that matches the e#ception type

The try Statement


4sin$ try and catch

Oandling an e#ception has two benefits, "t allows you to fi# the error "t prevents the program from automatically terminating The catch clause should follow immediately the try bloc& Once an e#ception is thrown, program control transfer out of the try bloc& into the catch bloc& Once the catch statement has e#ecuted, program control continues with the ne#t line in the program following the entire try;catch mechanism

,hapter -

Packages and Interfaces


[Package is a container] In java package is a grouping several class definitions together in a logical grouping is usually done according to functionality. Infact packages are acts like a container to classes. By organizing our classes we achieve the following benefits. The classes contained in the packages of other programs can be easily reused. In packages class can be uni ue compared !ithin antoher packages. Packages provide a !ay to hide classes thus preventing other programs or packages from a accessing classes that are meant for internal use only. Packages also provide a !ay for separating design from coding. It is possible to change the implementation of any method !ithout affecting the rest of the design. In java the packages are classified into two ways. Predefined "#ava $PI% Packages &ser defined packages. In java six Predefined (Standard API APPLICATION PROGRAM INTERFACE) Packa es

lang " 'anguage%


util "&tility% a!t " $bstract (indo! Tool% io " Input )utput% net " *et!ork Package% applet " Internet !eb +ro!ser%

You might also like