core java interview questions_topicwise

Upload: amyy23

Post on 03-Jun-2018

227 views

Category:

Documents


1 download

TRANSCRIPT

  • 8/12/2019 Core Java Interview Questions_Topicwise

    1/44

    Oops:-

    1.What are the principle concepts of OOPS?

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

    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 oraccessing the properties or methods of the encapsulated object.

    4.What is the difference between abstraction and encapsulation?

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

    Abstractionsol$es the problem in the design side while Encapsulationis the

    Implementation.

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

  • 8/12/2019 Core Java Interview Questions_Topicwise

    2/44

    Inheritance is done by using the !eyword e"tends.

    The two most common reasons to use inheritance are:

    o To promote code reuse

    o 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 differentconte"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 runtime polymorphism. *ompile time polymorphism is method o$erloading. +unti#e ti#epol"#orphis#is done using inheritance and interface.

    ,ote:From a practical programming viewpoint, polymorphism manifests itself in three distinctforms 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 ano$erridden method is resol$ed at runtime rather than at compile-time. In this process& an

  • 8/12/2019 Core Java Interview Questions_Topicwise

    3/44

    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 0indin?

    +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 withpolymorphism and inheritance.

    11.What is #ethod o'erloadin?

    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'erridin?

    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'erloadin and #ethod o'erridin?

    O'erloaded ethod O'erridden ethod

  • 8/12/2019 Core Java Interview Questions_Topicwise

    4/44

    Aru#ents ust change ust not change

    +eturn t"pe *an change *an%t change e"cept for co$ariant

    returns

    E)ceptions *an change *an reduce or eliminate. ust notthrow new or broader chec!ed

    e"ceptions

    Access *an change ust not ma!e more restricti$e (can be

    less restricti$e

    n'ocation eference type determines which

    o$erloaded $ersion is selected.

    /appens at compile time.

    bject type determines which method

    is selected. /appens at runtime.

    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 themethod 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 subclasssuper.overriddenMethod();

    1$.What is super?

    superis 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 theuse of the super !eyword.

    ,ote:

  • 8/12/2019 Core Java Interview Questions_Topicwise

    5/44

    '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.xxxvaria"les or methods to compute its parameters*

    1(.%ow do "ou pre'ent a #ethod fro# bein 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 itsinheritance hierarchy.

    public final void exampleMethod() { // Method statements

    }nterface

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

  • 8/12/2019 Core Java Interview Questions_Topicwise

    6/44

    23.What #odifiers are allowed for #ethods in an nterface?

    nly publicand abstractmodifiers 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!ableinterface and "loneableare

    typical mar!er interfaces. These do not contain any methods& but classes must implement thisinterface 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 amethod 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 reuire 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 nterfaces

    An abstract class can pro$ide complete& defaultcode and8or just the details that ha$e to be

    o$erridden.

    An interface cannot pro$ide any code at all&justthe signature.

    In case of abstract class& a class may e"tend onlyone abstract class. A *lass may implement se$eral interfaces.

    An abstract class can ha$e non-abstractmethods.

    All methods of an Interface are abstract.

    An abstract class can ha$e instance $ariables. An Interface cannot ha$e instance $ariables.

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

  • 8/12/2019 Core Java Interview Questions_Topicwise

    7/44

    pri$ate& protected.

    If we add a new method to an abstract class then

    we ha$e the option of pro$iding defaultimplementation and therefore all the e"isting

    code might wor! properly.

    If we add a new method to an Interface then we

    ha$e to trac! down all the implementations ofthe interface and define implementation for the

    new method.

    An abstract class can contain constructors . An Interface cannot contain constructors .

    Abstract classes are fast.

    Interfaces are slow as it re#uires e"tra

    indirection to find corresponding method in theactual 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.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    8/44

    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 'oidand 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 notha$e any constructor& compiler will automatically pro$ide

    one no-parameter-constructor (default-constructor for the class in the byte code. The accessmodifier (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 ethods?

    *onstructors ethods

    Purpose *reate an instance of a class roup )a$a statements

    odifiers *annot be a"stract, final, native,static& orsynchroni-ed

    *an be a"stract, final, native, static& orsynchroni-ed

    +eturn :"pe 1o return type& not e$en $oid $oid or a $alid return type

    ,a#e ;ame name as the class (first letter is

    capitali7ed by con$ention -- usually a

    noun

    Any name e"cept the class. ethod

    names begin with a lowercase letter by

    con$ention -- usually the name of anaction

    this efers to another constructor in the

    same class. If used& it must be the first

    line of the constructor

    efers to an instance of the owning

    class. *annot be used by static

    methods.

    super *alls the constructor of the parentclass. If used& must be the first line of

    the constructor

    *alls an o$erridden method in theparent class

    nheritance *onstructors are not inherited ethods are inherited

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

  • 8/12/2019 Core Java Interview Questions_Topicwise

    9/44

    *onstructors use thisto refer to another constructor in the same class with a different

    parameter list.

    *onstructors usesuperto in$o!e the superclass2s constructor. If a constructor usessuper&

    it must use it in the first line< otherwise& the compiler will complain.

    3!.What are the differences between *lass ethods and nstance ethods?

    *lass ethods nstance ethods

    *lass methods are methods which are declared

    as static. The method can be called withoutcreating an instance of the class

    Instance methods on the other hand re#uire aninstance 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.

    *lass methods can only operate on classmembers and not on instance members as class

    methods are unaware of instance members.

    Instance methods of the class can also not becalled from within a class method unless they

    are being called on an instance of that class.

    *lass methods are methods which are declared

    as static. The method can be called without

    creating an instance of the class.

    Instance methods are not declared as static.

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

    *onstructors use thisto refer to another constructor in the same class with a different

    parameter list.

    *onstructors usesuperto 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 Specifiers

    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"licclasses& methods& and fields can be accessed from e$erywhere.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    10/44

    Protected-protectedmethods 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

  • 8/12/2019 Core Java Interview Questions_Topicwise

    11/44

    =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 nonstatic '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 cannotreference to the current o".ect using #eywords super or this*

    *olletion

    >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 throuh a collection usin 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@Bs iterator()

    method.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    12/44

    ;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 durin 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 terator

    Enumeration doesn2t ha$e a remo$e( method Iterator has a remo$e( method

    Enumeration acts as ead-only interface&

    because it has the methods only to tra$erse and

    fetch the objects

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

    F.%ow is >istterator5

    >istteratoris just li!e Iterator& e"cept it allows us to access the collection in either the forwardor bac!ward direction and lets us modify an element

    3.What is the >ist interface5

    The Gist interface pro$ides support for ordered collections of objects.

    Gists may contain duplicate elements.

    H.What are the #ain i#ple#entations of the >ist interface5

    The main implementations of the Gist interface are as follows :

    Arra">ist: esi7able-array implementation of the Gist interface. The best all-aroundimplementation 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. seful for #ueues and double-ended #ueues (de#ues.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    13/44

    J.What are the ad'antaes 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.

    >./ifference between Arra">ist and =ector5

    Arra">ist =ector

    ArrayGist is ,O:synchroni7ed by default. =ector Gist is synchroni7ed by default.

    ArrayGist can use only Iterator to access the

    elements.

    =ector list can use Iterator and Enumeration

    Interface to access the elements.

    The ArrayGist increases its array si7e by F

    percent if it runs out of room.

    A =ector defaults to doubling the si7e of its

    array if it runs out of room

    ArrayGist has no default si7e. 9hile $ector has a default si7e of 3F.

    .%ow to obtain Arra" fro# an Arra">ist5

    Array can be obtained from an ArrayGist using toArray() method on ArrayGist.

    %ist arra#%ist & ne' rra#%ist(); arra#%ist.add(*+

    bject- a & arrayList.toArray();

    4.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. 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 innodes 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 onlyupdating the ne"t pointer in the node before the deleted node and updating the pre$ious

    pointer in the node after the deleted node.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    14/44

    ?.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"ceptthrough the iterator2s own remo$e or add methods& the iterator will throw a

    *oncurrentodificationE"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.

    C.%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 tofre#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.

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

    The main implementations of the Gist interface are as follows:

    /ash;et

    Tree;et

    Gin!ed/ash;et

    Enum;et

    43.What is a %ashSet5

    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.

    se this class when you want a collection with no duplicates and you don%t care about

    order when you iterate through it.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    15/44

    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 :reeSet

    /ash;et is under set interface i.e. it does not

    guarantee for either sorted order or se#uenceorder.

    Tree;et is under set i.e. it pro$ides elements in a

    sorted order (acceding order.

    9e can add any type of elements to hash set.9e can add only similar types

    of elements to tree set.

    4.What is a ap ? 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 ap interface5

    The main implementations of the Gist interface are as follows:

    /ashap

    /ashTable

    Treeap

    Enumap

    4?.What is a :reeap ?

  • 8/12/2019 Core Java Interview Questions_Topicwise

    16/44

    Treeap actually implements the ;ortedap interface which e"tends the ap interface. In a

    Treeap 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. Treeap is based on the ed-+lac!tree data structure.

    4C.%ow do "ou decide when to use %ashap and when to use :reeap ?

    6or inserting& deleting& and locating elements in a ap& the /ashap offers the best alternati$e.If& howe$er& you need to tra$erse the !eys in a sorted order& then Treeap is your better

    alternati$e. ,epending upon the si7e of your collection& it may be faster to add elements to a

    /ashap& then con$ert the map to a Treeap for sorted !ey tra$ersal.

    4D./ifference between %ashap and %ashtable5

    %ashap %ashtable

    /ashap lets you ha$e null $alues as well as

    one null !ey.

    /ashTable does not allows null $alues as !ey

    and $alue.

    The iterator in the /ashap is fail-safe (If you

    change the map while iterating& you%ll !now.

    The enumerator for the /ashtable is not fail-

    safe.

    /ashap is unsynchroni7ed. /ashtable is synchroni7ed.

    ,ote: nly one 1GG is allowed as a !ey in /ashap. /ashap does not allow multiple !eysto be 1GG. 1e$ertheless& it can ha$e multiple 1GG $alues.

    ?F.%ow does a %ashtable internall" #aintain the 6e"'alue pairs?

    Treeap actually implements the ;ortedap interface which e"tends the ap interface. In aTreeap 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. Treeap is based on the ed-+lac!

    tree data structure.

    ?3.What Are the different *ollection

    =iews :hat aps 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.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    17/44

    ?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 allthe !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.

    ?.%ow do "ou sort an Arra">ist ;or an" list< of userdefined obects ?

    *reate an implementation of the.ava*lang*Compara"leinterface 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 theCollections.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.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    18/44

    ??.What are the differences between the *o#parable and *o#parator interfaces 5

    *o#parable *o#parato

    It uses the compareTo%)method.

    int o".ectOne*compareTo%o".ectTwo)*

    t uses the compare%) method.

    int compare%O".One, O".Two)

    It is necessary to modify the class whose

    instance is going to be sorted.

    A separate class can be created in order to sort

    the instances.

    nly one sort se#uence can be created. any sort se#uences can be created.

    It is fre#uently used by the API classes. It used by third-party classes to sort instances.

    E"ception /andling:-$(.What is an e)ception?

    An e$ceptionis an e$ent& which occurs during the e"ecution of a program& that disrupts thenormal 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 utfemoryError&

    which would be reported by the )= itself.

    (.Which is superclass of E)ception?

    :hrowable& the parent class of all e"ception related classes.

    (1.What are the ad'antaes of usin e)ception handlin?

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

  • 8/12/2019 Core Java Interview Questions_Topicwise

    19/44

    *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!ede"ception as a thrown e"ception.

    7nchec6ed e)ceptionsAll 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 errorclasses (Error and its subclasses aree"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$ceptionclasses (5untime6xceptionand its subclasses are e"empted from

    compile-time chec!ing because& in the judgment of the designers of the )a$a programminglanguage& 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$elof 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 sinificance of tr"catch 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 codethat handles it.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    20/44

    (!.What is the use of finall" bloc6?

    The finally bloc! encloses code that is always e"ecuted at some point after the try bloc!& whetheran 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"ecutesimmediately 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 returnstatement 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!.

    ,oteIt is not $alid to use a try clause without either a catch clause or a finally clause.

    (-.What is the difference throw and throws?

    throwssed 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 musteither ha$e a try-catch clause to handle that e"ception or must be declared to throw that

    e"ception (or its superclass itself.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    21/44

  • 8/12/2019 Core Java Interview Questions_Topicwise

    22/44

    J. +y unsuccessfully attempting to ac#uire an object2s loc!

    >. +y in$o!ing an object2s wait( method.

    . It can also enter the waiting state by in$o!ing its (deprecated suspend( method.

    -3.What is the difference between "ieldin and sleepin?

    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 prora#? E)plain different wa"s of usin thread? When a

    thread is created and started9 what is its initial state?

    Or

    E)tendin :hread class or i#ple#entin +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 whenyou 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 allmethods 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 distinguishabledifference. 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 usin &a'athreads?

    utual e"clusion is a phenomenon where no two processes can access critical regions of

    memory at the same time. sing )a$a multithreading we can arri$e at mutual e"clusion. 6ormutual 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 forcommunicating 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 schedulin and ti#e slicin?

    nder 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. nder time slicing& a tas! e"ecutes for apredefined 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?

  • 8/12/2019 Core Java Interview Questions_Topicwise

    23/44

  • 8/12/2019 Core Java Interview Questions_Topicwise

    24/44

    15.Whats the difference between the #ethods sleep;< and wait;

  • 8/12/2019 Core Java Interview Questions_Topicwise

    25/44

    88 method code.

    E.g. synchroni7ing a bloc! of code inside a function:public ethodH (O

    synchroni7ed (this O

    88 synchroni7ed code here.

    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 threadsmay 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 obectBs loc6 and which obects ha'e loc6s?

    Answer: An object2s loc! is a mechanism that is used by multiple threads to obtain synchroni7edaccess 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 processin?

    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 :hreadPoolnt

    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$ethreads that are waiting for acti$ation. nce the threads ha$e finished processing they come bac!

    and wait once again in the pool.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    26/44

    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 theycome 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 Swin 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 usingja$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 tocause paint( to be in$o!ed by the A9T painting thread.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    27/44

    121.Which pac6ae has liht weiht 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 Frid0a>a"out oraniCed?

    Or

    What is a la"out #anaer and what are different t"pes of la"out #anaers a'ailable in a'a

    Swin?

    Or

    %ow are the ele#ents of different la"outs oraniCed?

    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& Eastand 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'antae do &a'aBs la"out #anaers pro'ide o'er traditional windowin

    s"ste#s?

  • 8/12/2019 Core Java Interview Questions_Topicwise

    28/44

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

    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'" weiht 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.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    29/44

    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 iswrapper around a primiti$e data type.

    6ollowing table lists the primiti$e types and the corresponding wrapper classes:

    Pri#iti'e Wrapper

    +oolean ja$a.lang.+oolean

    +yte ja$a.lang.+yte

    *har ja$a.lang.*haracter

    double ja$a.lang.,ouble

    6loat ja$a.lang.6loat Int ja$a.lang.Integer

    Gong ja$a.lang.Gong

    ;hort ja$a.lang.;hort

    =oid 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

  • 8/12/2019 Core Java Interview Questions_Topicwise

    30/44

    ;QG RG support

    13(.E)plain 0asic Steps in writin a &a'a prora# usin &/0*?

    ),+* ma!es the interaction with ,+; simple and intuiti$e. 9hen a )a$a application needsto 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 applicationto&/0* anaerconnection.

    The ),+* ,ri$er API& which supports the &/0* anaerto/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 correctdri$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.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    31/44

    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'eranaer: 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 throughconnection object only.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    32/44

  • 8/12/2019 Core Java Interview Questions_Topicwise

    33/44

    143.What is &/0* /ri'er interface?

    The ),+* ,ri$er interface pro$ides $endor-specific implementations of the abstract classespro$ided by the ),+* API. Each $endor dri$er must pro$ide implementations of thejava.s=l."onnection,tatement,>reparedtatement, "allabletatement, 5esultet

    and

  • 8/12/2019 Core Java Interview Questions_Topicwise

    34/44

  • 8/12/2019 Core Java Interview Questions_Topicwise

    35/44

    :"pe 3 Open Protocol,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 netser$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 anydatabase.

    :"pe 4 Proprietar" Protocol,et;pure &a'a dri'er

  • 8/12/2019 Core Java Interview Questions_Topicwise

    36/44

    TA1;A*TI1;EIAGIUA+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.

    5esultet 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:

    1@>6JF5B56J"5%%J$6$1$L6specifies that a resultset is scrollable in either direction butis insensiti$e to changes committed by other transactions or other statements in the same

    transaction.

    1@>6J"5%%J6$1$L6specifies that a resultset is scrollable in either direction and is

    affected by changes committed by other transactions or statements within the same

    transaction.

    Note: A TYPE_FORAR!_O#Yresultset is always insensitive*

    1!3.Whats the difference between :HPEIS*+O>>I,SE,S:=E and:HPEIS*+O>>ISE,S:=E?

    :HPEIS*+O>>I,SE,S:=E :HPEIS*+O>>ISE,S:=E

    An insensiti$e resultset is li!e the snapshot of

    the data in the database when #uery was

    e"ecuted.

    A sensiti$e resultset does 1T represent a

    snapshot of data& rather it contains points to

    those rows which satisfy the #uery condition.

    After we get the resultset the changes made to

    data are not $isible through the resultset& and

    hence they are !nown as insensiti$e.

    After we obtain the resultset if the data is

    modified then such modifications are $isible

    through resultset.

    Performance not effected with insensiti$e. ;ince a trip is made for e$ery Vetoperation&the performance drastically get affected.

    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-

  • 8/12/2019 Core Java Interview Questions_Topicwise

    37/44

    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 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 maychange 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 +atchpdates 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'antaes 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

  • 8/12/2019 Core Java Interview Questions_Topicwise

    38/44

  • 8/12/2019 Core Java Interview Questions_Topicwise

    39/44

    starts with init( method. Application: ay or may not be a I. Applet: ust run within a

    I (sing A9T. This is essential feature of applets.

    1$4.*an we pass para#eters to an applet fro# %:> pae to an applet? %ow?- 9ecan pass parameters to an applet using LparamM tag in the following way:

    o Lparam nameNWparam3X $alueNW$alue3XM

    o Lparam nameNWparamHX $alueNW$alueHXM

    Access those parameters inside the applet is done by calling getParameter( methodinside 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# #" applets para#eters9 i'en that

    Applets etPara#eter;< #ethod returns a strin?

    - se 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 arrane for different applets on a web pae 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 theother applets on the page.

    1$$.%ow do select a 7+> fro# #" Applet and send the browser to that pae? - As! the

    applet for its applet conte"t and in$o!e show,ocument( on that conte"t object.

    4. ?5% tar7et?5%;. trin7 ?5%trin7. pplet"ontext context & 7etpplet"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 exception34.}3.context. sho'

  • 8/12/2019 Core Java Interview Questions_Topicwise

    40/44

  • 8/12/2019 Core Java Interview Questions_Topicwise

    41/44

    1(5.Which #ethod is used to output a strin 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 thepaint 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 isloaded 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 filesb. 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 processesd. 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($.Whats the applet class loader9 and what does it pro'ide?

    Ans: Applets loaded o$er the net are loaded by the applet class loader. 6ore"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 filesystem& and that a uni#ue namespace e"ists for each networ! source. 9hen a browser loads anapplet 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!sthat 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 offinally clauses that are used for )a$a e"ception handling.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    42/44

    1(5.whats the applet securit" #anaer9 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 bysun.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& ore"tended.Applets cannot create or reference their own security manager.

    1(!.f other lanuaes 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 thehigh-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 alldefined 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;tream8utput;tream classhierarchy 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 thedata in some way as it is passed from one stream to another.

    1-1.What is the difference between the ile and +ando#Accessile classes?

    The 6ile class encapsulates the files and directories of the local file system. TheandomAccess6ile class pro$ides the methods needed to directly access data contained in any

    part of a file.

  • 8/12/2019 Core Java Interview Questions_Topicwise

    43/44

    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 writebject( and readbject( two methods to control more comple" object

    seraili7ation process. 9hen you use E"ternali7able interface& you ha$e a complete control o$eryour 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. Italso 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( andwriteE"ternal(.

    1--.What class allows "ou to read obects directl" fro# a strea#?

    The bjectInput;tream class supports the reading of objects from input streams.

    2.What interface #ust an obect i#ple#ent before it can be written to a strea# as an

    obect?

  • 8/12/2019 Core Java Interview Questions_Topicwise

    44/44

    An object must implement the ;eriali7able or E"ternali7able interface before it can be written to

    a stream as an object.

    21.What is SerialiCation and deserialiCation?

    ;eriali7ation is the process of writing the state of an object to a byte stream. ,eseriali7ation is theprocess of restoring these objects.

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

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

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

    25.%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 andwriteE"ternal. 0ou should implement these methods and write the logic for customi7ing the

    seriali7ation process.