Вы находитесь на странице: 1из 44

Oops:1.What are the principle concepts of OOPS?

There are four principle concepts upon which object oriented design and programming rest. They are:

Abstraction Polymorphism Inheritance Encapsulation (i.e. easily remembered as A-PIE .

2.What is Abstraction? Abstraction refers to the act of representing essential features without including the bac!ground details or e"planations. 3.What is Encapsulation? Encapsulation is a techni#ue used for hiding the properties and beha$iors of an object and allowing outside access only as appropriate. It pre$ents other objects from directly altering or accessing the properties or methods of the encapsulated object. 4.What is the difference between abstraction and encapsulation? Abstraction focuses on the outside $iew of an object (i.e. the interface Encapsulation (information hiding pre$ents clients from seeing it%s inside $iew& where the beha$ior of the abstraction is implemented. Abstraction sol$es the problem in the design side while Encapsulation is the Implementation.

Encapsulation is the deli$erables of Abstraction. Encapsulation barely tal!s about grouping up your abstraction to suit the de$eloper needs.

5.What is nheritance? Inheritance is the process by which objects of one class ac#uire the properties of objects of another class. A class that is inherited is called a superclass.

The class that does the inheriting is called a subclass.

Inheritance is done by using the !eyword e"tends. The two most common reasons to use inheritance are:
o o

To promote code reuse To use polymorphism

!.What is Pol"#orphis#? Polymorphism is briefly described as 'one interface& many implementations.' Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different conte"ts - specifically& to allow an entity such as a $ariable& a function& or an object to ha$e more than one form. $.%ow does &a'a i#ple#ent pol"#orphis#? (Inheritance& ($erloading and ($erriding are used to achie$e Polymorphism in ja$a . Polymorphism manifests itself in )a$a in the form of multiple methods ha$ing the same name.

In some cases& multiple methods ha$e the same name& but different formal argument lists (o$erloaded methods . In other cases& multiple methods ha$e the same name& same return type& and same formal argument list (o$erridden methods .

(.E)plain the different for#s of Pol"#orphis#. There are two types of polymorphism one is *o#pile ti#e pol"#orphis# and the other is run time polymorphism. *ompile time polymorphism is method o$erloading. +unti#e ti#e pol"#orphis# is done using inheritance and interface. ,ote: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:

Method overloading Method overriding through inheritance Method overriding through the Java interface

-.What is runti#e pol"#orphis# or d"na#ic #ethod dispatch? In )a$a& runtime polymorphism or dynamic method dispatch is a process in which a call to an o$erridden method is resol$ed at runtime rather than at compile-time. In this process& an

o$erridden method is called through the reference $ariable of a superclass. The determination of the method to be called is based on the object being referred to by the reference $ariable. 1..What is /"na#ic 0indin1? +inding refers to the lin!ing of a procedure call to the code to be e"ecuted in response to the call. ,ynamic binding (also !nown as late binding means that the code associated with a gi$en procedure call is not !nown until the time of the call at run-time. It is associated with polymorphism and inheritance. 11.What is #ethod o'erloadin1? -ethod ($erloading means to ha$e two or more methods with same name in the same class with different arguments. The benefit of method o$erloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type. ,ote:

Overloaded methods MUST change the argument list Overloaded methods C ! change the return type Overloaded methods C ! change the access modifier Overloaded methods C ! declare new or "roader chec#ed e$ceptions method can "e overloaded in the same class or in a su"class

12.What is #ethod o'erridin1? -ethod o$erriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The !ey benefit of o$erriding is the ability to define beha$ior that%s specific to a particular subclass type. ,ote:

The overriding method cannot have a more restrictive access modifier than the method "eing overridden %&$: 'ou can(t override a method mar#ed pu"lic and ma#e it protected)* 'ou cannot override a method mar#ed final 'ou cannot override a method mar#ed static

13.What are the differences between #ethod o'erloadin1 and #ethod o'erridin1? O'erloaded 2ethod O'erridden 2ethod

Ar1u#ents +eturn t"pe E)ceptions

-ust change *an change *an change

-ust not change *an%t change e"cept for co$ariant returns *an reduce or eliminate. -ust not throw new or broader chec!ed e"ceptions -ust not ma!e more restricti$e (can be less restricti$e (bject type determines which method is selected. /appens at runtime.

Access n'ocation

*an change .eference type determines which o$erloaded $ersion is selected. /appens at compile time.

14.*an o'erloaded #ethods be o'erride too? 0es& deri$ed classes still can o$erride the o$erloaded methods. Polymorphism can still happen. *ompiler will not binding the method calls since it is o$erloaded& because it might be o$erridden now or in the future. 15. s it possible to o'erride the #ain #ethod? 1(& because main is a static method. A static method can2t be o$erridden in )a$a. 34./ow to in$o!e a superclass $ersion of an ($erridden method5 To in$o!e a superclass method that has been o$erridden in a subclass& you must either call the method directly through a superclass instance& or use the super prefi" in the subclass itself. 6rom the point of the $iew of the subclass& the super prefi" pro$ides an e"plicit reference to the superclass2 implementation of the method.
// From subclass super.overriddenMethod();

1$.What is super? is a !eyword which is used to access the method or member $ariables from the superclass. If a method hides one of the member $ariables in its superclass& the method can refer to the hidden $ariable through the use of the super !eyword. In the same way& if a method o$errides one of the methods in its superclass& the method can in$o!e the o$erridden method through the use of the super !eyword. ,ote:
super

'ou can only go "ac# one level* +n the constructor, if you use super%), it must "e the very first code, and you cannot access any this.xxx varia"les or methods to compute its parameters*

1(.%ow do "ou pre'ent a #ethod fro# bein1 o'erridden? To pre$ent a specific method from being o$erridden in a subclass& use the final modifier on the method declaration& which means 'this is the final implementation of this method'& the end of its inheritance hierarchy.
// public final void exampleMethod() { Method statements

nterface34
1-.What is an nterface? An interface is a description of a set of methods that conforming implementing classes must ha$e. ,ote:

'ou can(t mar# an interface as final* +nterface varia"les must "e static* n +nterface cannot e$tend anything "ut another interfaces*

2..*an we instantiate an interface? 0ou can%t instantiate an interface directly& but you can instantiate a class that implements an interface. 21.*an we create an ob5ect for an interface? 0es& it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right& so you must write a class that implements the interface and fulfill all the methods defined in it. 22./o interfaces ha'e #e#ber 'ariables? Interfaces may ha$e member $ariables& but these are implicitly public, static, and final- in other words& interfaces can declare only constants& not instance $ariables that are a$ailable to all implementations and may be used as !ey references for method arguments for e"ample.

23.What #odifiers are allowed for #ethods in an nterface? (nly public and abstract modifiers are allowed for methods in interfaces. 24.What is a #ar6er interface5 -ar!er interfaces are those which do not declare any re#uired methods& but signify their compatibility with certain operations. The java.io. eriali!able interface and "loneable are typical mar!er interfaces. These do not contain any methods& but classes must implement this interface in order to be seriali7ed and de-seriali7ed.

Abstract class:25.What is an abstract class? Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared& but contains no implementation. ,ote: +f even a single method is a"stract, the whole class must "e declared a"stract* "stract classes may not "e instantiated, and re,uire su"classes to provide implementations for the a"stract methods*

'ou can(t mar# a class as "oth a"stract and final*

2!.*an we instantiate an abstract class? An abstract class can ne$er be instantiated. Its sole purpose is to be e"tended (subclassed . 2$.What are the differences between nterface and Abstract class? Abstract *lass An abstract class can pro$ide complete& default code and8or just the details that ha$e to be o$erridden. nterfaces An interface cannot pro$ide any code at all&just the signature.

In case of abstract class& a class may e"tend only A *lass may implement se$eral interfaces. one abstract class. An abstract class can ha$e non-abstract methods. An abstract class can ha$e instance $ariables. All methods of an Interface are abstract. An Interface cannot ha$e instance $ariables.

An abstract class can ha$e any $isibility: public& An Interface $isibility must be public (or none.

pri$ate& protected. If we add a new method to an abstract class then we ha$e the option of pro$iding default implementation and therefore all the e"isting code might wor! properly. An abstract class can contain constructors . Abstract classes are fast. If we add a new method to an Interface then we ha$e to trac! down all the implementations of the interface and define implementation for the new method. An Interface cannot contain constructors . Interfaces are slow as it re#uires e"tra indirection to find corresponding method in the actual class.

2(.When should use abstract classes and when should use interfaces? 7se nterfaces when8

0ou see that something in your design will change fre#uently. If $arious implementations only share method signatures then it is better to use Interfaces. you need some classes to use some methods which you don2t want to be included in the class& then you go for the interface& which ma!es it easy to just implement and ma!e use of the methods defined in the interface.

7se Abstract *lass when8


If $arious implementations are of the same !ind and use common beha$ior or status then abstract class is better to use. 9hen you want to pro$ide a generali7ed form of abstraction and lea$e the implementation tas! with the inheriting subclass. Abstract classes are an e"cellent way to create planned inheritance hierarchies. They2re also a good choice for nonleaf classes in class hierarchies.

2-.When "ou declare a #ethod as abstract9 can other nonabstract #ethods access it? 0es& other nonabstract methods can access a method that you declare as abstract. 3..*an there be an abstract class with no abstract #ethods in it? 0es& there can be an abstract class without abstract methods. 31.What is *onstructor5 A constructor is a special method whose tas! is to initiali7e the object of its class.

It is special because its name is the sa#e as the class na#e. They do not ha$e return types& not e$en 'oid and therefore they cannot return $alues. They cannot be inherited& though a deri$ed class can call the base class constructor. *onstructor is in$o!ed whene$er an object of its associated class is created.

32.%ow does the &a'a default constructor be pro'ided? If a class defined by the code does not ha$e any constructor& compiler will automatically pro$ide one no-parameter-constructor (default-constructor for the class in the byte code. The access modifier (public8pri$ate8etc. of the default constructor is the same as the class itself. 33.*an constructor be inherited5 1o& constructor cannot be inherited& though a deri$ed class can call the base class constructor. 34.What are the differences between *ontructors and 2ethods? *onstructors Purpose 2odifiers +eturn :"pe ,a#e *reate an instance of a class *annot be a"stract, final, native, static& or synchroni-ed 1o return type& not e$en $oid ;ame name as the class (first letter is capitali7ed by con$ention -- usually a noun .efers to another constructor in the same class. If used& it must be the first line of the constructor *alls the constructor of the parent class. If used& must be the first line of the constructor *onstructors are not inherited 2ethods :roup )a$a statements *an be a"stract, final, native, static& or synchroni-ed $oid or a $alid return type Any name e"cept the class. -ethod names begin with a lowercase letter by con$ention -- usually the name of an action .efers to an instance of the owning class. *annot be used by static methods. *alls an o$erridden method in the parent class -ethods are inherited

this

super

nheritance

35.%ow are this;< and super;< used with constructors5

*onstructors use this to refer to another constructor in the same class with a different parameter list. *onstructors use super to in$o!e the superclass2s constructor. If a constructor uses super& it must use it in the first line< otherwise& the compiler will complain.

3!.What are the differences between *lass 2ethods and nstance 2ethods? *lass 2ethods nstance 2ethods Instance methods on the other hand re#uire an instance of the class to e"ist before they can be called& so an instance of a class needs to be created by using the new !eyword. Instance methods operate on specific instances of classes. Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class. Instance methods are not declared as static.

*lass methods are methods which are declared as static. The method can be called without creating an instance of the class

*lass methods can only operate on class members and not on instance members as class methods are unaware of instance members. *lass methods are methods which are declared as static. The method can be called without creating an instance of the class.

3$.%ow are this;< and super;< used with constructors5 *onstructors use this to refer to another constructor in the same class with a different parameter list. *onstructors use super to in$o!e the superclass2s constructor. If a constructor uses super& it must use it in the first line< otherwise& the compiler will complain.

Access Specifiers34
3(.What are Access Specifiers? (ne of the techni#ues in object-oriented programming is encapsulation. It concerns the hiding of data in a class and ma!ing this class a$ailable only through methods. )a$a allows you to control access to classes& methods& and fields $ia so-called access specifiers.. 3-.What are Access Specifiers a'ailable in &a'a5 )a$a offers four access specifiers& listed below in decreasing accessibility:

Public- pu"lic classes& methods& and fields can be accessed from e$erywhere.

Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong& within its subclasses& and within classes of the same pac!age. /efault;no specifier<4 If you do not set access to specific le$el& then such a class& method& or field will be accessible from inside the same pac!age to which the class& method& or field belongs& but not from outside this pac!age. Pri'ate- private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not $isible within subclasses and are not inherited by subclasses. Situation
public protected

default yes no

private

Accessible to class from same pac!age5 Accessible to class from different pac!age5 4..What is final #odifier5

yes yes

yes no& unless it is a su"class

no no

The final modifier !eyword ma!es that the programmer cannot change the $alue anymore. The actual meaning depends on whether it is applied to a class& a $ariable& or a method.

final *lasses- A final class cannot ha$e subclasses. final =ariables- A final $ariable cannot be changed once it is initiali7ed. final 2ethods- A final method cannot be o$erridden by subclasses.

41.What are the uses of final #ethod? There are two reasons for mar!ing a method as final:

,isallowing subclasses to change the meaning of the method. Increasing efficiency by allowing the compiler to turn calls to the method into inline )a$a code.

42.What is static bloc6? ;tatic bloc! which e"actly e"ecuted e"actly once when the class is first loaded into )=-. +efore going to the main method the static bloc! will e"ecute. 43.What are static 'ariables?

=ariables that ha$e only one copy per class are !nown as static $ariables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static !eyword as a modifier.
static t#pe var$dentifier;

where& the name of the $ariable is $arIdentifier and its data type is specified by type. ,ote: ;tatic $ariables that are not e"plicitly initiali7ed in the code are automatically initiali7ed with a default $alue. The default $alue depends on the data type of the $ariables. 44.What is the difference between static and non4static 'ariables? A static $ariable is associated with the class as a whole rather than with specific instances of a class. 1on-static $ariables ta!e on uni#ue $alues with each object instance. 45.What are static #ethods? -ethods declared with the !eyword static as modifier are called static methods or class methods. They are so called because they affect a class as a whole& not a particular instance of the class. ;tatic methods are always in$o!ed without reference to a particular instance of a class. ,ote:The use of a static method suffers from the following restrictions:

static method can only call other static methods* static method must only access static data* static method cannot reference to the current o".ect using #eywords super or this*

*olletion34
>4.What is an terator 5 The Iterator interface is used to step through the elements of a *ollection. Iterators let you process each element of a *ollection.

Iterators are a generic way to go through all the elements of a *ollection no matter how it is organi7ed. Iterator is an Interface implemented a different way for e$ery *ollection.

>?.%ow do "ou tra'erse throu1h a collection usin1 its terator? To use an iterator to tra$erse through the contents of a collection& follow these steps:

(btain an iterator to the start of the collection by calling the collection@ABs iterator() method.

;et up a loop that ma!es a call to hasNext(). /a$e the loop iterate as long as hasNext() returns true. 9ithin the loop& obtain each element by calling ne)t;<.

>C.%ow do "ou re#o'e ele#ents durin1 teration5 Iterator also has a method remove() when remo$e is called& the current element in the iteration is deleted. >D.What is the difference between Enu#eration and terator? Enu#eration Enumeration doesn2t ha$e a remo$e( method Enumeration acts as .ead-only interface& because it has the methods only to tra$erse and fetch the objects terator Iterator has a remo$e( method *an be a"stract, final, native, static& or synchroni-ed

,ote: ;o Enumeration is used whene$er we want to ma!e *ollection objects as .ead-only. EF.%ow is >ist terator5 >ist terator is just li!e Iterator& e"cept it allows us to access the collection in either the forward or bac!ward direction and lets us modify an element E3.What is the >ist interface5 The Gist interface pro$ides support for ordered collections of objects. Gists may contain duplicate elements. EH.What are the #ain i#ple#entations of the >ist interface 5 The main implementations of the Gist interface are as follows :

Arra">ist : .esi7able-array implementation of the Gist interface. The best all-around implementation of the Gist interface. =ector : ;ynchroni7ed resi7able-array implementation of the Gist interface with additional 'legacy methods.' >in6ed>ist : ,oubly-lin!ed list implementation of the Gist interface. -ay pro$ide better performance than the ArrayGist implementation if elements are fre#uently inserted or deleted within the list. Iseful for #ueues and double-ended #ueues (de#ues .

EJ.What are the ad'anta1es of Arra">ist o'er arra"s 5 ;ome of the ad$antages ArrayGist has o$er arrays are:

It can grow dynamically It pro$ides more powerful insertion and search mechanisms than arrays.

E>./ifference between Arra">ist and =ector 5 Arra">ist ArrayGist is ,O: synchroni7ed by default. ArrayGist can use only Iterator to access the elements. The ArrayGist increases its array si7e by EF percent if it runs out of room. ArrayGist has no default si7e. =ector =ector Gist is synchroni7ed by default. =ector list can use Iterator and Enumeration Interface to access the elements. A =ector defaults to doubling the si7e of its array if it runs out of room 9hile $ector has a default si7e of 3F.

EE.%ow to obtain Arra" fro# an Arra">ist 5 Array can be obtained from an ArrayGist using toArray() method on ArrayGist.
%ist arra#%ist & ne' (rra#%ist(); arra#%ist.add()*+ ,bjecta./ & arrayList.toArray();

E4.Wh" insertion and deletion in Arra">ist is slow co#pared to >in6ed>ist 5 Arra">ist internally uses and array to store the elements& when that array gets filled by inserting elements a new array of roughly 3.E times the si7e of the original array is created and all the data of old array is copied to new array. ,uring deletion& all elements present in the array after the deleted elements ha$e to be mo$ed one step bac! to fill the space created by deletion. In lin!ed list data is stored in nodes that ha$e reference to the pre$ious node and the ne"t node so adding element is simple as creating the node an updating the ne"t pointer on the last node and the pre$ious pointer on the new node. ,eletion in lin!ed list is fast because it in$ol$es only updating the ne"t pointer in the node before the deleted node and updating the pre$ious pointer in the node after the deleted node.

E?.Wh" are terators returned b" Arra">ist called ?ail ?ast ? +ecause& if list is structurally modified at any time after the iterator is created& in any way e"cept through the iterator2s own remo$e or add methods& the iterator will throw a *oncurrent-odificationE"ception. Thus& in the face of concurrent modification& the iterator fails #uic!ly and cleanly& rather than ris!ing arbitrary& non-deterministic beha$ior at an undetermined time in the future. EC.%ow do "ou decide when to use Arra">ist and When to use >in6ed>ist? If you need to support random access& without inserting or remo$ing elements from any place other than the end& then ArrayGist offers the optimal collection. If& howe$er& you need to fre#uently add and remo$e elements from the middle of the list and only access the list elements se#uentially& then Gin!edGist offers the better implementation. ED.What is the Set interface ? The ;et interface pro$ides methods for accessing the elements of a finite mathematical set ;ets do not allow duplicate elements

*ontains no methods other than those inherited from *ollection It adds the restriction that duplicate elements are prohibited Two ;et objects are e#ual if they contain the same elements

4F.What are the #ain #ple#entations of the Set interface 5 The main implementations of the Gist interface are as follows:

/ash;et Tree;et Gin!ed/ash;et Enum;et

43.What is a %ashSet 5

A /ash;et is an unsorted& unordered ;et. It uses the hashcode of the object being inserted (so the more efficient your hashcode( implementation the better access performance you%ll get . Ise this class when you want a collection with no duplicates and you don%t care about order when you iterate through it.

4H.What is a :reeSet ? Tree;et is a ;et implementation that !eeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator pro$ided at creation time. 4J.What is an Enu#Set ? An Enum;et is a speciali7ed set for use with enum types& all of the elements in the Enum;et type that is specified& e"plicitly or implicitly& when the set is created. 4>./ifference between %ashSet and :reeSet 5 %ashSet /ash;et is under set interface i.e. it does not guarantee for either sorted order or se#uence order. 9e can add any type of elements to hash set. :reeSet Tree;et is under set i.e. it pro$ides elements in a sorted order (acceding order . 9e can add only similar types of elements to tree set.

4E.What is a 2ap ? A map is an object that stores associations between !eys and $alues (!ey8$alue pairs . :i$en a !ey& you can find its $alue. +oth !eys and $alues are objects.

The !eys must be uni#ue& but the $alues may be duplicated. ;ome maps can accept a null !ey and null $alues& others cannot.

44.What are the #ain #ple#entations of the 2ap interface 5 The main implementations of the Gist interface are as follows:

/ash-ap /ashTable Tree-ap Enum-ap

4?.What is a :ree2ap ?

Tree-ap actually implements the ;orted-ap interface which e"tends the -ap interface. In a Tree-ap the data will be sorted in ascending order of !eys according to the natural order for the !ey2s class& or by the comparator pro$ided at creation time. Tree-ap is based on the .ed-+lac! tree data structure. 4C.%ow do "ou decide when to use %ash2ap and when to use :ree2ap ? 6or inserting& deleting& and locating elements in a -ap& the /ash-ap offers the best alternati$e. If& howe$er& you need to tra$erse the !eys in a sorted order& then Tree-ap is your better alternati$e. ,epending upon the si7e of your collection& it may be faster to add elements to a /ash-ap& then con$ert the map to a Tree-ap for sorted !ey tra$ersal. 4D./ifference between %ash2ap and %ashtable 5 %ash2ap /ash-ap lets you ha$e null $alues as well as one null !ey. The iterator in the /ash-ap is fail-safe (If you change the map while iterating& you%ll !now . /ash-ap is unsynchroni7ed. %ashtable /ashTable does not allows null $alues as !ey and $alue. The enumerator for the /ashtable is not failsafe. /ashtable is synchroni7ed.

,ote: (nly one 1IGG is allowed as a !ey in /ash-ap. /ash-ap does not allow multiple !eys to be 1IGG. 1e$ertheless& it can ha$e multiple 1IGG $alues. ?F.%ow does a %ashtable internall" #aintain the 6e"4'alue pairs? Tree-ap actually implements the ;orted-ap interface which e"tends the -ap interface. In a Tree-ap the data will be sorted in ascending order of !eys according to the natural order for the !ey2s class& or by the comparator pro$ided at creation time. Tree-ap is based on the .ed-+lac! tree data structure. ?3.What Are the different *ollection =iews :hat 2aps Pro'ide? -aps Pro$ide Three *ollection =iews.

@e" Set - allow a map2s contents to be $iewed as a set of !eys. =alues *ollection - allow a map2s contents to be $iewed as a set of $alues. Entr" Set - allow a map2s contents to be $iewed as a set of !ey-$alue mappings.

?H.What is a @e"Set =iew ? Key;et is a set returned by the keySet() method of the -ap Interface& It is a set that contains all the !eys present in the -ap. ?J.What is a =alues *ollection =iew ? =alues *ollection =iew is a collection returned by the values() method of the -ap Interface& It contains all the objects present as $alues in the map. ?>.What is an Entr"Set =iew ? Entry ;et $iew is a set that is returned by the entrySet() method in the map and contains (bjects of type -ap. Entry each of which has both Key and =alue. ?E.%ow do "ou sort an Arra">ist ;or an" list< of user4defined ob5ects ? *reate an implementation of the .ava*lang*Compara"le interface that !nows how to order your objects and pass it to .ava*util*Collections*sort(Gist& *omparator . ?4.What is the *o#parable interface ? The *omparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respecti$ely. The objects of the class implementing the *omparable interface can be ordered. The *omparable interface in the generic form is written as follows:
interface "omparable012

where T is the name of the type parameter* All classes implementing the *omparable interface must implement the compare1o() method that has the return type as an integer. The signature of the compare1o() method is as follows:
int i & object3.compare1o(object4)

If object3 L objectH: The $alue of i returned will be negati$e. If object3 M objectH: The $alue of i returned will be positi$e. If object3 N objectH: The $alue of i returned will be 7ero.

??.What are the differences between the *o#parable and *o#parator interfaces 5 *o#parable It uses the compareTo%) method. int o".ectOne*compareTo%o".ectTwo)* It is necessary to modify the class whose instance is going to be sorted. (nly one sort se#uence can be created. It is fre#uently used by the API classes. *o#parato t uses the compare%) method. int compare%O".One, O".Two) A separate class can be created in order to sort the instances. -any sort se#uences can be created. It used by third-party classes to sort instances.

E"ception /andling:$(.What is an e)ception? An e$ception is an e$ent& which occurs during the e"ecution of a program& that disrupts the normal flow of the program2s instructions. $-.What is error? An Error indicates that a non-reco$erable condition has occurred that should not be caught. Error& a subclass of Throwable& is intended for drastic problems& such as (ut(f-emoryError& which would be reported by the )=- itself. (..Which is superclass of E)ception? A:hrowableA& the parent class of all e"ception related classes. (1.What are the ad'anta1es of usin1 e)ception handlin1? E"ception handling pro$ides the following ad$antages o$er 'traditional' error management techni#ues:

;eparating Error /andling *ode from '.egular' *ode. Propagating Errors Ip the *all ;tac!. :rouping Error Types and Error ,ifferentiation.

(2.What are the t"pes of E)ceptions in &a'a? There are two types of e"ceptions in )a$a& unchec!ed e"ceptions and chec!ed e"ceptions.

*hec6ed e)ceptions: A chec!ed e"ception is some subclass of E"ception (or E"ception itself & e"cluding class .untimeE"ception and its subclasses. Each method must either handle all chec!ed e"ceptions by supplying a catch clause or list each unhandled chec!ed e"ception as a thrown e"ception. 7nchec6ed e)ceptions3 All E"ceptions that e"tend the .untimeE"ception class are unchec!ed e"ceptions. *lass Error and its subclasses also are unchec!ed.

(3.Wh" Errors are ,ot *hec6ed? A unchec!ed e"ception classes which are the error classes (Error and its subclasses are e"empted from compile-time chec!ing because they can occur at many points in the program and reco$ery from them is difficult or impossible. A program declaring such e"ceptions would be pointlessly. (4.Wh" +unti#e E)ceptions are ,ot *hec6ed? The runtime e$ception classes (5untime6xception and its subclasses are e"empted from compile-time chec!ing because& in the judgment of the designers of the )a$a programming language& ha$ing to declare such e"ceptions would not aid significantly in establishing the correctness of programs. -any of the operations and constructs of the )a$a programming language can result in runtime e"ceptions. The information a$ailable to a compiler& and the le$el of analysis the compiler performs& are usually not sufficient to establish that such run-time e"ceptions cannot occur& e$en though this may be ob$ious to the programmer. .e#uiring such e"ception classes to be declared would simply be an irritation to programmers. (5.E)plain the si1nificance of tr"4catch bloc6s? 9hene$er the e"ception occurs in )a$a& we need a way to tell the )=- what code to e"ecute. To do this& we use the try and catch !eywords. The try is used to define a bloc! of code in which e"ceptions may occur. (ne or more catch clauses match a specific e"ception to a bloc! of code that handles it.

(!.What is the use of finall" bloc6? The finally bloc! encloses code that is always e"ecuted at some point after the try bloc!& whether an e"ception was thrown or not. This is right place to close files& release your networ! soc!ets& connections& and perform any other cleanup your code re#uires. ,ote: If the try bloc! e"ecutes with no e"ceptions& the finally bloc! is e"ecuted immediately after the try bloc! completes. It there was an e"ception thrown& the finally bloc! e"ecutes immediately after the proper catch bloc! completes ($.What if there is a brea6 or return state#ent in tr" bloc6 followed b" finall" bloc6? If there is a return statement in the try bloc!& the finally bloc! e"ecutes right after the return statement encountered& and before the return e"ecutes. ((.*an we ha'e the tr" bloc6 without catch bloc6? 0es& we can ha$e the try bloc! without catch bloc!& but finally bloc! should follow the try bloc!. ,ote3 It is not $alid to use a try clause without either a catch clause or a finally clause. (-.What is the difference throw and throws? throws3 Ised in a method2s signature if a method is capable of causing an e"ception that it does not handle& so that callers of the method can guard themsel$es against that e"ception. If a method is declared as throwing a particular class of e"ceptions& then any other method that calls it must either ha$e a try-catch clause to handle that e"ception or must be declared to throw that e"ception (or its superclass itself.

A method that does not handle an e"ception it throws has to announce this:
public void m#func(int ar7) throws M#6xception { 8 }

throw3 Ised to trigger an e"ception. The e"ception will be caught by the nearest try-catch clause that can catch that type of e"ception. The flow of e"ecution stops immediately after the throw statement< any subse#uent statements are not e"ecuted.

To throw an user-defined e"ception within a bloc!& we use the throw command:


throw ne' M#6xception(9$ al'a#s 'anted to thro' an exception:9);

-..%ow to create custo# e)ceptions? A. +y e"tending the E"ception class or one of its subclasses. E)a#ple3
class M#6xception extends 6xception { public M#6xception() { super(); } public M#6xception( trin7 s) { super(s); } }

-1.What are the different wa"s to handle e)ceptions? There are two ways to handle e"ceptions:

9rapping the desired code in a try bloc! followed by a catch bloc! to catch the e"ceptions. Gist the desired e"ceptions in the throws clause of the method and let the caller of the method handle those e"ceptions.

-ultithreading:-2.What are three wa"s in which a thread can enter the waitin1 state? Or What are different wa"s in which a thread can enter the waitin1 state? A thread can enter the waiting state by the following ways: 3. In$o!ing its sleep( method& H. +y bloc!ing on I8(

J. +y unsuccessfully attempting to ac#uire an object2s loc! >. +y in$o!ing an object2s wait( method. E. It can also enter the waiting state by in$o!ing its (deprecated suspend( method. -3.What is the difference between "ieldin1 and sleepin1? 9hen a tas! in$o!es its yield( method& it returns to the ready state& either from waiting& running or after its creation. 9hen a tas! in$o!es its sleep( method& it returns to the waiting state from a running state. -4.%ow to create #ultithreaded pro1ra#? E)plain different wa"s of usin1 thread? When a thread is created and started9 what is its initial state? Or E)tendin1 :hread class or i#ple#entin1 +unnable nterface. Which is better? 0ou ha$e two ways to do so. 6irst& ma!ing your class 'e"tends' Thread class. The other way is ma!ing your class implement '.unnable' interface. The latter is more ad$antageous& cause when you are going for multiple inheritance& then only interface can help. . If you are already inheriting a different class& then you ha$e to go for .unnable Interface. (therwise you can e"tend Thread class. Also& if you are implementing interface& it means you ha$e to implement all methods in the interface. +oth Thread class and .unnable interface are pro$ided for con$enience and use them as per the re#uirement. +ut if you are not e"tending any class& better e"tend Thread class as it will sa$e few lines of coding. (therwise performance wise& there is no distinguishable difference. A thread is in the ready state after it has been created and started. -5.What is #utual e)clusion? %ow can "ou ta6e care of #utual e)clusion usin1 &a'a threads? -utual e"clusion is a phenomenon where no two processes can access critical regions of memory at the same time. Ising )a$a multithreading we can arri$e at mutual e"clusion. 6or mutual e"clusion& you can simply use the synchroni7ed !eyword and e"plicitly or implicitly pro$ide an (bject& any (bject& to synchroni7e on. The synchroni7ed !eyword can be applied to a class& to a method& or to a bloc! of code. There are se$eral methods in )a$a used for communicating mutually e"clusi$e threads such as wait( & notify( & or notifyAll( . 6or e"ample& the notifyAll( method wa!es up all threads that are in the wait list of an object. -!.What is the difference between pree#pti'e schedulin1 and ti#e slicin1? Inder preempti$e scheduling& the highest priority tas! e"ecutes until it enters the waiting or dead states or a higher priority tas! comes into e"istence. Inder time slicing& a tas! e"ecutes for a predefined slice of time and then re-enters the pool of ready tas!s. The scheduler then determines which tas! should e"ecute ne"t& based on priority and other factors. -$.What in'o6es a threadBs run;< #ethod?

After a thread is started& $ia its start( method of the Thread class& the )=- in$o!es the thread2s run( method when the thread is initially e"ecuted. -(.What is the purpose of the wait;<9 notif";<9 and notif"All;< #ethods? The wait( & notify( and notifyAll( methods are used to pro$ide an efficient way for thread intercommunication. --.What is thread? What are the hi1h4le'el thread states? Or 1...What are the states associated in the thread? A thread is an independent path of e"ecution in a system. The high-le$el thread states are ready& running& waiting and dead. 1.1.What is deadloc6? 9hen two threads are waiting for each other and can%t proceed until the first thread obtains a loc! on the other thread or $ice $ersa& the program is said to be in a deadloc!. 1.2.%ow does #ultithreadin1 ta6e place on a co#puter with a sin1le *P7? The operating system2s tas! scheduler allocates e"ecution time to multiple tas!s. +y #uic!ly switching between e"ecuting tas!s& it creates the impression that tas!s e"ecute se#uentially. 1.3.What are s"nchroniCed #ethods and s"nchroniCed state#ents? ;ynchroni7ed methods are methods that are used to control access to an object. A thread only e"ecutes a synchroni7ed method after it has ac#uired the loc! for the method2s object or class. ;ynchroni7ed statements are similar to synchroni7ed methods. A synchroni7ed statement can only be e"ecuted after a thread has ac#uired the loc! for the object or class referenced in the synchroni7ed statement. 1.4.*an &a'a ob5ect be loc6ed down for e)clusi'e use b" a 1i'en thread? Or What happens when a thread cannot acDuire a loc6 on an ob5ect? 0es. 0ou can loc! an object by putting it in a 'synchroni7ed' bloc!. The loc!ed object is inaccessible to any thread other than the one that e"plicitly claimed it. If a thread attempts to e"ecute a synchroni7ed method or synchroni7ed statement and is unable to ac#uire an object2s loc!& it enters the waiting state until the loc! becomes a$ailable.

1.5.WhatEs the difference between the #ethods sleep;< and wait;<? The sleep method is used when the thread has to be put aside for a fi"ed amount of time. E": sleep(3FFF & puts the thread aside for e"actly one second. The wait method is used to put the thread aside for up to the specified time. It could wait for much lesser time if it recei$es a notify( or notifyAll( call. E": wait(3FFF & causes a wait of up to one second. The method wait( is defined in the (bject and the method sleep( is defined in the class Thread. 1.!.What is the difference between process and thread? A thread is a separate path of e"ecution in a program. A Process is a program in e"ecution. 1.$.What is dae#on thread and which #ethod is used to create the dae#on thread? ,aemon threads are threads with low priority and runs in the bac! ground doing the garbage collection operation for the ja$a runtime system. The set,aemon( method is used to create a daemon thread. These threads run without the inter$ention of the user. To determine if a thread is a daemon thread& use the accessor method is,aemon( 9hen a standalone application is run then as long as any user threads are acti$e the )=- cannot terminate& otherwise the )=- terminates along with any daemon threads which might be acti$e. Thus a daemon thread is at the mercy of the runtime system. ,aemon threads e"ist only to ser$e user threads. 1.(.What do "ou understand b" S"nchroniCation? Or What is s"nchroniCation and wh" is it i#portant? Or /escribe s"nchroniCation in respect to #ultithreadin1? Or What is s"nchroniCation? 9ith respect to multithreading& ;ynchroni7ation is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access a particular resource at a time. In non synchroni7ed multithreaded application& it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object2s $alue. ;ynchroni7ation pre$ents such type of data corruption which may otherwise lead to dirty reads and significant errors. E.g. synchroni7ing a function: public synchroni7ed $oid -ethod3 ( O

88 method code. P E.g. synchroni7ing a bloc! of code inside a function: public -ethodH ( O synchroni7ed (this O 88 synchroni7ed code here. P P 1.-.When "ou will s"nchroniCe a piece of "our code? 9hen you e"pect that your shared code will be accessed by different threads and these threads may change a particular data causing data corruption& then they are placed in a synchroni7ed construct or a synchroni7ed method. 11..Wh" would "ou use a s"nchroniCed bloc6 's. s"nchroniCed #ethod? ;ynchroni7ed bloc!s place loc!s for shorter periods than synchroni7ed methods. 111.What is an ob5ectBs loc6 and which ob5ects ha'e loc6s? Answer: An object2s loc! is a mechanism that is used by multiple threads to obtain synchroni7ed access to the object. A thread may e"ecute a synchroni7ed method of an object only after it has ac#uired the object2s loc!. All objects and classes ha$e loc!s. A class2s loc! is ac#uired on the class2s *lass object. 112.*an a loc6 be acDuired on a class? 0es& a loc! can be ac#uired on a class. This loc! is ac#uired on the class2s *lass object. 113.What state does a thread enter when it ter#inates its processin1? 9hen a thread terminates its processing& it enters the dead state. 114.%ow would "ou i#ple#ent a thread pool? public class ThreadPool implements :hreadPool nt This class is an generic implementation of a thread pool& which ta!es the following input a ;i7e of the pool to be constructed b 1ame of the class which implements .unnable and constructs a thread pool with acti$e threads that are waiting for acti$ation. (nce the threads ha$e finished processing they come bac! and wait once again in the pool.

This thread pool engine can be loc!ed i.e. if some internal operation is performed on the pool then it is preferable that the thread engine be loc!ed. Goc!ing ensures that no new threads are issued by the engine. /owe$er& the currently e"ecuting threads are allowed to continue till they come bac! to the passi$ePool. 115. s there a separate stac6 for each thread in &a'a? 0es. E$ery thread maintains its own separate stac!& called .untime ;tac! but they share the same memory. Elements of the stac! are the method in$ocations& called acti$ation records or stac! frame. The acti$ation record contains pertinent information about a method li!e local $ariables.

Swing:11!.What is the difference between Swin1 and AW: co#ponents? A9T components are hea$y-weight& whereas ;wing components are lightweight. /ence ;wing wor!s faster than A9T. /ea$y weight components depend on the local windowing tool!it. 6or e"ample& ja$a.awt.+utton is a hea$y weight component. Pluggable loo! and feel possible using ja$a ;wing. Also& we can switch from one loo! and feel to another at runtime in swing which is not possible in A9T. 11$.,a#e the containers which use 0order >a"out as their default la"out? window& 6rame and ,ialog classes. 11(.,a#e *ontainer classes. 9indow& 6rame& ,ialog& 6ile,ialog& Panel& Applet& or ;crollPane 11-.%ow can a F7 co#ponent handle its own e'ents? A component can handle its own e$ents by implementing the re#uired e$ent-listener interface and adding itself as its own e$ent listener. 12..What is the difference between the paint;< and repaint;< #ethods? The paint( method supports painting $ia a :raphics object. The repaint( method is used to cause paint( to be in$o!ed by the A9T painting thread.

121.Which pac6a1e has li1ht wei1ht co#ponents? ja$a".;wing pac!age contains light weight components. All components in ;wing& e"cept )Applet& ),ialog& )6rame and )9indow are lightweight components. 122.What are peerless co#ponents? The peerless components are called light weight components. 123.What is a *ontainer in a F7 ? A *ontainer contains and arranges other components (including other containers through the use of layout managers& which use specific layout policies to determine where components should go as a function of the si7e of the container. 124.%ow are the ele#ents of a Frid0a1>a"out or1aniCed? Or What is a la"out #ana1er and what are different t"pes of la"out #ana1ers a'ailable in 5a'a Swin1? Or %ow are the ele#ents of different la"outs or1aniCed? A layout manager is an object that is used to organi7e components in a container. The different layouts a$ailable are 6lowGayout& +orderGayout& *ardGayout& :ridGayout and :rid+agGayout. 6lowGayout: The elements of a 6lowGayout are organi7ed in a top to bottom& left to right fashion. +orderGayout: The elements of a +orderGayout are organi7ed at the borders (1orth& ;outh& East and 9est and the center of a container. *ardGayout: The elements of a *ardGayout are stac!ed& on top of the other& li!e a dec! of cards. :ridGayout: The elements of a :ridGayout are of e#ual si7e and are laid out using the s#uare of a grid. :rid+agGayout: The elements of a :rid+agGayout are organi7ed according to a grid. /owe$er& the elements may be different si7es and may occupy more than one row or column of the grid. In addition& the rows and columns may ha$e different si7es. 125.What ad'anta1e do &a'aBs la"out #ana1ers pro'ide o'er traditional windowin1 s"ste#s?

)a$a uses layout managers to lay out components in a consistent manner across all windowing platforms. ;ince )a$a2s layout managers aren2t tied to absolute si7ing and positioning& they are able to accommodate platform-specific differences among windowing systems. 12!.What #ethod is used to specif" a containerBs la"out? The setGayout( method is used to specify a container2s layout. 6or e"ample& setGayout(new 6lowGayout( < will be set the layout as 6lowGayout. 12$.Which *ontainer #ethod is used to cause a container to be laid out and redispla"ed? $alidate( 12(.,a#e *o#ponent subclasses that support paintin1. The *an$as& 6rame& Panel& and Applet classes support painting. 12-.What is the purpose of the enableE'ents;< #ethod? The enableE$ents( method is used to enable an e$ent for a particular component. 1ormally& an e$ent is enabled when a listener is added to an object for a particular e$ent. The enableE$ents( method is used by objects that handle e$ents by o$erriding their e$ent-dispatch methods. 13..What is the difference between a Window and a ?ra#e? The 6rame class e"tends 9indow to define a main application window that can ha$e a menu bar. 131.What do hea'" wei1ht co#ponents #ean? /ea$y weight components li!e Abstract 9indow Tool!it (A9T depend on the local windowing tool!it. 6or e"ample& ja$a.awt .+utton is a hea$y weight component. 132.What is the difference between a Scrollbar and a ScrollPane? A ;crollbar is just a *omponent& but not a *ontainer. A ;crollPane is a *ontainer. A ;crollPane handles its own e$ents and performs its own scrolling. 133.What is the preferred siCe of a co#ponent? The preferred si7e of a component is the minimum component si7e that will allow the component to display normally. 134.Which containers use a ?low>a"out as their default la"out? The Panel and Applet classes use the 6lowGayout as their default layout.

9rapper *lasses:135.What are Wrapper *lasses? /escribe the wrapper classes in &a'a. 9rapper classes are classes that allow primiti$e types to be accessed as objects. 9rapper class is wrapper around a primiti$e data type. 6ollowing table lists the primiti$e types and the corresponding wrapper classes: Pri#iti'e +oolean +yte *har double 6loat Int Gong ;hort =oid Wrapper ja$a.lang.+oolean ja$a.lang.+yte ja$a.lang.*haracter ja$a.lang.,ouble ja$a.lang.6loat ja$a.lang.Integer ja$a.lang.Gong ja$a.lang.;hort ja$a.lang.=oid

JDBC:13!.What is the &/0*? )a$a ,atabase *onnecti$ity (&/0* is a standard )a$a API to interact with relational databases form )a$a. &/0* has set of classes and interfaces which can use from )a$a application and tal! to database without learning .,+-; details and using ,atabase ;pecific ),+* ,ri$ers. 13$.What are the new features added to &/0* 4..? The major features added in ),+* >.F include :

Auto-loading of ),+* dri$er class *onnection management enhancements ;upport for 5o'$d ;QG type ,ata;et implementation of ;QG using Annotations ;QG e"ception handling enhancements

;QG R-G support

13(.E)plain 0asic Steps in writin1 a &a'a pro1ra# usin1 &/0*? ),+* ma!es the interaction with .,+-; simple and intuiti$e. 9hen a )a$a application needs to access database :

Goad the .,+-; specific ),+* dri$er because this dri$er actually communicates with the database (Incase of ),+* >.F this is automatically loaded . (pen the connection to database which is then used to send ;QG statements and get results bac!. *reate ),+* ;tatement object. This object contains ;QG #uery. E"ecute statement which returns resultset(s . .esult;et contains the tuples of database table as a result of ;QG #uery. Process the result set. *lose the connection.

13-.E)aplain the &/0* Architecture. The ),+* Architecture consists of two layers:

The ),+* API& which pro$ides the application4to4&/0* 2ana1er connection. The ),+* ,ri$er API& which supports the &/0* 2ana1er4to4/ri'er *onnection.

The ),+* API uses a dri$er manager and database-specific dri$ers to pro$ide transparent connecti$ity to heterogeneous databases. The ),+* dri$er manager ensures that the correct dri$er is used to access each data source. The dri$er manager is capable of supporting multiple concurrent dri$ers connected to multiple heterogeneous databases. The location of the dri$er manager with respect to the ),+* dri$ers and the )a$a application is shown in 6igure 3.

6igure 3: ),+* Architecture 14..What are the #ain co#ponents of &/0* ? The life cycle of a ser$let consists of the following phases:

/ri'er2ana1er: -anages a list of database dri$ers. -atches connection re#uests from the ja$a application with the proper database dri$er using communication subprotocol. The first dri$er that recogni7es a certain subprotocol under ),+* will be used to establish a database *onnection.

/ri'er: The database communications lin!& handling all communication with the database. 1ormally& once the dri$er is loaded& the de$eloper need not call it e"plicitly. *onnection : Interface with all methods for contacting a database.The connection object represents communication conte"t& i.e.& all communication with database is through connection object only.

State#ent : Encapsulates an ;QG statement which is passed to the database to be parsed& compiled& planned and e"ecuted. +esultSet: The .esult;et represents set of rows retrie$ed due to #uery e"ecution.

141.%ow the &/0* application wor6s? A ),+* application can be logically di$ided into two layers: 3. /ri'er la"er H. Application la"er

,ri$er layer consists of ,ri$er-anager class and the a$ailable ),+* dri$ers. The application begins with re#uesting the ,ri$er-anager for the connection. An appropriate dri$er is choosen and is used for establishing the connection. This connection is gi$en to the application which falls under the application layer. The application uses this connection to create ;tatement !ind of objects& through which ;QG commands are sent to bac!end and obtain the results.

6igure H: ),+* Application 142.%ow do load a database dri'er with &/0* 4.. G &a'a !? Pro$ided the )A. file containing the dri$er is properly configured& just place the )A. file in the classpath. )a$a de$elopers ,O longer need to e"plicitly load ),+* dri$ers using code li!e "lass.for;ame() to register a ),+* dri$er.The ,ri$er-anager class ta!es care of this by automatically locating a suitable dri$er when the <riverMana7er.7et"onnection() method is called. This feature is bac!ward-compatible& so no changes are needed to the e"isting ),+* code.

143.What is &/0* /ri'er interface? The ),+* ,ri$er interface pro$ides $endor-specific implementations of the abstract classes pro$ided by the ),+* API. Each $endor dri$er must pro$ide implementations of the
java.s=l."onnection, tatement,>repared tatement, "allable tatement, 5esult et and <river.

144.What does the connection ob5ect represents5 The connection object represents communication conte"t& i.e.& all communication with database is through connection object only. 145.What is State#ent 5 ;tatement acts li!e a $ehicle through which ;QG commands can be sent. Through the connection object we create statement !ind of objects. Through the connection object we create statement !ind of objects.
tatement stmt & conn.create tatement();

This method returns object which implements statement interface. 14!.What is PreparedState#ent? A prepared statement is an ;QG statement that is precompiled by the database. Through precompilation& prepared statements impro$e the performance of ;QG commands that are e"ecuted multiple times (gi$en that the database supports prepared statements . (nce compiled& prepared statements can be customi7ed prior to each e"ecution by altering predefined ;QG parameters.
>repared tatement pstmt & conn.prepare tatement(9?><(16 6M>%,@66 (%(5@ & A BC656 $< & A9); pstmt.setDi7<ecimal(3, 3EFGFF.HH); pstmt.set$nt(4, 33HEI4); 61

/ere: conn is an instance of the Connection class and "?" represents parameters*These parameters must "e specified "efore e$ecution 14$.What is the difference between a State#ent and a PreparedState#ent? State#ent A standard ;tatement is used to create a )a$a representation of a literal ;QG statement and PreparedState#ent A Prepared;tatement is a precompiled statement. This means that when the

e"ecute it on the database. ;tatement has to $erify its metadata against the database e$ery time.

Prepared;tatement is e"ecuted& the .,+-; can just run the Prepared;tatement ;QG statement without ha$ing to compile it first. 9hile a prepared statement has to $erify its metadata against the database only once. If you want to e"ecute a single ;QG statement multiple number of times& then go for P.EPA.E,;TATE-E1T. Prepared;tatement objects can be reused with passing different $alues to the #ueries

If you want to e"ecute the ;QG statement once go for ;TATE-E1T

14(.What are callable state#ents ? *allable statements are used from ),+* application to in$o!e stored procedures and functions. 14-.%ow to call a stored procedure fro# &/0* ? PG8;QG stored procedures are called from within ),+* programs by means of the prepare*all( method of the *onnection object created. A call to this method ta!es $ariable bind parameters as input parameters as well as output $ariables and creates an object instance of the *allable;tatement class. The following line of code illustrates this:
"allable tatement stprocJstmt & conn.prepare"all(9{call procname(A,A,A)}9);

/ere conn is an instance of the *onnection class. 15..What are t"pes of &/0* dri'ers? There are four types of dri$ers defined by ),+* as follows:

:"pe 13 &/0*GO/0*SThese re#uire an (,+* ((pen ,atabase *onnecti$ity dri$er for the database to be installed. This type of dri$er wor!s by translating the submitted #ueries into e#ui$alent (,+* #ueries and forwards them $ia nati$e API calls directly to the (,+* dri$er. It pro$ides no host redirection capability. :"pe23 ,ati'e AP ;partl"4&a'a dri'er<SThis type of dri$er uses a $endor-specific dri$er or database API to interact with the database. An e"ample of such an API is (racle (*I ((racle *all Interface . It also pro$ides no host redirection.

:"pe 33 Open Protocol4,etSThis is not $endor specific and wor!s by forwarding database re#uests to a remote database source using a net ser$er component. /ow the net ser$er component accesses the database is transparent to the client. The client dri$er communicates with the net ser$er using a database-independent protocol and the net ser$er translates this protocol into database calls. This type of dri$er can access any database. :"pe 43 Proprietar" Protocol4,et;pure &a'a dri'er<SThis has a same configuration as a type J dri$er but uses a wire protocol specific to a particular $endor and hence can access only that $endor2s database. Again this is all transparent to the client.

,ote3 Type 0 J12C driver is most preferred #ind of approach in J12C* 151.Which t"pe of &/0* dri'er is the fastest one5 ),+* 1et pure )a$a dri$er(Type I= is the fastest dri$er because it con$erts the ),+* calls into $endor specific protocol calls and it directly interacts with the database. 152./oes the &/0*4O/0* 0rid1e support #ultiple concurrent open state#ents per connection? 1o. 0ou can open only one ;tatement object per connection when you are using the ),+*(,+* +ridge. 15(.Which is the ri1ht t"pe of dri'er to use and when? Type I dri$er is handy for prototyping Type III dri$er adds security& caching& and connection control

Type III and Type I= dri$ers need no pre-installation

1ote: 3referred "y 4 out of 56 Java developers: Type +7. 15-.What are the standard isolation le'els defined b" &/0*? The $alues are defined in the class ja$a.s#l.*onnection and are:

T.A1;A*TI(1T1(1E T.A1;A*TI(1T.EA,T*(--ITTE, T.A1;A*TI(1T.EA,TI1*(--ITTE, T.A1;A*TI(1T.EPEATA+GET.EA,

T.A1;A*TI(1T;E.IAGIUA+GE

Any gi$en database may not support all of these le$els. 1!..What is resultset ? The .esult;et represents set of rows retrie$ed due to #uery e"ecution.
5esult et rs & stmt.executeKuer#(s=lKuer#);

1!2.What are the t"pes of resultsets? The $alues are defined in the class ja$a.s#l.*onnection and are:

specifies that a resultset is not scrollable& that is& rows within it can be ad$anced only in the forward direction. 1@>6J "5,%%J$; 6; $1$L6 specifies that a resultset is scrollable in either direction but is insensiti$e to changes committed by other transactions or other statements in the same transaction.
1@>6JF,5B(5<J,;%@

specifies that a resultset is scrollable in either direction and is affected by changes committed by other transactions or statements within the same transaction.
1@>6J "5,%%J 6; $1$L6

Note: A TYPE_FOR AR!_O"#Y resultset is always insensitive* 1!3.WhatEs the difference between :HPEIS*+O>>I ,SE,S : =E and :HPEIS*+O>>ISE,S : =E? :HPEIS*+O>>I ,SE,S : =E An insensiti$e resultset is li!e the snapshot of the data in the database when #uery was e"ecuted. After we get the resultset the changes made to data are not $isible through the resultset& and hence they are !nown as insensiti$e. Performance not effected with insensiti$e. 1!4.What is rowset? A .ow;et is an object that encapsulates a set of rows from either )a$a ,atabase *onnecti$ity (),+* result sets or tabular data sources li!e a file or spreadsheet. .ow;ets support component:HPEIS*+O>>ISE,S : =E A sensiti$e resultset does 1(T represent a snapshot of data& rather it contains points to those rows which satisfy the #uery condition. After we obtain the resultset if the data is modified then such modifications are $isible through resultset. ;ince a trip is made for e$ery V1etE operation& the performance drastically get affected.

based de$elopment models li!e )a$a+eans& with a standard set of properties and an e$ent notification mechanism. 1!5.What are the different t"pes of +owSet ? There are two types of .ow;et are there. They are:

*onnected - A connected .ow;et object connects to the database once and remains connected until the application terminates. /isconnected 4 A disconnected .ow;et object connects to the database& e"ecutes a #uery to retrie$e the data from the database and then closes the connection. A program may change the data in a disconnected .ow;et while it is disconnected. -odified data can be updated in the database after a disconnected .ow;et reestablishes the connection with the database.

1!!.What is the need of 0atch7pdates? The +atchIpdates feature allows us to group ;QG statements together and send to database ser$er in one single trip. 1!$.What is a /ataSource? A ,ata;ource object is the representation of a data source in the )a$a programming language. In basic terms&

A ,ata;ource is a facility for storing data. ,ata;ource can be referenced by )1,I. ,ata ;ource may point to .,+-;& file ;ystem & any ,+-; etc..

1!(.What are the ad'anta1es of /ataSource? The few ad$antages of data source are :

An application does not need to hardcode dri$er information& as it does with the
<riverMana7er. The <ata ource implementations

can easily change the properties of data sources. For e$ample: There is no need to modify the application code when ma!ing changes to the database details. The ,ata;ource facility allows de$elopers to implement a <ata ource class to ta!e ad$antage of features li!e connection pooling and distributed transactions.

1!-.What is connection poolin1? what is the #ain ad'anta1e of usin1 connection poolin1?

A connection pool is a mechanism to reuse connections created. *onnection pooling can increase performance dramatically by reusing connections rather than creating a new physical connection each time a connection is re#uested..

Applet:1$..What is an Applet? Should applets ha'e constructors? - Applets are small programs transferred through Internet& automatically installed and run as part of web-browser. Applets implements functionality of a client. Applet is a dynamic and interacti$e program that runs inside a 9eb page displayed by a )a$a-capable browser. 9e don%t ha$e the concept of *onstructors in Applets. Applets can be in$o!ed either through browser or through Applet$iewer utility pro$ided by ),K. 1$1.What are the AppletEs >ife *"cle #ethods? E)plain the#? - 6ollowing are methods in the life cycle of an Applet:
o

o o

init( method - called when an applet is first loaded. This method is called only once in the entire cycle of an applet. This method usually intiali7e the $ariables to be used in the applet. start( method - called each time an applet is started. paint( method - called when the applet is minimi7ed or refreshed. This method is used for drawing different strings& figures& and images on the applet window. stop( method - called when the browser mo$es off the applet%s page. destroy( method - called when the browser is finished with the applet.

o o

1$2.What is the seDuence for callin1 the #ethods b" AW: for applets? - 9hen an applet begins& the A9T calls the following methods& in this se#uence:
o o o

init( start( paint(

9hen an applet is terminated& the following se#uence of method calls ta!es place :
o o

stop( destroy(

1$3.%ow do Applets differ fro# Applications? - 6ollowing are the main differences: Application: ;tand Alone& doesn%t need web-browser. Applet: 1eeds no e"plicit installation on local machine. *an be transferred through Internet on to the local machine and may run as part of web-browser. Application: E"ecution starts with main( method. ,oesn%t wor! if main is not there. Applet: E"ecution

starts with init( method. Application: -ay or may not be a :II. Applet: -ust run within a :II (Ising A9T . This is essential feature of applets. 1$4.*an we pass para#eters to an applet fro# %:2> pa1e to an applet? %ow? - 9e can pass parameters to an applet using LparamM tag in the following way:
o o

Lparam nameNWparam3X $alueNW$alue3XM Lparam nameNWparamHX $alueNW$alueHXM

Access those parameters inside the applet is done by calling getParameter( method inside the applet. 1ote that getParameter( method returns ;tring $alue corresponding to the parameter name. 1$5.%ow do we read nu#ber infor#ation fro# #" appletEs para#eters9 1i'en that AppletEs 1etPara#eter;< #ethod returns a strin1? - Ise the parseInt( method in the Integer *lass& the 6loat(;tring constructor or parse6loat( method in the *lass 6loat& or the ,ouble(;tring constructor or parse,oulbl( method in the class ,ouble. 1$!.%ow can arran1e for different applets on a web pa1e to co##unicate with each other? - 1ame your applets inside the Applet tag and in$o!e Applet*onte"t%s getApplet( method in your applet code to obtain references to the other applets on the page. 1$$.%ow do select a 7+> fro# #" Applet and send the browser to that pa1e? - As! the applet for its applet conte"t and in$o!e show,ocument( on that conte"t object.
4. ?5% tar7et?5%; F. trin7 ?5% trin7 M. (pplet"ontext context & 7et(pplet"ontext(); E. tr# N. { O. tar7et?5% & ne' ?5%(?5% trin7); G. } I. catch (Malformed?5%6xception e) 3H.{ 33. // "ode for recover from the exception 34.} 3F.context. sho'<ocument (tar7et?5%);

1$(.*an applets on different pa1es co##unicate with each other? - 1o& 1ot ,irectly. The applets will e"change the information at one meeting place either on the local file system or at remote system. 1$-.%ow do deter#ine the width and hei1ht of #" application? - Ise the get;i7e( method& which the Applet class inherits from the *omponent class in the

)a$a.awt pac!age. The get;i7e( method returns the si7e of the applet as a ,imension object& from which you e"tract separate width& height fields. The following code snippet e"plains this:
3M.<imension dim & 7et i!e(); 3E.int applet'idth & dim.'idth(); 3N.int applethei7ht & dim.hei7ht();

1(..Which classes and interfaces does Applet class consist? Y Applet class consists of a single class& the Applet class and three interfaces: Applet*onte"t& Applet;tub& and Audio*lip. 1(1.What is AppletStub nterface? - The applet stub interface pro$ides the means by which an applet and the browser communicate. 0our code will not typically implement this interface. 1(2.What ta1s are #andator" when creatin1 %:2> to displa" an applet?
3. 4. F. M.

name& height& width code& name codebase& height& width code& height& width

*orrect answer is d. 1(3.What are the AppletEs infor#ation #ethods? - The following are the Applet%s information methods: getAppletInfo( method: .eturns a string describing the applet& its author& copyright information& etc. getParameterInfo( method: .eturns an array of string describing the applet%s parameters. 1(4.What are the steps in'ol'ed in Applet de'elop#ent? Y 6ollowing are the steps in$ol$ed in Applet de$elopment:
o o o

*reate8Edit a )a$a source file. This file must contain a class which e"tends Applet class. *ompile your program using ja$ac E"ecute the applet$iewer& specifying the name of your applet%s source file or html file. In case the applet information is stored in html file then Applet can be in$o!ed using ja$a enabled web browser.

1(5.Which #ethod is used to output a strin1 to an applet? Which function is this #ethod included in? Y draw;tring( method is used to output a string to an applet. This method is included in the paint method of the Applet. 1(!.what is the difference between applets loaded o'er the net and applets loaded 'ia the file s"ste#? Ans: There are two different ways that applets are loaded by a )a$a system. The way an applet enters the system affects what it is allowed to do. If an applet is loaded o$er the net& then it is loaded by the applet class loader& and is subject to the restrictions enforced by the applet security manager. If an applet resides on the client%s local dis!& and in a directory that is on the client%s *GA;;PAT/& then it is loaded by the file system loader. The most important differences are : a. applets loaded $ia the file system are allowed to read and write files b. applets loaded $ia the file system are allowed to load libraries on the client c. applets loaded $ia the file system are allowed to e"ec processes d. applets loaded $ia the file system are allowed to e"it the $irtual machine e. applets loaded $ia the file system are not passed through the byte code $erifier 1($.WhatEs the applet class loader9 and what does it pro'ide? Ans: Applets loaded o$er the net are loaded by the applet class loader. 6or e"ample& the applet $iewer%s applet class loader is implemented by the class sun.applet.Applet*lassGoader.The class loader enforces the )a$a name space hierarchy. The class loader guarantees that a uni#ue namespace e"ists for classes that come from the local file system& and that a uni#ue namespace e"ists for each networ! source. 9hen a browser loads an applet o$er the net& that applet%s classes are placed in a pri$ate namespace associated with the applet%s origin. Thus& applets loaded from different networ! sources are partitioned from each other. Also& classes loaded by the class loader are passed through the $erifier. The $erifier chec!s that the class file conforms to the )a$a language specification Y it doesn%t assume that the class file was produced by a ZfriendlyW or ZtrustedW compiler. (n the contrary& it chec!s the class files for purposeful $iolations of the language type rules and name space restrictions. The $erifier ensures that: a. There are no stac! o$erflows or underflows. b. All register accesses and stores are $alid. c. The parameters to all byte code instructions are correct. d. There is no illegal data con$ersion. e. The $erifier accomplishes that by doing a data-flow analysis of the byte code instruction stream& along with chec!ing the class file format& object signatures& and special analysis of finally clauses that are used for )a$a e"ception handling.

1(5.whatEs the applet securit" #ana1er9 and what does it pro'ide? Ans: The applet security manager is the )a$a mechanism for enforcing the applet restrictions described abo$e. The applet $iewer%s applet security manager is implemented by sun.applet.Applet;ecurity.A browser may only ha$e one security manager. The security manager is established at startup& and it cannot thereafter be replaced& o$erloaded& o$erridden& or e"tended.Applets cannot create or reference their own security manager. 1(!. f other lan1ua1es are co#piled to &a'a b"te codes9 how does that affect the applet securit" #odel? Ans: The $erifier is independent of ;un%s reference implementation of the )a$a compiler and the high-le$el specification of the )a$a language. It $erifies byte codes generated by other )a$a compilers. It also $erifies byte codes generated by compiling other languages into the byte code format. +yte codes imported o$er the net that pass the $erifier can be trusted to run on the )a$a $irtual machine. In order to pass the $erifier& byte codes ha$e to conform to the strict typing& the object signatures& the class file format& and the predictability of the runtime stac! that are all defined by the )a$a language implementation.

)a$a I8(:1($.What is the difference between the +eaderGWriter class hierarch" and the nputStrea#GOutputStrea# class hierarch"? The .eader89riter class hierarchy is character-oriented& and the Input;tream8(utput;tream class hierarchy is byte-oriented. 1((.What is the purpose of the ?ile class? The 6ile class is used to create objects that pro$ide access to the files and directories of a local file system. 1-..What an GO filter? An I8( filter is an object that reads from one stream and writes to another& usually altering the data in some way as it is passed from one stream to another. 1-1.What is the difference between the ?ile and +ando#Access?ile classes? The 6ile class encapsulates the files and directories of the local file system. The .andomAccess6ile class pro$ides the methods needed to directly access data contained in any part of a file.

1-2.What is a transient 'ariable? A transient $ariable is a $ariable that may not be seriali7ed. If you don2t want some field to be seriali7ed& you can mar! that field transient or static. 1-3.%ow are Obser'er and Obser'able used? (bjects that subclass the (bser$able class maintain a list of obser$ers. 9hen an (bser$able object is updated it in$o!es the update( method of each of its obser$ers to notify the obser$ers that it has changed state. The (bser$er interface is implemented by objects that obser$e (bser$able objects. 1-4.What is the difference between SerialiCalble and E)ternaliCable interface? 9hen you use ;eriali7able interface& your class is seriali7ed automatically by default. +ut you can o$erride write(bject( and read(bject( two methods to control more comple" object seraili7ation process. 9hen you use E"ternali7able interface& you ha$e a complete control o$er your class2s seriali7ation process. 1-5.What is the purpose of the +unti#e class? The purpose of the .untime class is to pro$ide access to the )a$a runtime system. 1-!.What is the purpose of the S"ste# class? The purpose of the ;ystem class is to pro$ide access to system resources. 1-$.What is the Properties class? The properties class is a subclass of /ashtable that can be read from or written to a stream. It also pro$ides the capability to specify a set of default $alues to be used. 1-(.%ow #an" #ethods in the E)ternaliCable interface? There are two methods in the E"ternali7able interface. 0ou ha$e to implement these two methods in order to ma!e your class e"ternali7able. These two methods are readE"ternal( and writeE"ternal( . 1--.What class allows "ou to read ob5ects directl" fro# a strea#? The (bjectInput;tream class supports the reading of objects from input streams. 2...What interface #ust an ob5ect i#ple#ent before it can be written to a strea# as an ob5ect?

An object must implement the ;eriali7able or E"ternali7able interface before it can be written to a stream as an object. 2.1.What is SerialiCation and deserialiCation? ;eriali7ation is the process of writing the state of an object to a byte stream. ,eseriali7ation is the process of restoring these objects. 2.2..What is the serialiCation? The seriali7ation is a !ind of mechanism that ma!es a class or a bean persistence by ha$ing its properties or fields and state information sa$ed and restored to and from storage. 2.3.%ow to #a6e a class or a bean serialiCable? +y implementing either the ja$a.io.;eriali7able interface& or the ja$a.io.E"ternali7able interface. As long as hierarchy implements ;eriali7able or E"ternali7able& that class is seriali7able. 2.4.%ow #an" #ethods in the SerialiCable interface? There is no method in the ;eriali7able interface. The ;eriali7able interface acts as a mar!er& telling the object seriali7ation tools that your class is seriali7able. 2.5.%ow can custo#iCe the seraliCation process? i.e. how can one ha'e a control o'er the serialiCation process? 0es it is possible to ha$e control o$er seriali7ation process. The class should implement E"ternali7able interface. This interface contains two methods namely readE"ternal and writeE"ternal. 0ou should implement these methods and write the logic for customi7ing the seriali7ation process.

Вам также может понравиться