Core Java Interview Questions.doc

download Core Java Interview Questions.doc

of 25

Transcript of Core Java Interview Questions.doc

  • 8/14/2019 Core Java Interview Questions.doc

    1/25

    Core Java Interview Questions

    1. Why threads block or enters to waiting state on I/O?Threads enters to waiting state or block on I/O because other threads can execute while the I/O operations areperformed.

    2. What is List interface?List is an ordered collection of objects.

    3. What is the difference between yield() and slee()?When a object invokes yield() it returns to ready state. But when an object invokes sleep() method enters to notready state.

    !. What are Wraer Classes ?They are wrappers to primitive data types. They allow us to access primitives as objects.

    ". Can we call finali#e() $ethod ?Yes. obody will stop us to call any method ! if it is accessible in our class. But a "arba"e collector cannot call anobject#s finali$e method if that object is reachable.

    %&. What is the difference between ti$e slicin' and ree$tive schedulin' ?%n preemptive schedulin"! hi"hest priority task continues e&ecution till it enters a not runnin" state or a hi"her

    priority task comes into e&istence. %n ime slicin"! the task continues its e&ecution for a predefined period of timeand reenters the pool of ready tasks.

    %%. What is the initial state of a thread when it is created and started?The thread is in ready state.

    %2. Can we declare an anony$ous class as both etendin' a class and i$le$entin' an interface?o. 'n anonymous class can e&tend a class or implement an interface! but it cannot be declared to do both

    %3. What are the differences between boolean oerator and oerator?

    When an e&pression containin" the operator is evaluated both operands are evaluated 'nd the operator isli d h d Wh i i i i l d h fi d i l d %f

  • 8/14/2019 Core Java Interview Questions.doc

    2/25

    When an e&pression containin" the operator is evaluated both operands are evaluated 'nd the operator isli d t th d Wh i t i i t i l t d th fi t d i l t d %f

    1acka"es are a way to or"ani$e files in java when a project consists of more than one module. %t helps in resolvin"name conflicts when different modules have classes with the same names.2*. What $ust be the order of catch bloc+s when catchin' $ore than one ecetion?The sub classes must come first. 9therwise it will "ive a compile time error.2,. 0ow can we call a $ethod or variable of the suer class fro$ child class ?We can use super.method() or super.variable synta& for this purpose.2-. If you are overridin' euals() $ethod of a class4 what other $ethods you $i'ht need to override ?

    hash,ode2/. 0ow can you create your own ecetion?9ur class must e&tend either :&ception or its sub class2!. What is seriali#ation?*eriali$ation is the process of savin" the state of an object.2". What is de5seriali#ation?

    2e4seriali$ation is the process of restorin" the state of an object.3&. What is eternali#able?%t is an interface that e&tends *eriali$able. %t is havin" two different methods write:&ternal() and read:&ternal. Thisinterface allows us to customi$e the output.3%. 6oes 'arba'e collection 'uarantee that a ro'ra$ will not run out of $e$ory?+arba"e collection does not "uarantee that a pro"ram will not run out of memory. %t is also possible for pro"rams tocreate objects that are not subject to "arba"e collection. 'nd there is no "uarantee that +arba"e ,ollection threadwill be e&ecuted.32. What is a native $ethod?native method is a method that is implemented in a lan"ua"e other than ava.

    ;;. What are different type of e&ceptions in avauntime:&ception is calledunchecked e&ception. We don#t need to e&plicitly catch a unchecked e&ception.ore& ,urrency Tradin" 3elpful links on ore& currency tradin". Tired 9f 0y*pace< 0eet cool people at Ta"World?

    'cne 3elpful links on on several acne treatments. 0ake 0oney 9nline 3elpful links to pro"rams to makin" moneyfrom home.3*. Can we catch an error in our 1ava ro'ra$ ?

    Yes We can We can catch anythin" that is derived from Throwable *ince :rror is a sub class of Throwable we

  • 8/14/2019 Core Java Interview Questions.doc

    3/25

    java.lan".9bject.*-. What is the difference between readers and strea$s?>eaders are character oriented where streams are byte oriented. The readers are havin" full support for =nicodedata.*/. What is constructor chainin'?When a constructor of a class is e&ecuted it will automatically call the default constructor of the super class (if noe&plicit call to any of the super class constructor) till the root of the hierarchy.*!. What are the different ri$itive data tyes in 1ava?There are C primitive types in java. boolean ! char! byte! short! int lon"! float! double.*". What is static?static means one per class. static variables are created when the class loads. They are associated with the class.%n order to access a static we don#t need objects. We can directly access static methods and variable by callin"classname.variablename.,&. Why we cannot override static $ethods?*tatic means they are associated with a class. %n static methods! the bindin" mechanism is static bindin". *o itmust be available at the compile time.,%. What is the difference between static and non static variables?

    ' static variable is associated with the class as a whole rather than with specific instances of a class. There will beonly one value for static variable for all instances of that class. on4static variables take on uni-ue values witheach object instance.,2. When does a co$iler sulies a default constructor for a class?%f there is no other constructor e&ist in a class! the compiler will supply a default constructor.,3. What are the restrictions laced on overridin' a $ethod ?

    The overridden method have the e&act si"nature of the super class method! includin" the return type. The accessspecified cannot be less restrictive than the super class method. We cannot throw any new e&ceptions inoverridden method.,*. What are the restrictions laced on overloadin' a $ethod?

    9verloadin" methods must differ in their parameter list! or number of parameters.,,. What is castin'?,astin" means convertin" one type to another. There are mainly two types of castin". ,astin" between primitivetypes and castin" between object references.,astin" between primitive numeric types is used to convert lar"er data types to smaller data types. ,astin"between object references is used to refer to an object by a compatible class! interface! or array type reference.

    ,- What is the difference between 99 and euals?

  • 8/14/2019 Core Java Interview Questions.doc

    4/25

    %f statement is used to select from two alternatives. %t uses a boolean e&pression to decide which alternative shouldbe e&ecuted. The e&pression in if must be a boolean value. The switch statement is used to select from multiplealternatives. The case values must be promoted to an to int value.--. What is hashCode?The hashcode of a ava 9bject is simply a number (;F4bit si"ned int) that allows an object to be mana"ed by ahash4based data structure. ' hashcode shouldbe! e-ual for e-ual object (this is mandatory?) ! fast to compute based on all or most of the internal state of anobject! use all or most of the space of;F4bit inte"ers in a fairly uniform way ! and likely to be different even for objects that are very similar. %f you areoverridin" hash,ode you need to override e-uals method also.-/. What is an I

  • 8/14/2019 Core Java Interview Questions.doc

    5/25

    '> stands for ava 'rchive. This is a file format that enables you to bundle multiple files into a sin"le archive file.' jar file will contains a manifest.mf file inside 0:T'4% folder that describes the version and other features of jarfile.!,. Why Java is not fully ob1ective oriented ?2ue to the use of primitives in java! which are not objects.!-. What is a $ar+er interface ?

    'n interface that contains no methods. :"I *eriali$able! ,loneable! *in"leThread0odel etc. %t is used to just markjava classes that support certain capability.!/. What are ta' interfaces?Ta" interface is an alternate name for marker interface.!!. What are the restrictions laced on static $ethod ?We cannot override static methods. We cannot access any object variables inside static method. 'lso the thisreference also not available in static methods.!". What is J@?/0 stands for ava /irtual 0achine. %t is the run time for java pro"rams. 'll are java pro"rams are runnin" insidethis /0 only. %t converts java byte code to 9* specific commands. %n addition to "overnin" the e&ecution of anapplication#s byte codes! the virtual machine handles related tasks such as mana"in" the system#s memory!providin" security a"ainst malicious code! and mana"in" multiple threads of pro"ram e&ecution."&. What is JIA?%T stands for ust %n Time compiler. %t compiles java byte code to native code.7@. What is java byte codeunnable interface! because it "ive loose couplin".%2&. What is coulin'?

    ' ,ouplin" is the dependency between different components of a system

    %3- Why Java is not %&&G ure ob1ect oriented lan'ua'e?

  • 8/14/2019 Core Java Interview Questions.doc

    7/25

    %*/. What is a classloader?' class loader is an object that is responsible for loadin" classes.%*!. What is the difference between Co$arable and Co$arator ?

    ' The ,omparable is for natural orderin" and ,omparator is for custom orderin". But we can override thecompareTo method of comparable interface to "ive a custom orderin".%*". What is the difference between List4 et and @a?' ' *et is a collection that has no duplicate elements. ' List is a collection that has an order associated with itselements. ' map is a way of storin" keyEvalue pairs. The way of storin" a 0ap is similar to two4column table.%,&. What is the difference between Bcetion and Brror?:rror is unrecoverable.%,%. What is $eant by =en ource?%n "eneral! open source refers to any pro"ram whose source code is made available for use or modification asusers or other developers see fit. 9pen source software is usually developed as a public collaboration and made

    freely available.%,2. 0ow do you send data fro$ an alet to ervlet ? What are the stes involved in it?You can use the java.net.=>L,onnection and java.net.=>L classes to open a standard 3TT1 connection to theweb server. The server then passes this information to the servlet in the normal way. Basically! the applet pretendsto be a web browser! and the servlet doesn#t know the difference. 's far as the servlet is concerned! the applet is

    just another 3TT1 client.The 1acka"e Youn" man mails himself in a bo& to his "irlfriend... naked. 2ru" >ehab 3elpful links on dru"addictions! treatment and rehab. ore& 3elpful links on ore& currency tradin". Tired 9f 0y*pace< 0eet coolpeople at Ta"World?%,3. What is oly$orhis$?

    %t is the ability of an object to behave differently on different situations for the same messa"e.%,*. What is a class4 $e$ber and local variable?/ariables declared within a method are local variables. /ariables declared within the class are member variables./ariables declared within the class with static modifier are class variables%,,. 0ow do I convert a nu$eric ID address li+e --.2".3-.%3& into a hostna$e li+e www.1avacertificate.net*trin" hostname D %net'ddress."etByame(JKK.F7.;K.@;AJ)."et3ostame()%,-. What is the difference between a constructor and a $ethod?

    ' constructor is a member function of a class that is used to create objects of that class. %t has the same name asthe class itself! has no return type! and is invoked usin" the new operator. We cannot invoke a constructor directly.

    ' method is an ordinary member function of a class. %t has its own name! a return type (which may be void)! and is

    i k d i th d t t

  • 8/14/2019 Core Java Interview Questions.doc

    8/25

    The /0 is "uaranteed to treat reads and writes of data of ;F bits or less as atomic. or lon" or double variable!pro"rammers should take care in multi4threadin" environment. :ither put these variables in a synchroni$ed methodor block! or declare them volatile.%-". What factors are used to decide usin' synchroni#ed or volatile?You can make a variable synchroni$ed or volatile under the followin" casesI @) if you are not updatin" manyvariables often in a multithread environment!consider usin" volatile. F) %f you are updatin" many variables! consider usin" synchroni$ed! because usin" volatilemi"ht be slower.%/&. What are the drawbac+s of inheritance?*ince inheritance inherits everythin" from the super class and interface! it may make the subclass too clusterin"and sometimes error4prone when dynamicoverridin" or dynamic overloadin" in some situation. %n addition! the inheritance may make peers hardlyunderstand your code if they don#t know how your super4class acts.

    %/%. What is the difference between static synchroni#ed and synchroni#ed $ethods?Both are synchroni$ed methods. 9ne is instance method! the other is class method. 0ethod with static modifier isa class method. That means the method belon"s to class itself and can be accessed directly with class name andis also called *in"leton desi"n. The method without static modifier is an instance method. That means the instancemethod belon"s to its object. :very instance of the class "ets its own copy of its instance method.%/2. What is the urose of the :unti$e class?The purpose of the >untime class is to provide access to the ava runtime system.%/3. What is the urose of the yste$ class?The purpose of the *ystem class is to provide access to system resources.%/*. 6oes the code in finally bloc+ 'et eecuted if there is an ecetion and a return state$ent in a catch

    bloc+?%f an e&ception occurs and there is a return statement in catch block! the finally block is still e&ecuted. The finallyblock will not be e&ecuted when the *ystem.e&it(@) statement is e&ecuted earlier or the system shut down earlier orthe memory is used up earlier before the thread "oes to finally block.%/,. Considerin' notead

  • 8/14/2019 Core Java Interview Questions.doc

    9/25

    %!/. What is a olicy?.%t#s an abstract class for representin" the system security policy for a ava application environment (specifyin"which permissions are available for code from various sources). ava security properties file resides in N'/'4

    390:OElibEsecurityEjava.security directory.%!!. What is a thread 'rou?

    ' thread "roup is a data structure that controls the state of collection of thread as a whole mana"ed by theparticular runtime environment.%!". Why is A>6ata>or$atBcetion thrown by 6ata=ututtrea$.writeA>() when seriali#in' a trin'?2ata9utput*tream.write=T() does not support writin" out strin"s lar"er than K68. The first two bytes of a =Tstrin" in the stream are the len"th of the strin". %f a java.lan".*trin" is lar"er than K68! it needs to be stored in thestream by an alternative method rather than dependin" on the default method of storin" a *trin" in the stream!write=T.%"&. Why is =ut=f@e$oryBrror thrown after writin' a lar'e nu$ber of ob1ects into an

    =b1ect=ututtrea$?The 9bject9utput*tream maintains a table mappin" objects written into the stream to a handle. The first time anobject is written to a stream! its contents are written into the stream subse-uent writes of the object result in ahandle to the object bein" written into the stream. This table maintains references to objects that mi"ht otherwisebe unreachable by an application! thus! resultin" in an une&pected situation of runnin" out of memory. ' call to the9bject9utput*tream.reset() method resets the objectEhandle table to its initial state! allowin" all previously writtenobjects to be eli"ible for "arba"e collection.%"%. 0ow can I 'et the serialersionI6 of a class?By runnin" the serialver tool with the name of the class as the command line ar"umet! as shown in the e&amplethat followsI serialver java.lan".*trin"

    %"2. What is serialersionI6 ?' The serial/ersion=%2 is a universal version identifier for a *eriali$able class. 2eseriali$ation uses this identifiernumber to ensure that a loaded class corresponds to a seriali$ed object.%"3. What is abstraction?'n abstraction is an idea! concept! or word which defines the phenomena which make up the concrete events orthin"s which the abstraction refers to! the referents.%"*. What is encasulation?' :ncapsulation describes the ability of an object to hide its data and methods from the rest of the world%",. What is inheritance?%nheritance is the ability to create new classes based on e&istin" classes. %t is useful to reuse e&istin" code.

    %", 0ow could Java classes direct ro'ra$ $essa'es to the syste$ console but error $essa'es say to

  • 8/14/2019 Core Java Interview Questions.doc

    10/25

    '. ,onstructors must have the same name as the class and can not return a value. They are only called once whilere"ular methods could be called many times.2&3. Can you call one constructor fro$ another if a class has $ultile constructors

    '. Yes. =se this() synta&.2&*. Blain the usa'e of Java ac+a'es.

    '. This is a way to or"ani$e files when a project consists of multiple modules. %t also helps resolve namin" conflictswhen different packa"es have classes with the same names. 1acka"es access level also allows you to protectdata from bein" used by the non4authori$ed classes.2&,. If a class is located in a ac+a'e4 what do you need to chan'e in the = environ$ent to be able to useit?

    '. You need to add a directory or a jar file that contains the packa"e directories to the ,L'**1'T3 environmentvariable. Let#s say a class :mployee belon"s to a packa"e com.&y$.hr and is located in the filecIPdevPcomP&y$PhrP:mployee.java. %n this case! you#d need to add cIPdev to the variable ,L'**1'T3. %f this class

    contains the method main()! you could test it from a command prompt window as followsI

    cIPOjava com.&y$.hr.:mployee

    2&-. Whats the difference between J26 %., and J26 ,.&?'.There#s no difference! *un 0icrosystems just re4branded this version.2&-. What would you use to co$are two trin' variables 5 the oerator 99 or the $ethod euals()?

    '. %#d use the method e-uals() to compare the values of the *trin"s and the DD to check if two variables point at thesame instance of a *trin" object.2&/. 6oes it $atter in what order catch state$ents for >ileHot>oundBcetion and I=Bcetion are

    written?'. Yes! it does. The ileoound:&ception is inherited from the %9:&ception. :&ception#s subclasses have to becau"ht first.2&/. Can an inner class declared inside of a $ethod access local variables of this $ethod?%t#s possible if these variables are final.2&!. What can 'o wron' if you relace with in the followin' code*trin" aDnull if (a?Dnull a.len"th()O@A) Q...R

    ' sin"le ampersand here would lead to a ull1ointer:&ception.2%&. When should the $ethod invo+eLater()be used?

    ' Thi th d i d t th t * i t d t d th h th t di t hi th d

  • 8/14/2019 Core Java Interview Questions.doc

    11/25

    222. What is the diffrence between an Abstract class and Interface? Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain

    no implementation code. A class can implement any number of interfaces, but subclass at most one abstract class. An abstract class can have nonabstract methods. All methods of an interface are abstract.

    An abstract class can have instance variables. An interface cannot.

    An abstract class can define constructor. An interface cannot.

    An abstract class can have any visibility public, protected, private or none !package". An interface#s

    visibility must be public or none !package". An abstract class inherits from Ob$ect and includes methods such as clone!" and e%uals!".

    223. What is a user defined exception?

    &ser'defined exceptions may be implemented by defining a class to respond to the exception and embedding a throw statement in the try block where the exception can occur or declaring that the method

    throws the exception !to another method where it is handled".The developer can define a new exception by deriving it from the (xception class as followspublic class )y(xception extends (xception *

    /+ class definition of constructors !but OT the exception handling code" goes here +/public )y(xception!" *

    super!"-

    public )y(xception! tring error)essage " *super! error)essage "-

    The throw statement is used to signal the occurance of the exception within a try block. Often, exceptions areinstantiated in the same statement in which they are thrown using the syntax.

    throw new )y(xception!0I threw my own exception.0"

  • 8/14/2019 Core Java Interview Questions.doc

    12/25

    serali9able ob$ect must implement the erili9able interface. 5e use Ob$ectOutputtream to write this ob$ect to astream and Ob$ectInputtream to read it from the stream.

    '. Why there are soe null interface in (a)a ? What does it ean ? *i)e e soe null interfaces in!A"A?ull interfaces act as markers..they $ust tell the compiler that the ob$ects of this class need to be treateddifferently..some marker interfaces are eriali9able, :emote, ;loneableWhat are checked and unchecked exceptions?;hecked exceptions are the ones which you expect beforehand to be raised when an exceptional condition occursand so write your code in a try'catch block to handle that sufficiently. 3or example Insuffucient

  • 8/14/2019 Core Java Interview Questions.doc

    13/25

    1'. Is Iterator a 0lass or Interface? What is its use?Iterator is an interface which is used to step through the elements of a ;ollection.

    1+. What is siilarities/difference between an Abstract class and Interface?7ifferences are as follows

    Interfaces provide a form of multiple inheritance. A class can extend only one other class.

    Interfaces are limited to public methods and constants with no implementation. Abstract classes can have

    a partial implementation, protected parts, static methods, etc. A ;lass may implement several interfaces.

  • 8/14/2019 Core Java Interview Questions.doc

    14/25

    #. Which (a)a.util classes and interfaces support e)ent handling?The (ventOb$ect class and the (ventCistener interface support event processing.#1. Is si&eof a keyword?

    The si9eof operator is not a keyword.#2. What are wrapped classes?5rapped classes are classes that allow primitive types to be accessed as ob$ects.#. 8oes garbage collection guarantee that a progra will not run out of eory?Karbage collection does not guarantee that a program will not run out of memory. It is possible for programs touse up memory resources faster than they are garbage collected. It is also possible for programs to createob$ects that are not sub$ect to garbage collection##. What restrictions are placed on the location of a package stateent within a source code file?A package statement must appear as the first line in a source code file !excluding blank lines and comments".#%. 0an an ob(ect4s finali&e56 ethod be in)oked while it is reachable?An ob$ect#s finali9e!" method cannot be invoked by the garbage collector while the ob$ect is still reachable.?owever, an ob$ect#s finali9e!" method may be invoked by other ob$ects.#+. What is the difference between preepti)e scheduling and tie slicing?&nder preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or ahigher priority task comes into existence. &nder time slicing, a task executes for a predefined slice of time andthen reenters the pool of ready tasks. The scheduler then determines which task should execute next, based onpriority and other actors.#-. What )alue does readine56 return when it has reached the end of a file?The readCine!" method returns null when it has reached the end of a file.%. What is the iediate superclass of the 8ialog class? Ans 5indow%1. What is clipping?

    Ans ;lipping is the process of confining paint operations to a limited area or shape.%2. What is a nati)e ethod?A native method is a method that is implemented in a language other than 2ava.%. 0an a for stateent loop indefinitely?4es, a for statement can loop indefinitely. 3or example, consider the following for!--" -%#. What are order of precedence and associati)ity7 and how are they used?Order of precedence determines the order in which operators are evaluated in expressions. Associatitydetermines whether an expression is evaluated left'to'right or right'to'left%%. When a thread blocks on I/O7 what state does it enter?A thread enters the waiting state when it blocks on I/O.%'. o what )alue is a )ariable of the >tring type autoatically initiali&ed?

    Th d f lt l f t i t i ll

  • 8/14/2019 Core Java Interview Questions.doc

    15/25

    is then applied to the first and second operands. If the first operand evaluates to false, the evaluation of thesecond operand is skipped.+2. What is the *regorian0alendar class?

    The Kregorian;alendar provides support for traditional 5estern calendars.+#. What is the purpose of the Duntie class?The purpose of the :untime class is to provide access to the 2ava runtime system.+%. ;ow any ties ay an ob(ect4s finali&e56 ethod be in)oked by the garbage collector?An ob$ect#s finali9e!" method may only be invoked once by the garbage collector.+'. What is the purpose of the finally clause of a try@catch@finally stateent?The finally clause is used to provide the capability to execute code no matter whether or not an exception isthrown or caught.++. What is the arguent type of a progra4s ain56 ethod?A program#s main!" method takes an argument of the tringP type.+,. Which !a)a operator is right associati)e? The Q operator is right associative.

    +-. What is the ocale class?The Cocale class is used to tailor program output to the conventions of a particular geographic, political, orcultural region.,. 0an a double )alue be cast to a byte?4es, a double value can be cast to a byte.,1. What is the difference between a break stateent and a continue stateent?A break statement results in the termination of the statement to which it applies !switch,for, do, or while". Acontinue statement is used to end the current loop iteration and return control to the loop statement.,2. What ust a class do to ipleent an interface?It must provide all of the methods in the interface and identify the interface in its implements clause.

    ,. What ethod is in)oked to cause an ob(ect to begin executing as a separate thread?The start!" method of the Thread class is invoked to cause an ob$ect to begin executing as a separate thread.,#. $ae two subclasses of the ext0oponent class.Text3ield and TextArea

    ,%. What is the ad)antage of the e)ent@delegation odel o)er the earlier e)ent inheritance odel?The event'delegation model has two advantages over the event'inheritance model. 3irst, it enables eventhandling to be handled by ob$ects other than the ones that generate the events !or their containers". This allowsa clean separation between a component#s design and its use. The other advantage of the event'delegationmodel is that it performs much better in applications where many events are generated. This performanceimprovement is due to the fact that the event'delegation model does not have to repeatedly process unhandled

    t i th f th t i h it d l

  • 8/14/2019 Core Java Interview Questions.doc

    16/25

    container.11. What is the E operator?It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by

    the second operand.12. When can an ob(ect reference be cast to an interface reference?An ob$ect reference be cast to an interface reference when the ob$ect implements the referenced interface.1. What is the difference between a Window and a :rae?The 3rame class extends 5indow to define a main application window that can have a menu bar.1#. Which class is extended by all other classes?The Ob$ect class is extended by all other classes.1%. 0an an ob(ect be garbage collected while it is still reachable?A reachable ob$ect cannot be garbage collected. Only unreachable ob$ects may be garbage collected..1'. Is the ternary operator written x F y ? & or x ? y F & ?It is written x > y 9.

    1+. What is the difference between the :ont and :ontetrics classes?The 3ont)etrics class is used to define implementation'specific properties, such as ascent and descent, of a 3ontob$ect.1,. ;ow is rounding perfored under integer di)ision?The fractional part of the result is truncated. This is known as rounding toward 9ero.1-. What happens when a thread cannot ac3uire a lock on an ob(ect?If a thread attempts to execute a synchroni9ed method or synchroni9ed statement and is unable to ac%uire anob$ect#s lock, it enters the waiting state until the lock becomes available.11. What is the difference between the Deader/Writer class hierarchy and theInput>trea/Output>trea classhierarchy?

    The :eader/5riter class hierarchy is character'oriented, and the Inputtream/Outputtream class hierarchy isbyte'oriented.111. What classes of exceptions ay be caught by a catch clause?A catch clause can catch any exception that may be assigned to the Throwable type. This includes the (rror and(xception types.112. If a class is declared without any access odifiers7 where ay the class be accessed?A class that is declared without any access modifiers is said to have package access. This means that the classcan only be accessed by other classes and interfaces that are defined within the same package.11. What is the >ipleieGone class?The impleTime=one class provides support for a Kregorian calendar.11#. What is the ap interface?

    Th ) i t f l th 27@ 7i ti l d i d i t k ith l

  • 8/14/2019 Core Java Interview Questions.doc

    17/25

    The $ava.util.(ventOb$ect class is the highest'level class in the event'delegation class hierarchy.12,. What e)ent results fro the clicking of a button?The Action(vent event is generated as the result of the clicking of a button.

    12-. ;ow can a *=I coponent handle its own e)ents?A component can handle its own events by implementing the re%uired event'listener interface and adding itselfas its own event listener.1. What is the difference between a while stateent and a do stateent?A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A dostatement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statementwill always execute the body of a loop at least once.11. ;ow are the eleents of a *ridBagayout organi&ed?The elements of a Krid

  • 8/14/2019 Core Java Interview Questions.doc

    18/25

    1#-. What is casting?There are two types of casting, casting between primitive numeric types and casting between ob$ect references.;asting between numeric types is used to convert larger values, such as double values, to smaller values, such

    as byte values. ;asting between ob$ect references is used to refer to an ob$ect by a compatible class, interface,or array type reference.

    1%. What is the return type of a progra4s ain56 ethod?A program#s main!" method has a void return type.

    1%1. $ae four 0ontainer classes. Ans 5indow, 3rame, 7ialog, 3ile7ialog, 6anel, Applet, orcroll6ane

    1%2. What is the difference between a 0hoice and a ist?A ;hoice is displayed in a compact form that re%uires you to pull it down to see the list of available choices. Only

    one item may be selected from a ;hoice. A Cist may be displayed in such a way that several Cist items arevisible. A Cist supports the selection of one or more Cist items.

    1%. What class of exceptions are generated by the !a)a run@tie syste?The 2ava runtime system generates :untime(xception and (rror exceptions.

    1%#. What class allows you to read ob(ects directly fro a strea?The Ob$ectInputtream class supports the reading of ob$ects from input streams.

    1%%. What is the difference between a field )ariable and a local )ariable?

    A field variable is a variable that is declared as a member of a class. A local variable is a variable that is declaredlocal to a method.

    1%'. =nder what conditions is an ob(ect4s finali&e56 ethod in)oked by the garbage collector?The garbage collector invokes an ob$ect#s finali9e!" method when it detects that the ob$ect has becomeunreachable.

    1%+. ;ow are this56 and super56 used with constructors?this!" is used to invoke a constructor of the same class. super!" is used to invoke a superclass constructor.

    1%,. What is the relationship between a ethod4s throws clause and the exceptions that can be

    h d i h h d4 i ?

  • 8/14/2019 Core Java Interview Questions.doc

    19/25

    1''. If an ob(ect is garbage collected7 can it becoe reachable again?Once an ob$ect is garbage collected, it ceases to exist. It can no longer become reachable again.

    1'+. What is the >et interface?The et interface provides methods for accessing the elements of a finite mathematical set. ets do not allowduplicate elements.

    1',. What classes of exceptions ay be thrown by a throw stateent?A throw statement may throw any expression that may be assigned to the Throwable type.

    1',. What are J and I?( is the base of the natural logarithm and 6I is mathematical value pi.

    1+. Are true and false keywords? Ans The values true and false are not keywords.

    1+1. What is a )oid return type?A void return type indicates that a method does not return a value.

    1+2. What is the purpose of the enableJ)ents56 ethod?The enable(vents!" method is used to enable an event for a particular ob$ect. ormally,an event is enabled when a listener is added to an ob$ect for a particular event. The enable(vents!" method isused by ob$ects that handle events by overriding their eventdispatch methods.

    1+. What is the difference between the :ile and DandoAccess:ile classes?

    The 3ile class encapsulates the files and directories of the local file system. The :andomAccess3ile class providesthe methods needed to directly access data contained in any part of a file.

    1+#. What happens when you add a double )alue to a >tring?The result is a tring ob$ect.

    1+%. What is your platfor4s default character encoding?If you are running 2ava on (nglish 5indows platforms, it is probably ;pBMB. If you are running 2ava on (nglisholaris platforms, it is most likely JJMES..

    1+'. Which package is always iported by default?

    h $ l k i l i d b d f l

  • 8/14/2019 Core Java Interview Questions.doc

    20/25

    1,'. Which arithetic operations can result in the throwing of an AritheticJxception?Integer / and U can result in the throwing of an Arithmetic(xception.

    1,+. What are three ways in which a thread can enter the waiting state?A thread can enter the waiting state by invoking its sleep!" method, by blocking on I/O, by unsuccessfullyattempting to ac%uire an ob$ect#s lock, or by invoking an ob$ect#s wait!" method. It can also enter the waitingstate by invoking its !deprecated" suspend!" method.

    1,,. 0an an abstract class be final? An abstract class may not be declared as final.

    1,-. What is the DesourceBundle class?The :esource

  • 8/14/2019 Core Java Interview Questions.doc

    21/25

    interface.

    2#. What ethods are used to get and set the text label displayed by a Button ob(ect?

    Ans getCabel!" and setCabel!"

    2%. Which 0oponent subclass is used for drawing and painting? Ans ;anvas

    2'. What are synchroni&ed ethods and synchroni&ed stateents?ynchroni9ed methods are methods that are used to control access to an ob$ect. A thread only executes asynchroni9ed method after it has ac%uired the lock for the method#s ob$ect or class. ynchroni9ed statements aresimilar to synchroni9ed methods. A synchroni9ed statement can only be executed after a thread has ac%uired thelock for the ob$ect or class referenced in the synchroni9ed statement.

    2+. What are the two basic ways in which classes that can be run as threads ay be defined?

    A thread class may be declared as a subclass of Thread, or it may implement the :unnable interface.

    2,. What are the probles faced by !a)a prograers who don4t use layout anagers?5ithout layout managers, 2ava programmers are faced with determining how their K&I will be displayed acrossmultiple windowing systems and finding a common si9ing and positioning that will work within the constraintsimposed by each windowing system.

    2-. What is the difference between an if stateent and a switch stateent?The if statement is used to select among two alternatives. It uses a boolean expression to decide whichalternative should be executed. The switch statement is used to select among multiple alternatives. It uses an intexpression to determine which alternative should be executed.

    21. What happens when you add a double )alue to a >tring?The result is a tring ob$ect.

    211. What is the ist interface?The Cist interface provides support for ordered collections of ob$ects.212. What do you know about the garbage collector?Karbage collector is a runtime component of 2ava which sits on top of the heap memory area from which 2avaob$ects are created and periodically scans it for ob$ects which are eligible to be reclaimed when there are noreferences to these ob$ects in the program. There is simply no way to force garbage collection, but you can

  • 8/14/2019 Core Java Interview Questions.doc

    22/25

    everal things happen in a particular order to ensure the ob$ect is constructed properly )emory is allocatedfrom heap to hold all instance variables and implementation'specific data of the ob$ect and its superclasses.Implemenation'specific data includes pointers to class and method data. The instance variables of the ob$ects

    are initiali9ed to their default values. The constructor for the most derived class is invoked. The first thing aconstructor does is call the consctructor for its superclasses. This process continues until the constrcutor for

    $ava.lang.Ob$ect is called, as $ava.lang.Ob$ect is the base class for all ob$ects in $ava.

  • 8/14/2019 Core Java Interview Questions.doc

    23/25

    The ava pro"rammin" lan"ua"e supports static methods as well as static variables. *tatic methods! which havethe static modifier in their declarations! should be invoked with the class name! without the need for creatin" aninstance of the class! as in

    Class,ae.ethod,ae&args)oteI You can also refer to static methods with an object reference like instance,ae.ethod,ae&args)

    but this is discoura"ed because it does not make it clear that they are class methods.' common use for static methods is to access static fields. or e&ample! we could add a static method to theBicycle class to access the number9fBicycles static fieldIpublic staticint get,uber!"Bicycles&) { return nuber!"Bicycles;

    %

    ot all combinations of instance and class variables and methods are allowedI

    %nstance methods can access instance variables and instance methods directly.

    %nstance methods can access class variables and class methods directly.

    ,lass methods can access class variables and class methods directly.

    ,lass methods cannot access instance variables or instance methods directly they must use an object

    reference. 'lso! class methods cannot use the this keyword as there is no instance for this to refer to.@ethod =verridin'0ethod overridin" occurs when a class declares a method that has the same type si"nature as a method declaredby one of its superclasses. >ecall that a type si"nature is a combination of a method name and the se-uence of its

    parameter types. When a method in a subclass overrides a method in a superclass! the method in the superclassis hidden relative to the subclass object.0ethod overridin" is a very important capability because it forms the basis for run5ti$e oly$orhis$. >ecallthat polymorphism means one interface! multiple implementations. The si"nature of the method defines theinterface! and each overridden version provides a uni-ue implementation.

    's e&plained! a superclass reference can be used to refer to a subclass object. Ahe dyna$ic $ethod disatch$echanis$in ava selects the appropriate version of an overridden method to e&ecute based on the class of thee&ecutin" object! not the type of a variable that references that object. Thus! the actual version of an overriddenmethod that is e&ecuted is determined at run4time! not compile time.

  • 8/14/2019 Core Java Interview Questions.doc

    24/25

    odifier :unction

    0lasses ethod "ariables 0onstructor

    public ,lass is publicly accessible (the class can be used by any otherclass)

    0ethod is publ icl y accessible /ariabl es are publ icl y accessibl e 'ny class can use this constructor.

    protected ,lasses can be declared with security so they can be accessedoutside their packa"e by usin" the public statement in the classdeclaration. %f no e&plicit statement is made at declaration time! theclass may be accessed only from within its own packa"e. A compileerror is generated if any other security modifier is used in thedeclaration, such asprivate or protected, which are reserved formethods.

    ,lass members are accessible only to methods inthat class and subclasses of that class. This meansthat protected class members have visibility limited tosubclasses

    *ame as methods *ubclasses of this class and classes in the same packa"ecan use this constructor.

    +e"ault&no

    odi"ier) 9nly classes in the same packa"e can have access

    to a class s variables and methods*ame as methods %f no access specif ier is provided! the constructor has the

    default access (sometimes called packa"e private). 9nlyclasses within the same packa"e as this class can use thisconstructor.

    private 9nly inner classes can be rivate ,lass members are only accessible by the class theyare defined in. This means that no other class hasaccess to private class members! even subclasses

    *ame as methods 9nly this class can use this constructor. 0akin" aconstructor private! in essence! makes the class final the class can#t be subclassed! e&cept from within. %f allconstructors within a class are private! the class mi"htcontain public class methods (called factory methods) thatcreate and initiali$e an instance of this class. 9ther classescan use the factory methods to create an instance of thisclass.

    static Thestatickeyword can be used for inner classes! but can notbe used to re"ular classes. The static modifier is onlyapplicable toso4called member classes

    The static modifier specifies that a variable or method is the same for all objects of a

    particular class. Typically! new variables are allocated for each instance of a class. When avariable is declared as bein" static! it is only allocated once re"ardless of how many objectsare instantiated. The result is that all instantiated objects share the same instance of the staticvariable. *imilarly! a static method is one whose implementation is e&actly the same for allobjects of a particular class. This means that static methods only have access to staticvariables2eclares this is a %class variablerather than an instance variable. You also use static todeclare 2class methods.

    &

    -inal The cl ass cannot be subcl assed ' variabl e has a constant val ue or that a method cannot be overri dden in a subcl ass. ' classmember is the final version allowed for the class%ndicates that the value of this member cannot chan"e. ' compile4time constant is defined byusin" static and final to"ether

    abstract

    ,lass cannot be instantiated'n abstract class can only be subclassed.'n abstract class can contain abstract methods.%n practice! abstract classes usually provide a complete or partialimplementation of at least one method

    'n abstract method has no implementation and mustbe a member of an abstract class

    & &

    synchroniedThe class can not be

    synchronied./e can create synchronied blockThe synchroni$ed modifier is used to specify that a

    method is thread safe

    &

    native &

    The native modifier is used to identify methods thathave native implementations. The native modifierinforms the ava compiler that a method simplementation is in an e&ternal , file

    & &

    transient & S0arks member variables that shouldnot be seriali$ed. This component isused in object seriali$ation

    &

    volatile & S1revents the compiler from performin"certain optimi$ations on a member.

    &

    24

  • 8/14/2019 Core Java Interview Questions.doc

    25/25

    Controllin' 7ccess to @e$bers of a Class7ccess Levels

    ecifier ClassDac+a'eubclass World

    private 4

    no specifier 4 4 protected 4 4 4 public 4 4 4 4

    static +eyword

    %n order to understand the use of the statickeyword in class declaration! we need to understand the class declaration itself. You can declare two kinds ofclassesI top4level classes and inner classes.

    Ao5level classesYou declare a top4level class at the top level as a member of a packa"e. :ach top4level class corresponds to its ownjavafile sportin" the same name as the class

    name.' top4level class is by definition already top4level! so there is no point in declarin" it static it is an error to do so. The compiler will detect and report this error.

    Inner classesYou define an inner class within a top4level class. 2ependin" on how it is defined! an inner class can be one of the followin" four typesI

    %. 7nony$ous. 'nonymous classes are declared and instantiated within the same statement. They do not have names! and they can be instantiated only once.The followin" is an e&ample of an anonymous classIokButton.addActionListener& ne0 ActionListener&){

    public void action1er"ored&Action2vent e){

    dispose&);

    %

    %);

    Because an anonymous class doesn#t have a normal class declaration where it#s possible to use static! it cannot be declared static.

    2. Local.Local classes are the same as local variables! in the sense that they#re created and used inside a block. 9nce you declare a class within a block! it can

    be instantiated as many times as you wish within that block. Like local variables! local classes aren#t allowed to be declared public! protected! private! or static.

    3. @e$ber. 0ember classes are defined within the body of a class. You can use member classes anywhere within the body of the containin" class. You declaremember classes when you want to use variables and methods of the containin" class without e&plicit dele"ation.The member class is the only class that you can declare static. When you declare a member class! you can instantiate that member class only within the conte&t

    of an object of the outer class in which this member class is declared. %f you want to remove this restriction! you declarethe member class a static class.When you declare a member class with a static modifier! it becomes a nested top4level class and can be used as a normal top4level class as e&plained above.

    6. Hested to5level.' nested top4level class is a member classes with a static modifier. ' nested top4level class is just like any o ther top4level class e&cept that itis declared within another class or interface. ested top4level classes are typically used as a convenient way to "roup related classes without creatin" a newpacka"e.%f your main class has a few smaller helper classes that can be used outside the class and make sense only with your main class! it#s a "ood idea to make them

    nested top4level classes.

    25

    http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html#%23http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html#%23http://www.javaworld.com/javaworld/javaqa/1999-08/01-qa-static2.html#%23