You are on page 1of 35

We are going to discus about Object Class Methods in Java. The java.lang.

Object class is the root of the class hierarchy tree in JDE(java develop ent environ ent!. Every Java class e"tends the java.lang.Object class directly or indirectly. There are any ethods defined in java.lang.Object class these are as clone(!# e$uals(!# finali%e(!# notify(!# notify&ll(!# getClass(!# to'tring(!# (ait(!# etc

Class java.lang.Object
java.lang.Object

public class Object Class Object is the root of the class hierarchy. Every class has Object as a superclass. All objects, including arrays, implement the methods of this class. 'ee &lso) Class

Object()

clone() Creates a new object of the same class as this object. e$uals(Object) Compares two Objects for e uality. finali%e() Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. getClass() !eturns the runtime class of an object. hashCode() !eturns a hash code value for the object. notify() "a#es up a single thread that is waiting on this object$s monitor. notify&ll() "a#es up all threads that are waiting on this object$s monitor. to'tring() !eturns a string representation of the object. (ait() "aits to be notified by another thread of a change in this object. (ait(long) "aits to be notified by another thread of a change in this object. (ait(long, int)

"aits to be notified by another thread of a change in this object.

Object
public Object()

public final native Class getClass()

getClass

!eturns the runtime class of an object. *eturns) the object of type Class that represents the runtime class of the object. hashCode
public native int hashCode()

!eturns a hash code value for the object. %his method is supported for the benefit of hashtables such as those provided by java.util.Hashtable. %he general contract of hashCode is&

"henever it is invo#ed on the same object more than once during an e'ecution of a (ava application, the hashCode method must consistently return the same integer. %his integer need not remain consistent from one e'ecution of an application to another e'ecution of the same application. )f two objects are e ual according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.

*eturns) a hash code value for this object. 'ee &lso) e uals, *ashtable e$uals
public boolean equals(Object obj)

Compares two Objects for e uality. %he equals method implements an e uivalence relation&

)t is reflexive& for any reference value x, x.equals(x) should return true. )t is symmetric& for any reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. )t is transitive& for any reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true.

)t is consistent& for any reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false. +or any reference value x, x.equals(null) should return false.

%he e uals method for class Object implements the most discriminating possible e uivalence relation on objects, that is, for any reference values x and y, this method returns true if and only if x and y refer to the same object (x==y has the value true). +ara eters) obj - the reference object with which to compare. *eturns) true if this object is the same as the obj argument, false otherwise. 'ee &lso) hashCode, *ashtable clone
protected native Object clone() thro s Clone!ot"upported#xception

Creates a new object of the same class as this object. )t then initiali.es each of the new object$s fields by assigning it the same value as the corresponding field in this object. /o constructor is called. %he clone method of class Object will only clone an object whose class indicates that it is willing for its instances to be cloned. A class indicates that its instances can be cloned by declaring that it implements the Cloneable interface. *eturns) a clone of this instance. Thro(s) Clone/ot0upportedE'ception if the object$s class does not support the Cloneable interface. 0ubclasses that override the clone method can also throw this e'ception to indicate that an instance cannot be cloned. Thro(s) OutOf1emoryError if there is not enough memory. 'ee &lso) Cloneable to'tring !eturns a string representation of the object. )n general, the to"tring method returns a string that 2te'tually represents2 this object. %he result should be a concise but informative representation that is easy for a person to read. )t is recommendedthat all subclasses override this method. %he to"tring method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character 3$$, and the unsigned he'adecimal representation of the hash code of the object. *eturns)

public "tring to"tring()

a string representation of the object. notify


public final native void notify()

"a#es up a single thread that is waiting on this object$s monitor. A thread waits on an object$s monitor by calling one of the ait methods. %his method should only be called by a thread that is the owner of this object$s monitor. A thread becomes the owner of the object$s monitor in one of three ways&

4y e'ecuting a synchroni.ed instance method of that object. 4y e'ecuting the body of a synchronized statement that synchroni.es on the object. +or objects of type Class% by e'ecuting a synchroni.ed static method of that class.

Only one thread at a time can own an object$s monitor. Thro(s) )llegal1onitor0tateE'ception if the current thread is not the owner of this object$s monitor. 'ee &lso) notifyAll, wait notify&ll
public final native void notify&ll()

"a#es up all threads that are waiting on this object$s monitor. A thread waits on an object$s monitor by calling one of the ait methods. %his method should only be called by a thread that is the owner of this object$s monitor. 0ee the notify method for a description of the ways in which a thread can become the owner of a monitor. Thro(s) )llegal1onitor0tateE'ception if the current thread is not the owner of this object$s monitor. 'ee &lso) notify, wait
public final native void

(ait

ait(long ti'eout) thro s (nterrupted#xception

"aits to be notified by another thread of a change in this object. %he current thread must own this object$s monitor. %he thread releases ownership of this monitor and waits until either of the following two conditions has occurred&

Another thread notifies threads waiting on this object$s monitor to wa#e up either through a call to the notify method or the notify&ll method. %he timeout period, specified by the ti'eout argument in milliseconds, has elapsed.

%he thread then waits until it can re-obtain ownership of the monitor and resumes e'ecution. %his method should only be called by a thread that is the owner of this object$s monitor. 0ee the notify method for a description of the ways in which a thread can become the owner of a monitor. +ara eters) timeout - the ma'imum time to wait in milliseconds. Thro(s) )llegalArgumentE'ception if the value of timeout is negative. Thro(s) )llegal1onitor0tateE'ception if the current thread is not the owner of the object$s monitor. Thro(s) )nterruptedE'ception if another thread has interrupted this thread. 'ee &lso) notify, notifyAll (ait
public final void ait(long ti'eout% int nanos) thro s (nterrupted#xception

"aits to be notified by another thread of a change in this object. %his method is similar to the ait method of one argument, but it allows finer control over the amount of time to wait for a notification before giving up. %he current thread must own this object$s monitor. %he thread releases ownership of this monitor and waits until either of the following two conditions has occurred&

Another thread notifies threads waiting on this object$s monitor to wa#e up either through a call to the notify method or the notify&ll method. %he timeout period, specified by ti'eout milliseconds plus nanos nanoseconds arguments, has elapsed.

%he thread then waits until it can re-obtain ownership of the monitor and resumes e'ecution %his method should only be called by a thread that is the owner of this object$s monitor. 0ee the notify method for a description of the ways in which a thread can become the owner of a monitor. +ara eters) timeout - the ma'imum time to wait in milliseconds. nano - additional time, in nanoseconds range 5-666666. Thro(s) )llegalArgumentE'ception if the value of timeout is negative or the value of nanos is not in the range 5-666666. Thro(s) )llegal1onitor0tateE'ception if the current thread is not the owner of this object$s monitor.

Thro(s) )nterruptedE'ception if another thread has interrupted this thread. (ait


public final void ait() thro s (nterrupted#xception

"aits to be notified by another thread of a change in this object. %he current thread must own this object$s monitor. %he thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object$s monitor to wa#e up either through a call to the notify method or the notify&ll method. %he thread then waits until it can re-obtain ownership of the monitor and resumes e'ecution. %his method should only be called by a thread that is the owner of this object$s monitor. 0ee the notify method for a description of the ways in which a thread can become the owner of a monitor. Thro(s) )llegal1onitor0tateE'ception if the current thread is not the owner of the object$s monitor. Thro(s) )nterruptedE'ception if another thread has interrupted this thread. 'ee &lso) notify, notifyAll finali%e Called by the garbage collector on an object when garbage collection determines that there are no more references to the object. A subclass overrides the finalize method to dispose of system resources or to perform other cleanup. Any e'ception thrown by the finalize method causes the finali.ation of this object to be halted, but is otherwise ignored. %he finalize method in Object does nothing.

protected void finalize() thro s )hro able

What,s the difference bet(een an application server and a (eb serverA "eb 0erver understands and supports only *%%7 protocol whereas an Application 0erver supports *%%7,%C78)7 and many more protocols. Also many more features such as Caches,Clusters,9oad 4alancing are there in Application 0ervers which are not available in "eb 0ervers. "e can also Configure Application 0ervers to wor# as "eb 0erver. )n short, Applicaion 0erver is a super set of which "eb 0erver is a sub set. :ou can$t run E(4 or any business logic in (avawebserver. An application server should have the capability to run business logic in it. %hat$s why we can$t say that ("server a application server. %he "eb server&

A "eb server handles the *%%7 protocol. "hen the "eb server receives an *%%7 re uest, it responds with an *%%7 response, such as sending bac# an *%19 page. %o process a re uest, a "eb server may respond with a static *%19 page or image, send a redirect, or delegate the dynamic response generation to some other program such as C;) scripts, (07s ((ava0erver 7ages), servlets, A07s (Active 0erver 7ages), server-side (ava0cripts, or some other server-side technology. "hatever their purpose, such server-side programs generate a response, most often in *%19, for viewing in a "eb browser. <nderstand that a "eb server$s delegation model is fairly simple. "hen a re uest comes into the "eb server, the "eb server simply passes the re uest to the program best able to handle it. %he "eb server doesn$t provide any functionality beyond simply providing an environment in which the server-side program can e'ecute and pass bac# the generated responses. %he server-side program usually provides for itself such functions as transaction processing, database connectivity, and messaging. "hile a "eb server may not itself support transactions or database connection pooling, it may employ various strategies for fault tolerance and scalability such as load balancing, caching, and clustering=features oftentimes erroneously assigned as features reserved only for application servers. Eg& Apache *%%7 0erver, 0un O/E "eb 0erver, i7lanet "eb 0erver %he application server& As for the application server, according to our definition, an application server e'poses business logic to client applications through various protocols, possibly including *%%7. "hile a "eb server mainly deals with sending *%19 for display in a "eb browser, an application server provides access to business logic for use by client application programs. %he application program can use this logic just as it would call a method on an object (or a function in the procedural world). 0uch application server clients can include ;<)s (graphical user interface) running on a 7C, a "eb server, or even other application servers. %he information traveling bac# and forth between an application server and its client is not restricted to simple display mar#up. )nstead, the information is program logic. 0ince the logic ta#es the form of data and method calls and not static *%19, the client can employ the e'posed business logic however it wants. )n most cases, the server e'poses this business logic through a component A7), such as the E(4 (Enterprise (ava4ean) component model found on (>EE ((ava > 7latform, Enterprise Edition) application servers. 1oreover, the application server manages its own resources. 0uch gate#eeping duties include security, transaction processing, resource pooling, and messaging. 9i#e a "eb server, an application server may also employ various scalability and fault-tolerance techni ues.

Exception Handling

? An e'ception is an event, which occurs during the e'ecution of a program, that interrupts the normal flow of the program. )t is an error thrown by a class or method reporting an error in code. ? %he $%hrowable$ class is the superclass of all errors and e'ceptions in the (ava language ? E'ceptions are broadly classified as .chec/ed e"ceptions. and .unchec/ed e"ceptions$. &ll *unti eE"ceptions and Errors are unchec/ed e"ceptions. !est of the e'ceptions are called chec#ed e'ceptions. Chec#ed e'ceptions should be handled in the code to avoid compile time errors. ? E'ceptions can be handled by using $try-catch$ bloc#. %ry bloc# contains the code which is under observation for e'ceptions. %he catch bloc# contains the remedy for the e'ception. )f any e'ception occurs in the try bloc# then the control jumps to catch bloc#. ? )f a method doesn$t handle the e'ception, then it is mandatory to specify the e'ception type in the method signature using $throws$ clause. ? "e can e'plicitly throw an e'ception using $throw$ clause http&88www.java>novice.com8java@interview@ uestions8

0uestion) 1ive the list of Java Object class ethods.


clone() * Creates and returns a copy of this object. equals() * (ndicates hether so'e other object is +equal to+ this one. finalize() * Called by the garbage collector on an object hen garbage collection deter'ines that there are no 'ore references to the object. getClass() * ,eturns the runti'e class of an object.

hashCode() * ,eturns a hash code value for the object. notify() * -a.es up a single thread that is aiting on this object/s 'onitor. notify&ll() * -a.es up all threads that are aiting on this object/s 'onitor. to"tring() * ,eturns a string representation of the object. ait() * Causes current thread to ait until another thread invo.es the notify() 'ethod or the notify&ll() 'ethod for this object.

0uestion) Can Java thread object invo/e start ethod t(icepac.age co'.java0novice.ex'pcode1 public class 2y#x'pCode extends )hread3 public void run()3 "yste'.out.println(+,un+)1 4 public static void 'ain("tring a56)3 )hread t7 = ne )hread(ne 2y#x'pCode())1 t7.start()1 t7.start()1 4 4 !o% it thro s (llegal)hread"tate#xception

0uestion) Can (e call servlet destory(! fro service(!&s you .no % destory() is part of servlet life cycle 'ethods% it is used to .ill the servlet instance. "ervlet #ngine is used to call destory(). (n case% if you call destroy 'ethod fro' service()% it just execute the code ritten in the destory()% but it on8t .ill the servlet instance. destroy() ill be called before .illing the servlet instance by servlet engine.

0uestion) Can (e override static

ethod-

-e cannot override static 'ethods. "tatic 'ethods are belogs to class% not belongs to object. (nheritance ill not be applicable for class 'e'bers

0uestion) Can you list seriali%ation

ethods-

"erialization interface does not have any 'ethods. (t is a 'ar.er interface. (t just tells that your class can be serializable.

0uestion) What is the difference bet(een super(! and this(!super() is used to call super class constructor% hereas this() used to call constructors in the sa'e class% 'eans to call para'eterized constructors.

0uestion) 2o( to prevent a being overridden-

ethod fro

9y specifying final .ey ord to the 'ethod you can avoid overriding in a subcalss. "i'ilarlly one can use final at class level to prevent creating subclasses.

0uestion) Can (e create abstract classes (ithout any abstract ethods:es% e can create abstract classes ithout any abstract 'ethods.

0uestion) 2o( to destroy the session in servlets9y calling invalidate() 'ethod on session object% e can destory the session.

0uestion) Can (e have static interface-

ethods in

9y default% all 'ethods in an interface are decleared as public% abstract. (t ill never be static.

0uestion) What is transient variable)ransient variables cannot be serialized. ;uring serialization process% transient variable states ill not be serialized. "tate of the value ill be al ays defaulted after deserialization.

0uestion) 3ncase# there is a return at the end of try bloc/# (ill e"ecute finally bloc/:es% the finally bloc. ill be executed even after riting return state'ent at the end fo try bloc.. (t returns after executing finally bloc..

0uestion) What is abstract class or abstract ethod-e cannot create instance for an abstract class. -e can able to create instance for its subclass only. 9y specifying abstract .ey ord just before class% e can 'a.e a class as abstract class. public abstract class 2y&bstractClass3 4 &bstract class 'ay or 'ay not contains abstract 'ethods. &bstract 'ethod is just 'ethod signature% it does not containes any i'ple'entation. (ts subclass 'ust provide i'ple'entation for abstract 'ethods. &bstract 'ethods are loo.s li.e as given belo < public abstract int get=ength()1

0uestion) What is default value of a boolean;efault value of a boolean is false.

0uestion) When to use 4in/ed4ist or &rray4ist&ccessing ele'ents are faster ith &rray=ist% because it is index based. 9ut accessing is difficult ith =in.ed=ist. (t is slo access. )his is to access any ele'ent% you need to navigate through the ele'ents one by one. 9ut insertion and deletion is 'uch faster ith =in.ed=ist% because if you .no the node% just change the pointers before or after nodes. (nsertion and deletion is slo ith &rray=ist% this is because% during these operations &rray=ist need to adjust the indexes according to deletion or insetion if you are perfor'ing on 'iddle indexes. 2eans% an &rray=ist having 7> ele'ents% if you are inserting at index ?% then you need to shift the indexes above ? to one 'ore.

0uestion) What is dae on thread-

;ae'on thread is a lo priority thread. (t runs inter'ittently in the bac. ground% and ta.es care of the garbage collection operation for the java runti'e syste'. 9y calling set;ae'on() 'ethod is used to create a dae'on thread.

0uestion) Does each thread in java uses seperate stac/Answer&


(n @ava every thread 'aintains its o n separate stac.. (t is called ,unti'e "tac. but they share the sa'e 'e'ory.

0uestion) What is the difference bet(een Enu eration and 3teratorAnswer&


)he functionality of #nu'eration and the (terator are sa'e. :ou can get re'ove() fro' (terator to re'ove an ele'ent% hile hile #nu'eration does not have re'ove() 'ethod. Asing #nu'eration you can only traverse and fetch the objects% here as using (terator e can also add and re'ove the objects. "o (terator can be useful if you ant to 'anipulate the list and #nu'eration is for read*only access.

0uestion) 5ind out belo( s(itch state ent output.


Code&
public static void 'ain("tring a56)3 int price = B1 s itch (price) 3 case 0< "yste'.out.println(+(t is< 0+)1 default< "yste'.out.println(+(t is< default+)1 case ?< "yste'.out.println(+(t is< ?+)1 case C< "yste'.out.println(+(t is< C+)1 4 4

Answer&
(t is< default (t is< ? (t is< C

0uestion) Does syste .e"it(! in try bloc/

e"ecutes code in finally bloc/Code&


try3 "yste'.out.println(+( a' in try bloc.+)1 "yste'.exit(7)1 4 catch(#xception ex)3 ex.print"tac.)race()1 4 finally 3 "yste'.out.println(+( a' in finally bloc.DDD+)1 4

Answer&
(t ill not execute finally bloc.. )he progra' after "yste'.exit() state'ent. ill be ter'inated

0uestion) What is fail6fast in java& fail*fast syste' is nothing but i''ediately report any failure that is li.ely to lead to failure. -hen a proble' occurs% a fail*fast syste' fails i''ediately. (n @ava% e can find this behavior ith iterators. (ncase% you have called iterator on a collection object% and another thread tries to 'odify the collection object% then concurrent 'odification exception ill be thro n. )his is called fail*fast.

0uestion) What is final# finally and finali%efinal< final is a .ey ord. )he variable decleared as final should be initialized only once and cannot be changed. @ava classes declared as final cannot be extended. 2ethods declared as final cannot be overridden. finally< finally is a bloc.. )he finally bloc. al ays executes hen the try bloc. exits. )his ensures that the finally bloc. is executed even if an unexpected exception occurs. 9ut finally is useful for 'ore than just exception handling * it allo s the progra''er to avoid having cleanup code accidentally bypassed by a return% continue% or brea.. Eutting cleanup code in a finally bloc. is al ays a good practice% even hen no exceptions are anticipated. finalize< finalize is a 'ethod. 9efore an object is garbage collected% the runti'e syste' calls its finalize() 'ethod. :ou can rite syste'

resources release code in finalize() 'ethod before getting garbage collected.

0uestion) 3n java# are true and false /eywordsA


true% false% and null 'ight see' li.e .ey ords% but they are actually literals. :ou cannot use the' as identifiers in your progra's.

0uestion) What are the different session trac/ing ethodsCoo.ies< :ou can use H))E coo.ies to store infor'ation. Coo.ies stored at bro ser side. ill be A,= re riting< -ith this 'ethod% the infor'ation is carried through url as request para'eters. (n general added para'eter ill be sessionid% userid. Http"ession< Asing Http"ession% e can store infor'ation at server side. Http "ession provides 'ethods to handle session related infor'ation. Hidden for' fields< 9y using hidden for' fields e can insert infor'ation in the ebpages and these infor'ation ill be sent to the server. )hese fields are not visible directly to the user% but can be vie ed using vie source option fro' the bro sers. )he hidden for' fields are as given belo < Finput type=/hidden/ na'e=/site!a'e/ value=/java0novice/GH

0uestion) What is the purpose of garbage collection)he garbage collection process is to identify the objects hich are no longer referenced or needed by a progra' so that their resources can be reclai'ed and reused. )hese identified objects ill be discarded

0uestion) What are the types of *esult'et)he type of a ,esult"et object deter'ines the level of its functionality in t o areas< the ays in hich the cursor can be 'anipulated% and ho concurrent

changes 'ade to the underlying data source are reflected by the ,esult"et object. )he sensitivity of a ,esult"et object is deter'ined by one of three different ,esult"et types< ):E#IJO,-&,;IO!=:< )he result set cannot be scrolled1 its cursor 'oves for ard only% fro' before the first ro to after the last ro . )he ro s contained in the result set depend on ho the underlying database generates the results. )hat is% it contains the ro s that satisfy the query at either the ti'e the query is executed or as the ro s are retrieved. ):E#I"C,O==I(!"#!"()(K#< )he result can be scrolled1 its cursor can 'ove both for ard and bac. ard relative to the current position% and it can 'ove to an absolute position. )he result set is insensitive to changes 'ade to the underlying data source hile it is open. (t contains the ro s that satisfy the query at either the ti'e the query is executed or as the ro s are retrieved. ):E#I"C,O==I"#!"()(K#< )he result can be scrolled1 its cursor can 'ove both for ard and bac. ard relative to the current position% and it can 'ove to an absolute position. )he result set reflects changes 'ade to the underlying data source hile the result set re'ains open. )he default ,esult"et type is ):E#IJO,-&,;IO!=:.

0uestion) What is difference bet(een (ait and sleep ethods in javasleep()< (t is a static 'ethod on )hread class. (t 'a.es the current thread into the +!ot ,unnable+ state for specified a'ount of ti'e. ;uring this ti'e% the thread .eeps the loc. ('onitors) it has acquired. (t is a 'ethod on Object class. (t 'a.es the current thread into the +!ot ,unnable+ state. -ait is called on a object% not a thread. 9efore calling ait() 'ethod% the object should be synchronized% 'eans the object should be inside synchronized bloc.. ait()<

)he call to

ait() releases the acquired loc..

0uestion) What is servlet conte"t)he servlet context is an interface hich helps to co''unicate ith other servlets. (t contains infor'ation about the -eb application and container. (t is .ind of application environ'ent. Asing the context% a servlet can obtain A,= references to resources% and store attributes that other servlets in the context can use.

0uestion) What happens if one of the e bers in a class does not i ple ent 'eriali%able interface-hen you try to serialize an object hich i'ple'ents "erializable interface% incase if the object includes a reference of an non serializable object then !ot"erializable#xception ill be thro n.

0uestion) What is race condition& race condition is a situation in hich t o or 'ore threads or processes are reading or riting so'e shared data% and the final result depends on the ti'ing of ho the threads are scheduled. ,ace conditions can lead to unpredictable results and subtle progra' bugs. & thread can prevent this fro' happening by loc.ing an object. -hen an object is loc.ed by one thread and another thread tries to call a synchronized 'ethod on the sa'e object% the second thread ill bloc. until the object is unloc.ed.

0uestion) 2o( to get current ti e in seconds-

illi

"yste'.current)i'e2illis() returns the current ti'e in 'illiseconds. (t is a static 'ethod% returns long type.

0uestion) 2o( can you convert Map to 4ist-e .no that 2ap contains .ey*value pairs% hereas a list contains only objects. "ince #ntry class contains both .ey*value pair% #ntry class ill helps us to convert fro' 2ap (Hash2ap) to =ist (&rray=ist). 9y using 2ap.entry"et() you ill get "et object% hich intern you can use it to convert to list object. public static void 'ain("tring a56)3 2apF"tring% "tringH ord2ap = ne Hash2apF"tring% "tringH()1

"etF#ntryF"tring% "tringHH set = ord2ap.entry"et()1 =istF#ntryF"tring% "tringHH list = ne &rray=istF#ntryF"tring% "tringHH(set)1 4

0uestion) What is strictfp /ey(ord9y using strictfp .ey ord% ta.e place precisely. e can ensure that floating point operations

0uestion) What is 'yste .out in JavaHere out is an instance of Erint"trea'. (t is a static 'e'ber variable in "yste' class. )his is called standard output strea'% connected to console.

0uestion) What is difference bet(een 'ervletOuptput'trea and +rintWriter"ervletOutput"trea'< "ervlet,esponse.getOutput"trea'() returns a "ervletOutput"trea' suitable for riting binary data in the response. )he servlet container does not encode the binary data% it sends the ra data as it is. Erint-riter< "ervlet,esponse.get-riter() returns Erint-riter object hich sends character text to the client. )he Erint-riter uses the character encoding returned by getCharacter#ncoding(). (f the response/s character encoding has not been specified then it does default character encoding.

0uestion) What is java static i port9y using static i'ports% e can i'port the static 'e'bers fro' a class rather than the classes fro' a given pac.age. Jor exa'ple% )hread class has static sleep 'ethod% belo exa'ple gives an idea< i'port static java.lang.)hread1 public class 2y"tatic('port)est 3 public static void 'ain("tring56 a) 3 try3 sleep(7>>)1 4 catch(#xception ex)3 4 4

0uestion) When to use 'tring and 'tring7uffer-e .no that "tring is i''utable object. -e can not change the value of a "tring object once it is initiated. (f e try to change the value of the existing "tring object then it creates ne object rather than changing the value of the existing object. "o incase% e are going to do 'ore 'odificatios on "tring% then use "tring9uffer. "tring9uffer updates the existing objects value% rather creating ne object.

0uestion) What is difference bet(een 'tring7uffer and 'tring7uilder)he only difference bet een "tring9uffer and "tring9uilder is "tring9uffer is thread*safe% that is "tring9uffer is synchronized.

0uestion) What is (rapper class in java#verything in java is an object% except pri'itives. Eri'itives are int% short% long% boolean% etc. "ince they are not objects% they cannot return as objects% and collection of objects. )o support this% java provides rapper classes to 'ove pri'itives to objects. "o'e of the rapper classes are (nteger% =ong% 9oolean% etc.

0uestion) 3s 3terator a Class(terator is an interface. (t is not a class. (t is used to iterate through each and every ele'ent in a list. (terator is i'ple'ented (terator design pattern.

0uestion) What is java classpath)he classpath is an environ'ent variable. (t is used to let the co'piler .no here the class files are available for i'port.

0uestion) Can a class in java be private-e can not declare top level class as private. @ava allo s only public and default 'odifier for top level classes in java.

(nner classes can be private.

0uestion) 3s null a /ey(ord in java)he null value is not a .ey ord in java. true and flase are also not .ey ords in java. )hey are reserved ords in java language.

0uestion) What is the initial state of a thread (hen it is started-hen the thread is createdn and started% initially it in the ready state. ill be

0uestion) What is the super class for E"ception and Error)he super class or base class for #xception and #rror is )hro able.

0uestion) What is Class.for8a e(!Class.for!a'e() loads the class into the Class=oader.

0uestion) Can interface be final!o. -e can not instantiate interfaces% so in order to 'a.e interfaces useful e 'ust create subclasses. )he final .ey ord 'a.es a class unable to be extended.

0uestion) What is the difference bet(een e"ception and error&n error is an irrecoverable condition occurring at runti'e li.e out of 'e'ory error. )hese .ind of jv' errors cannot be handled at runti'e. #xceptions are because of condition failures% hich can be handled easily at runti'e.

0uestion) What is default value of a local variables-

)he local variables are not initialized to any default values. -e should not use local variables ith out initialization. #ven the java co'piler thro s error.

0uestion) What is local class in java(n java% local classes can be defined in a bloc. as in a 'ethod body or local bloc..

0uestion) Can (e initialise uninitiali%ed final variable:es. -e can initialise blan. final variable in constructor% only in construtor. )he condition here is the final variable should be non*static.

0uestion) Can (e declare abstract final!o% e can not declare abstract 'ethod as final. -e have to proved i'ple'entation to abstract 'ethods in subclasses.

ethod as

0uestion) Can (e have finally bloc/ (ithout catch bloc/:es% e can have finally bloc. ithout catch bloc..

0uestion) What is pass by value and pass by referenceEass by value< Eassing a copy of the value% not the original reference. Eass by reference< Easssing the address of the object% so that you can access the original object.

0uestion) Can (e declare private:es%

ain

ethod as
ithout

e can declare 'ain 'ethod as private. (t co'piles

any errors% but in runti'e% it says 'ain 'ethod is not public.

0uestion) What is the difference bet(een pree ptive scheduling and ti e slicingPreemptive scheduling: )he highest priority tas. executes until it enters the aiting or dead states or a higher priority tas. co'es into existence. Time slicing: & tas. executes for a predefined slice of ti'e and then reenters the pool of ready tas.s. )he scheduler then deter'ines hich tas. should execute next% based on priority and other factors.

0uestion) Can non6static e ber classes (4ocal classes! have static e bers!o% non*static 'e'ber classes cannot have static 'e'bers. 9ecause% an instance of a non*static 'e'ber class or local class 'ust be created in the context of an instance of the enclosing class. :ou can declare constants% 'eans static final variables.

0uestion) What are the environ ent variables do (e neet to set to run Java-e need to set t o environ'ent variables those are E&)H and C=&""E&)H.

0uestion) Can you seriali%e static fields of a class"ince static fields are not part of object state% they are part of class% serialization ignores the static fields.

0uestion) What is the difference bet(een declaring a variable and defining a variableWhen variable declaration we just mention the type of the variable and it's name, it does not have any reference to live object. But defining means combination of declaration and initialization. The examples are as given below Declaration:

!ist list" Defining: !ist list # new $rray!ist%&"

0uestion) Where can (e use seriali%ationWhenever an object has to sent over the networ', those objects should be serialized. $lso if the state of an object is to be saved, objects need to be serilazed.

0uestion) What odifiers are allo(ed for ethods in an 3nterface(nly public and abstract modifiers are allowed for methods in an interfaces.

0uestion) What is the purpose of *unti e and 'yste classThe purpose of the )untime class is to provide access to the *ava runtime system. The runtime information li'e memory availability, invo'ing the garbage collector, etc. The purpose of the +ystem class is to provide access to system resources. ,t contains accessibility to standard input, standart output, error output streams, current time in millis, terminating the application, etc.

0uestion) Which one is faster- &rray4ist or 9ector- Why$rray!ist is faster than -ector. The reason is synchronization. -ector is synchronized. $s we 'now synchronization reduces the performance.

0uestion) What is the difference bet(een static synchroni%ed and synchroni%ed ethods+tatic synchronized methods synchronize on the class object. ,f one thread is executing a static synchronized method, all other threads trying to execute any static synchronized methods will be bloc'ed.

.on/static synchronized methods synchronize on this ie the instance of the class. ,f one thread is executing a synchronized method, all other threads trying to execute any synchronized methods will be bloc'ed.

0uestion) What is the order of catch bloc/s (hen catching ore than one e"ceptionWhen you are handling multiple catch bloc's, ma'e sure that you are specifing exception sub classes first, then followed by exception super classes. (therwise we will get compile time error.

0uestion) What is the difference bet(een the prefi" and postfi" for s of the incre ent(::! operatorThe prefix form first performs the increment operation and then returns the value of the increment operation. The postfix form first returns the current value of the expression and then performs the increment operation on that value. 0or example int count#1" +ystem.out.println%22count&" displays 3. $nd int count#1" +ystem.out.println%count22&" displays 1.

0uestion) What is hashCodeThe hashcode of a *ava (bject is simply a number, it is 43/bit signed int, that allows an object to be managed by a hash/based data structure. We 'now that hash code is an uni5ue id number allocated to an object by *-6. But actually spea'ing, 7ash code is not an uni5ue number for an object. ,f two objects are e5uals then these two objects should return same hash code. +o we have to implement hashcode%& method of a class in such way that if two objects are e5uals, ie compared by e5ual%& method of that class, then those two objects must return same hash code. ,f you are overriding hash8ode you need to override e5uals method also.

0uestion) What is the difference bet(een 2ashtable and 2ashMap-

The basic differences are 7ashtable is synchronized and 7ash6ap is not synchronized. 7ashtable does not allow null values, and 7ash6ap allows null values.

0uestion) What are the restrictions (hen overriding a ethod(verriding methods must have the same name, parameter list, and same return type. i.e., they must have the exact signature of the method we are going to override, including return type. The overriding method cannot be less visible than the method it overrides. i.e., a public method cannot be override to private. The overriding method may not throw any exceptions that may not be thrown by the overridden method.

0uestion) What is the use of assert /ey(ord*ava assertion feature allows developer to put assert statements in *ava source code to help unit testing and debugging. $ssert 'eyword validates certain expressions. ,t replaces the if bloc' effectively and throws an $ssertion9rror on failure.

0uestion) What is adapter class$n adapter class provides the default implementation of all methods in an event listener interface. $dapter classes are very useful when you want to process only few of the events that are handled by a particular event listener interface. :ou can define a new class by extending one of the adapter classes and implement only those events relevant to you.

0uestion) What is difference bet(een brea/# continue and return state entsThe brea' statement results in the termination of the loop, it will come out of the loop and stops further iterations. The continue statement stops the current execution of the iteration and proceeds to the next iteration. The return statement ta'es you out of the method. ,t stops executing the method and returns from the method execution.

0uestion) What is the difference bet(een (hile and do6(hile state entsThe while statement verifies the condition before entering into the loop to see whether the next loop iteration should occur or not. The do/while statement executes the first iteration without chec'ing the condition, it verifies the condition after finishing each iteration. The do/while statement will always execute the body of a loop at least once.

0uestion) When does the co piler provides the default constructorThe compiler provides a default constructor if no other constructors are available in the class. ,n case the class contains parametarized constructors, compiler doesnot provide the default constructor.

0uestion) What are the advantages of java pac/age.


*ava pac'ages helps to resolve naming conflicts when different pac'ages have classes with the same names. This also helps you organize files within your project. 0or example, java.io pac'age do something related to ,;( and java.net pac'age do something to do with networ' and so on. ,f we tend to put all .java files into a single pac'age, as the project gets bigger, then it would become a nightmare to manage all your files.

0uestion) What is dyna ic class loadingBynamic loading is a techni ue for programmatically invo#ing the functions of a class loader at run time. 9et us loo# at how to load classes dynamically by using Class.forName (String className); method, it is a static method. %he above static method returns the class object associated with the class name. %he string class/ame can be supplied dynamically at run time. Once the class is dynamically loaded the class.newInstance () method returns an instance of the loaded class. )t is just li#e creating a class object with no arguments. A ClassNotFoundException is thrown when an application tries to load in a class through its class name, but no definition for the class with the specified name could be found.

0uestion) What happens if you do not provide a constructor*ava does not actually re5uire an explicit constructor in the class description. ,f you do not include a constructor, the *ava compiler will create a default constructor in the byte code with an empty argument.

0uestion) Difference bet(een shallo( cloning and deep cloning of objects%he default behavior of an objectCs clone() method automatically yields a shallow copy. 0o to achieve a deep copy the classes must be edited or adjusted. Shallow copy ;enerally clone method of an object, creates a new instance of the same class and copies all the fields to the new instance and returns it. %his is called shallow copy. Object class provides a clone method and provides support for the shallow copy. )t returns DObjectC as type and you need to e'plicitly cast bac# to your original object. 0ince the Object class has the clone method, you cannot use it in all your classes. %he class which you want to be cloned should implement clone method and overwrite it. )t should provide its own meaning for copy or to the least it should invo#e the super.clone(). Also you have to implement Cloneable mar#er interface or else you will get Clone/ot0upportedE'ception. "hen you invo#e the super.clone() then you are dependent on the Object classCs implementation and what you get is a shallow copy. !eep copy "hen you need a deep copy then you need to implement it yourself. "hen the copied object contains some other object its references are copied recursively in deep copy. "hen you implement deep copy be careful as you might fall for cyclic dependencies. )f you donCt want to implement deep copy yourselves then you can go for seriali.ation. )t does implements deep copy implicitly and gracefully handling cyclic dependencies.

0uestion) Can (e have interfaces (ith no defined ethods in java%he interfaces with no defined methods act li#e mar#ers. %hey just tell the compiler that the objects of the classes implementing the interfaces with no defined methods need to be treated differently. 1ar#er interfaces are also #nown as EtagF interfaces.

0uestion) What is the difference bet(een ;<<= and e$uals(! ethod%he GG (double e uals) returns true, if the variable reference points to the same object in memory. %his is called Eshallow comparisonF. %he e uals() method calls the user implemented e uals() method, which compares the object attribute values. %he e uals() method provides Edeep comparisonF by chec#ing if two objects are logically e ual as opposed to the shallow comparison provided by the operator GG.

)f e uals() method does not e'ist in a user supplied class then the inherited Object class$s e uals() method will be called which evaluates if the references point to the same object in memory. )n this case, the object.e uals() wor#s just li#e the 2GG2 operator.

0uestion) 2o( can you create an i class in java*ere are the steps to create immutable class& Beclare the class as final, we can not e'tend the final class. public final class MyTestImmutable { ... } Beclare all fields as final. +inal fields can not be changed once its assigned. private final int salary;

utable

Bo not provide any method which can change the state of the object, for e'ample the setter methods which changes the values of the instance variables. %he EthisF reference is not allowed to escape during construction from the immutable class and the immutable class should have e'clusive access to fields that contain references to mutable objects li#e arrays, collections and mutable classes li#e Bate etc by& Beclaring the mutable references as private. /ot returning or e'posing the mutable references to the caller.

0uestion) What are access

odifiers in java-

pu"lic A class or interface may be accessed from outside the pac#age. Constructors, inner classes, methods and field variables may be accessed wherever their class is accessed. protected Accessed by other classes in the same pac#age or any subclasses of same pac#age or different pac#age. pri#ate Accessed only within the class in which they are declared. no modifier (default modifier) Accessed only with in the class.

0uestion) Can (e have private constructor in

java7rivate constructor is used if you do not want other classes to instantiate the object. 7rivate constructors are used in singleton design pattern, factory method design pattern.

0uestion) Why do (e need generics in javaCode that uses generics has many benefits over non-generic code& >! 'tronger type chec/s at co pile ti e) A (ava compiler applies strong type chec#ing to generic code and issues errors if the code violates type safety. +i'ing compile-time errors is easier than fi'ing runtime errors, which can be difficult to find. ?! Eli ination of casts) )f you use generics, then e'plicit type casting is not re uired. @! Enabling progra ers to i ple ent generic algorith s) 4y using generics, programmers can implement generic algorithms that wor# on collections of different types, can be customi.ed, and are type safe and easier to read.

http&88www.tutorialspoint.com8java8java@object@classes.htm ava is an Object-Oriented 9anguage. As a language that has the Object Oriented feature, (ava supports the following fundamental concepts&

7olymorphism )nheritance Encapsulation Abstraction Classes Objects )nstance

1ethod 1essage 7arsing

)n this chapter, we will loo# into the concepts Classes and Objects.

Object 6 Objects have states and behaviors. E'ample& A dog has states - color, name, breed as well as behaviors -wagging, bar#ing, eating. An object is an instance of a class. Class 6 A class can be defined as a template8blue print that describes the behaviors8states that object of its type support.

Objects in Java)
9et us now loo# deep into what are objects. )f we consider the real-world we can find many objects around us, Cars, Bogs, *umans, etc. All these objects have a state and behavior. )f we consider a dog, then its state is - name, breed, color, and the behavior is - bar#ing, wagging, running )f you compare the software object with a real world object, they have very similar characteristics. 0oftware objects also have a state and behavior. A software object$s state is stored in fields and behavior is shown via methods. 0o in software development, methods operate on the internal state of an object and the object-toobject communication is done via methods.

Classes in Java)
A class is a blue print from which individual objects are created. A sample of a class is given below&
public class ;og3 "tring breed1 int age1 "tring color1 void bar.ing()3 4 void hungry()3 4 void sleeping()3 4

A class can contain any of the following variable types.

4ocal variables) Hariables defined inside methods, constructors or bloc#s are called local variables. %he variable will be declared and initiali.ed within the method and the variable will be destroyed when the method has completed. 3nstance variables) )nstance variables are variables within a class but outside any method. %hese variables are instantiated when the class is loaded. )nstance variables can be accessed from inside any method, constructor or bloc#s of that particular class. Class variables) Class variables are variables declared with in a class, outside any method, with the static #eyword.

A class can have any number of methods to access the value of various #inds of methods. )n the above e'ample, bar#ing(), hungry() and sleeping() are methods. 4elow mentioned are some of the important topics that need to be discussed when loo#ing into classes of the (ava 9anguage.

Constructors)
"hen discussing about classes, one of the most important sub topic would be constructors. Every class has a constructor. )f we do not e'plicitly write a constructor for a class the (ava compiler builds a default constructor for that class. Each time a new object is created, at least one constructor will be invo#ed. %he main rule of constructors is that they should have the same name as the class. A class can have more than one constructor. E'ample of a constructor is given below&
public class Euppy3 public Euppy()3 4 public Euppy("tring na'e)3 GG )his constructor has one para'eter% name. 4 4

(ava also supports 0ingleton Classes where you would be able to create only one instance of a class.

Creating an Object)
As mentioned previously, a class provides the blueprints for objects. 0o basically an object is created from a class. )n (ava, the new #ey word is used to create new objects.

%here are three steps when creating an object from a class&


Declaration) A variable declaration with a variable name with an object type. 3nstantiation) %he $new$ #ey word is used to create the object. 3nitiali%ation) %he $new$ #eyword is followed by a call to a constructor. %his call initiali.es the new object.

E'ample of creating an object is given below&


public class Euppy3 public Euppy("tring na'e)3 GG )his constructor has one para'eter% name. "yste'.out.println(+Eassed !a'e is <+ L na'e )1 4 public static void 'ain("tring 56args)3 GG Jollo ing state'ent ould create an object 'yEuppy Euppy 'yEuppy = ne Euppy( +to''y+ )1 4

)f we compile and run the above program, then it would produce the following result&
Eassed !a'e is <to''y

&ccessing 3nstance 9ariables and Methods)


)nstance variables and methods are accessed via created objects. %o access an instance variable the fully ualified path should be as follows&
GM Jirst create an object MG Object,eference = ne Constructor()1 GM !o call a variable as follo s MG Object,eference.variable!a'e1 GM !o you can call a class 'ethod as follo s MG Object,eference.2ethod!a'e()1

E"a ple)
%his e'ample e'plains how to access instance variables and methods of a class&
public class Euppy3 int puppy&ge1 public Euppy("tring na'e)3 GG )his constructor has one para'eter% name.

"yste'.out.println(+Eassed !a'e is <+ L na'e )1 4 public void set&ge( int age )3 puppy&ge = age1 4 public int get&ge( )3 "yste'.out.println(+Euppy/s age is <+ L puppy&ge )1 return puppy&ge1 4 public static void 'ain("tring 56args)3 GM Object creation MG Euppy 'yEuppy = ne Euppy( +to''y+ )1 GM Call class 'ethod to set puppy/s age MG 'yEuppy.set&ge( 0 )1 GM Call another class 'ethod to get puppy/s age MG 'yEuppy.get&ge( )1 GM :ou can access instance variable as follo s as ell MG "yste'.out.println(+Kariable Kalue <+ L 'yEuppy.puppy&ge )1 4 4

)f we compile and run the above program, then it would produce the following result&
Eassed !a'e is <to''y Euppy/s age is <0 Kariable Kalue <0

'ource file declaration rules)


As the last part of this section let$s now loo# into the source file declaration rules. %hese rules are essential when declaring classes, import statements and package statements in a source file.

%here can be only one public class per source file. A source file can have multiple non public classes. %he public class name should be the name of the source file as well which should be appended by .java at the end. +or e'ample & %he class name is . public class Employee{} %hen the source file should be as Employee.java. )f the class is defined inside a pac#age, then the pac#age statement should be the first statement in the source file. )f import statements are present then they must be written between the pac#age statement and the class declaration. )f there are no pac#age statements then the import statement should be the first line in the source file.

)mport and pac#age statements will imply to all the classes present in the source file. )t is not possible to declare different import and8or pac#age statements to different classes in the source file.

Classes have several access levels and there are different types of classes, abstract classes, final classes, etc. ) will be e'plaining about all these in the access modifiers chapter. Apart from the above mentioned types of classes, (ava also has some special classes called )nner classes and Anonymous classes.

Java +ac/age)
)n simple, it is a way of categori.ing the classes and interfaces. "hen developing applications in (ava, hundreds of classes and interfaces will be written, therefore categori.ing these classes is a must as well as ma#es life much easier.

3 port state ents)


)n (ava if a fully ualified name, which includes the pac#age and the class name, is given then the compiler can easily locate the source code or classes. )mport statement is a way of giving the proper location for the compiler to find that particular class. +or e'ample, the following line would as# compiler to load all the classes available in directory java@installation8java8io &
i'port java.io.M1

& 'i ple Case 'tudy)


+or our case study, we will be creating two classes. %hey are Employee and Employee%est. +irst open notepad and add the following code. !emember this is the Employee class and the class is a public class. /ow, save this source file with the name Employee.java. %he Employee class has four instance variables name, age, designation and salary. %he class has one e'plicitly defined constructor, which ta#es a parameter.
i'port java.io.M1 public class #'ployee3 "tring na'e1 int age1 "tring designation1 double salary1 GG )his is the constructor of the class #'ployee public #'ployee("tring na'e)3 this.na'e = na'e1

4 GG &ssign the age of the #'ployee to the variable age. public void e'p&ge(int e'p&ge)3 age = e'p&ge1 4 GM &ssign the designation to the variable designation.MG public void e'p;esignation("tring e'p;esig)3 designation = e'p;esig1 4 GM &ssign the salary to the variable salary.MG public void e'p"alary(double e'p"alary)3 salary = e'p"alary1 4 GM Erint the #'ployee details MG public void print#'ployee()3 "yste'.out.println(+!a'e<+L na'e )1 "yste'.out.println(+&ge<+ L age )1 "yste'.out.println(+;esignation<+ L designation )1 "yste'.out.println(+"alary<+ L salary)1 4 4

As mentioned previously in this tutorial, processing starts from the main method. %herefore inorder for us to run this Employee class there should be main method and objects should be created. "e will be creating a separate class for these tas#s. ;iven below is the EmployeeTest class, which creates two instances of the class Employee and invo#es the methods for each object to assign values for each variable. 0ave the following code in Employee%est.java file
i'port java.io.M1 public class #'ployee)est3 public static void 'ain("tring args56)3 GM Create t o objects using constructor MG #'ployee e'pOne = ne #'ployee(+@a'es "'ith+)1 #'ployee e'p) o = ne #'ployee(+2ary &nne+)1 GG (nvo.ing 'ethods for each object created e'pOne.e'p&ge(0B)1 e'pOne.e'p;esignation(+"enior "oft are #ngineer+)1 e'pOne.e'p"alary(7>>>)1 e'pOne.print#'ployee()1 e'p) e'p) e'p) e'p) o.e'p&ge(07)1 o.e'p;esignation(+"oft are #ngineer+)1 o.e'p"alary(?>>)1 o.print#'ployee()1

4 4

/ow, compile both the classes and then run EmployeeTest to see the result as follows&

C <H javac #'ployee.java C <H vi #'ployee)est.java C <H javac #'ployee)est.java C <H java #'ployee)est !a'e<@a'es "'ith &ge<0B ;esignation<"enior "oft are #ngineer "alary<7>>>.> !a'e<2ary &nne &ge<07 ;esignation<"oft are #ngineer "alary<?>>.>

You might also like