You are on page 1of 38

Basic Java interview questions

1. Why do you prefer Java?


Answer: write once ,run anywhere.
2. Name some of the classes which provide the functionality of collation?
Answer: collator, rulebased collator, collationkey, collationelement iterator.
3. Awt stands for? and what is it?
Answer: AWT stands for Abstract window tool kit. It is a is a package that provides an integrated
set of classes to manage user interface components.
. why a !ava pro"ram can not directly communicate with an #$B% driver?
Answer: Since !"# A$I is written in # language and makes use of pointers which %ava can not
support.
&. Are servlets platform independent? 'f so Why? Also what is the most common
application of servlets?
Answer: &es, "ecause they are written in %ava. The most common application of servlet is to
access database and dynamically construct 'TT$ response
(.What is a )ervlet?
Answer: Servlets are modules of %ava code that run in a server application (hence the name
)Servlets), similar to )Applets) on the client side* to answer client re+uests.
*.What advanta"es does %+#) have over ,,-.transitor transitor lo"ic/? .A-%A,0-/
Answer:
low power dissipation
pulls up to rail
easy to interface
1.2ow is Java unli3e %44? .As3ed 5y )un/
Some language features of #,, have been removed. String manipulations in %ava do not allow
for buffer overflows and other typical attacks. S-specific calls are not advised, but you can still
call native methods. .verything is a class in %ava. .verything is compiled to %ava bytecode, not
e/ecutable (although that is possible with compiler tools*.
6.What is 2,+- .2yperte7t +ar3up -an"ua"e/?
'T01 ('yperTe/t 0arkup 1anguage* is the set of )markup) symbols or tags inserted in a file
intended for display on a World Wide Web browser. The markup tells the Web browser how to
display a Web page2s words and images for the user.
18.$efine class.
Answer: A class describes a set of properties (primitives and ob3ects* and behaviors (methods*.
Advanced Java interview questions
1.'n Java9 what is the difference 5etween an 'nterface and an A5stract class?
A: An Abstract class declares have at least one instance method that is declared abstract which
will be implemented by the subclasses. An abstract class can have instance methods that
implement a default behavior. An Interface can only declare constants and instance methods, but
cannot implement default behavior.
2. %an you have virtual functions in Java? :es or No. 'f yes9 then what are virtual
functions?
A: &es, %ava class functions are virtual by default. 4irtual functions are functions of subclasses
that can be invoked from a reference to their superclass. In other words, the functions of the
actual ob3ect are called when a function is invoked on the reference to that ob3ect.
3.Write a function to reverse a lin3ed list p in %44?
A:
1ink5 reverse6list(1ink5 p*
7
if (p 88 9:11*
return 9:11;
1ink5 h 8 p;
p 8 p-<ne/t;
h-<ne/t 8 9:11;
while (p =8 null*
7
1ink5 t 8 p-<ne/t;
p-<ne/t 8 h;
h 8 p;
p 8 t;
>
return h;
>
.'n %449 what is the usefulness of ;irtual destructors?
A:4irtual destructors are neccessary to reclaim memory that were allocated for ob3ects in the
class hierarchy. If a pointer to a base class ob3ect is deleted, then the compiler guarantees the
various subclass destructors are called in reverse order of the ob3ect construction chain.
&.What are mute7 and semaphore? What is the difference 5etween them?
A:A mute/ is a synchroni?ation ob3ect that allows only one process or thread to access a critical
code block. A semaphore on the other hand allows one or more processes or threads to access a
critial code block. A semaphore is a multiple mute/.
Advanced enterprise Java interview questions
1/ What is the purpose of "ar5a"e collection in Java9 and when is it used?
The purpose of garbage collection is to identify and discard ob3ects that are no longer needed by
a program so that their resources can be reclaimed and reused. A %ava ob3ect is sub3ect to
garbage collection when it becomes unreachable to the program in which it is used.
2/ $escri5e synchroni<ation in respect to multithreadin".
With respect to multithreading, synchroni?ation is the capability to control the access of multiple
threads to shared resources. Without synchoni?ation, it is possible for one thread to modify a
shared variable while another thread is in the process of using or updating same shared variable.
This usually leads to significant errors.
3/ 2ow is JavaBeans differ from 0nterprise JavaBeans?
The %ava"eans architecture is meant to provide a format for general-purpose components. n
the other hand, the .nterprise %ava"eans architecture provides a format for highly speciali?ed
business logic components.
/ 'n what ways do desi"n patterns help 5uild 5etter software?
!esign patterns helps software developers to reuse successful designs and architectures. It helps
them to choose design alternatives that make a system reusuable and avoid alternatives that
compromise reusability through proven techni+ues as design patterns.
&/ $escri5e 3=,ier Architecture in enterprise application development.
In @-tier architecture, an application is broken up into @ separate logical layers, each with a well-
defined set of interfaces. The presentation layer typically consists of a graphical user interfaces.
The business layer consists of the application or business logic, and the data layer contains the
data that is needed for the application.
J)> interview questions
1. What are the most common techniques for reusin" functionality in o5!ect=oriented
systems?
A: The two most common techni+ues for reusing functionality in ob3ect-oriented systems are class
inheritance and ob3ect composition.
#lass inheritance lets you define the implementation of one class in terms of another2s. Aeuse by
subclassing is often referred to as white-bo/ reuse.
b3ect composition is an alternative to class inheritance. 'ere, new functionality is obtained by
assembling or composing ob3ects to get more comple/ functionality. This is known as black-bo/
reuse.
2. Why would you want to have more than one catch 5loc3 associated with a sin"le try
5loc3 in Java?
A: Since there are many things can go wrong to a single e/ecuted statement, we should have
more than one catch(s* to catch any errors that might occur.
3. What lan"ua"e is used 5y a relational model to descri5e the structure of a data5ase?
A: The !ata !efinition 1anguage.
. What is J)>? $escri5e its concept.
A: %S$ is %ava Server $ages. The %avaServer $age concept is to provide an 'T01 document
with the ability to plug in content at selected locations in the document. (This content is then
supplied by the Web server along with the rest of the 'T01 document at the time the document is
downloaded*.
&. What does the J)> en"ine do when presented with a Java)erver >a"e to process?
A: The %S$ engine builds a servlet. The 'T01 portions of the %avaServer $age become Strings
transmitted to print methods of a $rintWriter ob3ect. The %S$ tag portions result in calls to
methods of the appropriate %ava"ean class whose output is translated into more calls to a println
method to place the result in the 'T01 document.
Java software en"ineerin" interview questions
1. What is the three tier model?
Answer: It is the presentation, logic, backend
2. Why do we have inde7 ta5le in the data5ase?
Answer: "ecause the inde/ table contain the information of the other tables. It will
be faster if we access the inde/ table to find out what the other contain.
3. ?ive an e7ample of usin" J$B% access the data5ase.
Answer:
try
7
#lass.for9ame()register the driver)*;
#onnection con 8 !river0anager.get#onnection()url of db), )username),)password)*;
Statement state 8 con.createStatement(*;
state.e/ecute:pdate()create table testing(firstname varchar(BC*, lastname varchar(BC**)*;
state.e/ecuteDuery()insert into testing values(EphuE,FhuynhE*)*;
state.close(*;
con.close(*;
>
catch(./ception e*
7
System.out.println(e*;
>
. What is the different of an Applet and a Java Application
Answer: The applet doesnEt have the main function
&. 2ow do we pass a reference parameter to a function in Java?
Answer: .ven though %ava doesnEt accept reference parameter, but we can
pass in the ob3ect for the parameter of the function.
Gor e/ample in #,,, we can do this:
void change4alue(intH a*
7
a,,;
>
void main(*
7
int b8B;
change4alue(b*;
>
however in %ava, we cannot do the same thing. So we can pass the
the int value into Integer ob3ect, and we pass this ob3ect into the
the function. And this function will change the ob3ect.
Java applet interview questions
1. What is an Applet? )hould applets have constructors?
- Applets are small programs transferred through Internet, automatically installed and run
as part of web-browser. Applets implements functionality of a client. Applet is a dynamic
and interactive program that runs inside a Web page displayed by a %ava-capable
browser. We don2t have the concept of #onstructors in Applets. Applets can be invoked
either through browser or through Appletviewer utility provided by %!I.
2. What are the Applet@s -ife %ycle methods? 07plain them? - Gollowing are methods in
the life cycle of an Applet:
o init(* method - called when an applet is first loaded. This method is called only
once in the entire cycle of an applet. This method usually intiali?e the variables to
be used in the applet.
o start( * method - called each time an applet is started.
o paint(* method - called when the applet is minimi?ed or refreshed. This method is
used for drawing different strings, figures, and images on the applet window.
o stop( * method - called when the browser moves off the applet2s page.
o destroy( * method - called when the browser is finished with the applet.
3. What is the sequence for callin" the methods 5y AW, for applets? - When an applet
begins, the AWT calls the following methods, in this se+uence:
o init(*
o start(*
o paint(*
When an applet is terminated, the following se+uence of method calls takes place :
o stop(*
o destroy(*
4. 2ow do Applets differ from Applications? - Gollowing are the main differences:
Application: Stand Alone, doesn2t need
web-browser. Applet: 9eeds no e/plicit installation on local machine. #an be transferred
through Internet on to the local machine and may run as part of web-browser.
Application: ./ecution starts with main(* method. !oesn2t work if main is not there.
Applet: ./ecution starts with init(* method. Application: 0ay or may not be a J:I.
Applet: 0ust run within a J:I (:sing AWT*. This is essential feature of applets.
5. %an we pass parameters to an applet from 2,+- pa"e to an applet? 2ow? - We can
pass parameters to an applet using Kparam< tag in the following way:
o Kparam name8LparamMN value8LvalueMN<
o Kparam name8LparamBN value8LvalueBN<
Access those parameters inside the applet is done by calling get$arameter(* method
inside the applet. 9ote that get$arameter(* method returns String value corresponding to
the parameter name.
6. 2ow do we read num5er information from my applet@s parameters9 "iven that
Applet@s "et>arameter./ method returns a strin"?
- :se the parseInt(* method in the Integer #lass, the Gloat(String* constructor or
parseGloat(* method in the #lass Gloat, or the
!ouble(String* constructor or parse!oulbl(* method in the class !ouble.
7. 2ow can ' arran"e for different applets on a we5 pa"e to communicate with each
other?
- 9ame your applets inside the Applet tag and invoke Applet#onte/t2s getApplet(* method
in your applet code to obtain references to the
other applets on the page.
8. 2ow do ' select a AB- from my Applet and send the 5rowser to that pa"e? - Ask the
applet for its applet conte/t and invoke show!ocument(* on that conte/t ob3ect.
O. :A1 target:A1;
MC. String :A1String
MM. Applet#onte/t conte/t 8 getApplet#onte/t(*;
MB. try
M@. 7
MP. target:A1 8 new :A1(:A1String*;
MQ. >
MR. catch (0alformed:A1./ception e*
MS. 7
MT. UU #ode for recover from the e/ception
MO. >
BC. conte/t. show!ocument (target:A1*;
21. %an applets on different pa"es communicate with each other?
- 9o, 9ot !irectly. The applets will e/change the information at one meeting place either
on the local file system or at remote system.
22. 2ow do ' determine the width and hei"ht of my application?
- :se the getSi?e(* method, which the Applet class inherits from the #omponent class in
the %ava.awt package. The getSi?e(* method returns the si?e of the applet as a
!imension ob3ect, from which you e/tract separate width, height fields. The following
code snippet e/plains this:
B@. !imension dim 8 getSi?e(*;
BP. int appletwidth 8 dim.width(*;
BQ. int appletheight 8 dim.height(*;
26. Which classes and interfaces does Applet class consist? - Applet class consists of a
single class, the Applet class and three interfaces: Applet#onte/t, AppletStub, and
Audio#lip.
27. What is Applet)tu5 'nterface?
- The applet stub interface provides the means by which an applet and the browser
communicate. &our code will not typically implement this interface.
28. What ta"s are mandatory when creatin" 2,+- to display an applet?
1. name, height, width
2. code, name
3. codebase, height, width
4. code, height, width
#orrect answer is d.
2. What are the Applet@s information methods?
- The following are the Applet2s information methods: getAppletInfo(* method: Aeturns a
string describing the applet, its author, copyright information, etc. get$arameterInfo( *
method: Aeturns an array of string describing the applet2s parameters.
3. What are the steps involved in Applet development? - Gollowing are the steps
involved in Applet development:
o #reateU.dit a %ava source file. This file must contain a class which e/tends
Applet class.
o #ompile your program using 3avac
o ./ecute the appletviewer, specifying the name of your applet2s source file or html
file. In case the applet information is stored in html file then Applet can be
invoked using 3ava enabled web browser.
29. Which method is used to output a strin" to an applet? Which function is this
method included in? - drawString( * method is used to output a string to an applet. This
method is included in the paint method of the Applet.
Java interview questions
1. What is the %ollections A>'? - The #ollections A$I is a set of classes and interfaces
that support operations on collections of ob3ects
2. What is the -ist interface? - The 1ist interface provides support for ordered collections
of ob3ects.
3. What is the ;ector class? - The 4ector class provides the capability to implement a
growable array of ob3ects
4. What is an 'terator interface? - The Iterator interface is used to step through the
elements of a #ollection
5. Which !ava.util classes and interfaces support event handlin"? - The .ventb3ect
class and the .vent1istener interface support event processing
6. What is the ?re"orian%alendar class? - The Jregorian#alendar provides support for
traditional Western calendars
7. What is the -ocale class? - The 1ocale class is used to tailor program output to the
conventions of a particular geographic, political, or cultural region
8. What is the )imple,imeCone class? - The SimpleTimeVone class provides support for
a Jregorian calendar
9. What is the +ap interface? - The 0ap interface replaces the %!I M.M !ictionary class
and is used associate keys with values
10. What is the hi"hest=level event class of the event=dele"ation model? - The
3ava.util..ventb3ect class is the highest-level class in the event-delegation class
hierarchy
11. What is the %ollection interface? - The #ollection interface provides support for the
implementation of a mathematical bag - an unordered collection of ob3ects that may
contain duplicates
12. What is the )et interface? - The Set interface provides methods for accessing the
elements of a finite mathematical set. Sets do not allow duplicate elements
13. What is the purpose of the ena5le0vents./ method? - The enable.vents(* method is
used to enable an event for a particular ob3ect. 9ormally, an event is enabled when a
listener is added to an ob3ect for a particular event. The enable.vents(* method is used
by ob3ects that handle events by overriding their event-dispatch methods.
14. What is the BesourceBundle class? - The Aesource"undle class is used to store
locale-specific resources that can be loaded by a program to tailor the program2s
appearance to the particular locale in which it is being run.
15. What is the difference 5etween yieldin" and sleepin"? - When a task invokes its
yield(* method, it returns to the ready state. When a task invokes its sleep(* method, it
returns to the waiting state.
16. When a thread 5loc3s on 'D#9 what state does it enter? - A thread enters the waiting
state when it blocks on IU.
17. When a thread is created and started9 what is its initial state? - A thread is in the
ready state after it has been created and started.
18. What invo3es a thread@s run./ method? - After a thread is started, via its start(* method
or that of the Thread class, the %40 invokes the thread2s run(* method when the thread is
initially e/ecuted.
19. What method is invo3ed to cause an o5!ect to 5e"in e7ecutin" as a separate
thread? - The start(* method of the Thread class is invoked to cause an ob3ect to begin
e/ecuting as a separate thread.
20. What is the purpose of the wait./9 notify./9 and notifyAll./ methods? - The
wait(*,notify(*, and notifyAll(* methods are used to provide an efficient way for threads to
wait for a shared resource. When a thread e/ecutes an ob3ect2s wait(* method, it enters
the waiting state. It only enters the ready state after another thread invokes the ob3ect2s
notify(* or notifyAll(* methods.
21. What are the hi"h=level thread states? - The high-level thread states are ready,
running, waiting, and dead
22. What happens when a thread cannot acquire a loc3 on an o5!ect? - If a thread
attempts to e/ecute a synchroni?ed method or synchroni?ed statement and is unable to
ac+uire an ob3ect2s lock, it enters the waiting state until the lock becomes available.
23. 2ow does multithreadin" ta3e place on a computer with a sin"le %>A? - The
operating system2s task scheduler allocates e/ecution time to multiple tasks. "y +uickly
switching between e/ecuting tasks, it creates the impression that tasks e/ecute
se+uentially.
24. What happens when you invo3e a thread@s interrupt method while it is sleepin" or
waitin"? - When a task2s interrupt(* method is e/ecuted, the task enters the ready state.
The ne/t time the task enters the running state, an Interrupted./ception is thrown.
25. What state is a thread in when it is e7ecutin"? - An e/ecuting thread is in the running
state
26. What are three ways in which a thread can enter the waitin" state? - A thread can
enter the waiting state by invoking its sleep(* method, by blocking on IU, by
unsuccessfully attempting to ac+uire an ob3ect2s lock, or by invoking an ob3ect2s wait(*
method. It can also enter the waiting state by invoking its (deprecated* suspend(*
method.
27. What method must 5e implemented 5y all threads? - All tasks must implement the
run(* method, whether they are a subclass of Thread or implement the Aunnable
interface.
28. What are the two 5asic ways in which classes that can 5e run as threads may 5e
defined? - A thread class may be declared as a subclass of Thread, or it may implement
the Aunnable interface.
29. 2ow can you store international D Anicode characters into a coo3ie? - ne way is,
before storing the cookie :A1.ncode it. :A1.nocder.encoder(str*; And use
:A1!ecoder.decode(str* when you get the stored cookie.
J$B% and J)> interview questions
1. What is the query used to display all ta5les names in )E- )erver .Euery analy<er/?
select 5 from information6schema.tables
2. 2ow many types of J$B% $rivers are present and what are they?- There are P types
of %!"# !rivers
o %!"#-!"# "ridge !river
o 9ative A$I $artly %ava !river
o 9etwork protocol !river
o %!"# 9et pure %ava !river
3. %an we implement an interface in a J)>?- 9o
4. What is the difference 5etween )ervlet%onte7t and >a"e%onte7t?- Servlet#onte/t:
Jives the information about the container. $age#onte/t: Jives the information about the
Ae+uest
5. What is the difference in usin" request."etBequest$ispatcher./ and
conte7t."etBequest$ispatcher./?- re+uest.getAe+uest!ispatcher(path*: In order to
create it we need to give the relative path of the resource,
conte/t.getAe+uest!ispatcher(path*: In order to create it we need to give the a5solute
path of the resource.
6. 2ow to pass information from J)> to included J)>?- :sing KW3sp:param< tag.
7. What is the difference 5etween directive include and !sp include?- KWX include<:
:sed to include static resources during translation time. %S$ include: :sed to include
dynamic content or static content during runtime.
8. What is the difference 5etween Bequest$ispatcher and sendBedirect?-
Ae+uest!ispatcher: server-side redirect with re+uest and response ob3ects. sendAedirect
: #lient-side redirect with new re+uest and response ob3ects.
9. 2ow does J)> handle runtime e7ceptions?- :sing error$age attribute of page
directive and also we need to specify is.rror$age8true if the current page is intended to
:A1 redirecting of a %S$.
10. 2ow do you delete a %oo3ie within a J)>?
#ookie mycook 8 new #ookie(Y)nameY),Y)valueY)*;
response.add#ookie(mycook*;
#ookie killmycook 8 new #ookie(Y)mycookY),Y)valueY)*;
killmycook.set0a/Age(C*;
killmycook.set$ath(Y)UY)*;
killmycook.add#ookie(killmycook*;
11. 2ow do ' mi7 J)> and ))' Finclude?- If you2re 3ust including raw 'T01, use the
Zinclude directive as usual inside your .3sp file.
K=--Zinclude file8)data.inc)--<
"ut it2s a little trickier if you want the server to evaluate any %S$ code that2s inside the
included file. If your data.inc file contains 3sp code you will have to use
KWX vinclude8)data.inc) W<
The K=[Zinclude file8)data.inc)[< is used for including non-%S$ files.
12. ' made my class %lonea5le 5ut ' still "et Cant access protected method clone.
Why?- Some of the %ava books imply that all you have to do in order to have your class
support clone(* is implement the #loneable interface. 9ot so. $erhaps that was the intent
at some point, but that2s not the way it works currently. As it stands, you have to
implement your own public clone(* method, even if it doesn2t do anything special and 3ust
calls super.clone(*.
13. Why is G+- such an important development?- It removes two constraints which were
holding back Web developments: dependence on a single, infle/ible document type
('T01* which was being much abused for tasks it was never designed for; the
comple/ity of full SJ01, whose synta/ allows many powerful but hard-to-program
options. \01 allows the fle/ible development of user-defined document types. It provides
a robust, non-proprietary, persistent, and verifiable file format for the storage and
transmission of te/t and data both on and off the Web; and it removes the more comple/
options of SJ01, making it easier to program for.
14. What is the fastest type of J$B% driver?- %!"# driver performance will depend on a
number of issues:
o the +uality of the driver code,
o the si?e of the driver code,
o the database server and its load,
o network topology,
o the number of times your re+uest is translated to a different A$I.
In general, all things being e+ual, you can assume that the more your re+uest and
response change hands, the slower it will be. This means that Type M and Type @ drivers
will be slower than Type B drivers (the database calls are make at least three translations
versus two*, and Type P drivers are the fastest (only one translation*.
15. 2ow do ' find whether a parameter e7ists in the request o5!ect?
boolean hasGoo 8 =(re+uest.get$arameter(Y)fooY)* 88 null
]] re+uest.get$arameter(Y)fooY)*.e+uals(Y)Y)**;
or
boolean has$arameter 8
re+uest.get$arameter0ap(*.contains(the$arameter*; UU(which works in Servlet B.@,*
16. 2ow can ' send user authentication information while ma3in"AB-%onnection?-
&ou2ll want to use 'ttp:A1#onnection.setAe+uest$roperty and set all the appropriate
headers to 'TT$ authori?ation.
Java 'nterview Euestions
1.Are the imports chec3ed for validity at compile time? e.". will the code containin" an
import such as !ava.lan".AB%$ compile?
&es the imports are checked for the semantic validity at compile time. The code containing above
line of import will not compile. It will throw an error saying,can not resolve symbol
symbol : class A"#!
location: package io
import 3ava.io.A"#!;
2.$oes importin" a pac3a"e imports the su5pac3a"es as well? e.". $oes importin"
com.+y,est.H also import com.+y,est.Anit,ests.H?
9o you will have to import the subpackages e/plicitly. Importing com.0yTest.5 will import classes
in the package 0yTest only. It will not import any class in any of itFs subpackage.
3.What is the difference 5etween declarin" a varia5le and definin" a varia5le?
In declaration we 3ust mention the type of the variable and itFs name. We do not initiali?e it. "ut
defining means declaration , initiali?ation.
e.g String s; is 3ust a declaration while String s 8 new String ()abcd)*; r String s 8 )abcd); are
both definitions.
.What is the default value of an o5!ect reference declared as an instance varia5le?
null unless we define it e/plicitly.
&.%an a top level class 5e private or protected?
9o. A top level class can not be private or protected. It can have either )public) or no modifier. If it
does not have a modifier it is supposed to have a default access.If a top level class is declared as
private the compiler will complain that the )modifier private is not allowed here). This means that a
top level class can not be private. Same is the case with protected.
(.What type of parameter passin" does Java support?
In %ava the arguments are always passed by value .
*.>rimitive data types are passed 5y reference or pass 5y value?
$rimitive data types are passed by value.
1.#5!ects are passed 5y value or 5y reference?
%ava only supports pass by value. With ob3ects, the ob3ect reference itself is passed by value and
so both the original reference and parameter copy both refer to the same ob3ect .
6.What is seriali<ation?
Seriali?ation is a mechanism by which you can save the state of an ob3ect by converting it to a
byte stream.
18.2ow do ' seriali<e an o5!ect to a file?
The class whose instances are to be seriali?ed should implement an interface Seriali?able. Then
you pass the instance to the b3ectutputStream which is connected to a fileoutputstream. This
will save the ob3ect to a file.
11.Which methods of )eriali<a5le interface should ' implement?
The seriali?able interface is an empty interface, it does not contain any methods. So we do not
implement any methods.
12.2ow can ' customi<e the serali<ation process? i.e. how can one have a control over the
seriali<ation process?
&es it is possible to have control over seriali?ation process. The class should implement
./ternali?able interface. This interface contains two methods namely read./ternal and
write./ternal. &ou should implement these methods and write the logic for customi?ing the
seriali?ation process.
13.What is the common usa"e of seriali<ation?
Whenever an ob3ect is to be sent over the network, ob3ects need to be seriali?ed. 0oreover if the
state of an ob3ect is to be saved, ob3ects need to be serila?ed.
1.What is 07ternali<a5le interface?
./ternali?able is an interface which contains two methods read./ternal and write./ternal. These
methods give you a control over the seriali?ation mechanism. Thus if your class implements this
interface, you can customi?e the seriali?ation process by implementing these methods.
1&.What happens to the o5!ect references included in the o5!ect?
The seriali?ation mechanism generates an ob3ect graph for seriali?ation. Thus it determines
whether the included ob3ect references are seriali?able or not. This is a recursive process. Thus
when an ob3ect is seriali?ed, all the included ob3ects are also seriali?ed alongwith the original
obect.
1(.What one should ta3e care of while seriali<in" the o5!ect?
ne should make sure that all the included ob3ects are also seriali?able. If any of the ob3ects is
not seriali?able then it throws a 9otSeriali?able./ception.
1*.What happens to the static fields of a class durin" seriali<ation? Are these fields
seriali<ed as a part of each seriali<ed o5!ect?
&es the static fields do get seriali?ed. If the static field is an ob3ect then it must have implemented
Seriali?able interface. The static fields are seriali?ed as a part of every ob3ect. "ut the
commonness of the static fields across all the instances is maintained even after seriali?ation.
Java >ac3a"es I %onstructors
1. 2ow to start to define my own pac3a"es? Any su""estions?
A: Suggestions:
!onFt put your own stuff under 3dk. #reate a directory such as c:Umyworkarea or c:Uliu/ia
#reate a stem directory, such as comUmyco or orgUmyorg under your c:Umyworkarea
9o %ava files should be put in your stem directory, only packages
All your code will start with a package statement, and put them under the corresponding
directories. ./amples: package com.myco.somepkg;
package com.myco.somepkg.somesubpkg;
That will be a good start.
2.If I define a class in com.myco package as com/myco/MyClass.java,
How do I compile and rn it!
In your c:Umyworkarea directory:
3avac comUmycoU0y#lass.3ava
3ava com.myco.0y#lass
'owever, this is 3ust to get you started. The better practice is using ant. Start to learn Ant now
3. 2ow to create my own pac3a"e9 how to call my class in another pac3a"e?
A: 'ere is a runnable e/ample with detailed e/planation for you to play and practice.
$ackage :sage
. What are the rules and convention a5out pac3a"e name? Why ' "ot an error when ' used
W0B='NJ as my pac3a"e name?
A:package name in %ava is an identifier, therefore it has to +ualify as an identifier first. Aead %1S
for rules of %ava identifiers %1S @.T Identifiers To my limited knowledge of computer
programming languages, I do not know any programming language which allows dash F-F as part
of an identifier. 9ot in any of the followings: $ascal, c, c,,, Gortran, cZ, Ada, 4", 1isp, %ava, 01,
perl, ... It might be allowed in #"1, but IFm not sure, since #"1 is a very loose language. I
do not know #"1. Any #"1 e/pert hereE 'elp, please= The first problem for W."-I9G as a
package name is dash F-F, of course. The second problem is W."-I9G in tomcat or %ava web
component develop environment has special meaning, you cannot use it for anything else.In all of
above, we are not talking about convention, but the rules. Aead %ava coding convention here:
#ode #onventions for the %avaT0 $rogramming 1anguage What are the differencesE
If you violate the convention only, your code should still compilableUrunnableUworkable, but not
very good. Another thing you need to remember is that conventions are very sub3ective. A good
convention in I"0 shop might be considered bad in 0icrosoft or .!S.
Java %onstructors
&. 2ow to use super and this Java 3eywords?
A:
super(*;
this(*;
With or without parameters, only one of these is allowed as the first line in your constructor,
nowhere else= 'owever,
super.methodM(*;
this.fieldP;
do not have the above restrictions in your code.
(. 2ow does the Java default constructor 5e provided? 's it the same as %44?
A: If a class defined by the code does not have any constructor, compiler will automatically
provide one no-parameter-constructor (default-constructor* for the class in the byte code. The
access modifier (publicUprivateUetc.* of the default constructor is the same as the class itself.
Attention to former %44 pro"rammersK It is very important to previous #,, programmers to
know the differences between #,, and %ava. #,, compiler will provide a no-parameter-
constructor (defult-constructor* as long as you did not define one. %ava only provide a no-
parameter-constructor when your class does not have any construcor.%an you let me see it?
h, yes, in where your class file is, type
3avap -private &our#lass9ame
&our #,, programmer will be real happy to see the output very similar to a &our#lass9ame.h f
course, 3BsdkUbin or 3reUbin directory must on your path.
*. Why does my followin" code not compila5le?
class "ase7
public int i 8 C;
public "ase(String te/t*7
i 8 M;
>
>
public class Sub e/tends "ase7
public Sub(String te/t*7
i 8 B;
>
public static void main(String args^_*7
Sub sub 8 new Sub()'ello)*;
System.out.println(sub.i*;
>
>
UU #ompile error:
UU Sub.3ava:T: cannot resolve symbol
UU symbol : constructor "ase (*
A:
"ecause you did not e/plicitly call super(String* in Sub contructor, a default super(* is added.
'owever, the super class of Sub does not have a "ase(* constructor. .AAA= 2ow to solve the
pro5lem? Two choices:
1. ./plicitly call super(String* in Sub constructor
B. Add a no-param-constructor for "ase(*
See the following detailed commented code, uncomment either one will work
class "ase7
public int i 8 C;
U5 ----------------- choice ZB
public "ase(* 7
UU do whatever
>
5U
public "ase(String te/t*7
i 8 M;
>
>
public class Sub e/tends "ase7
public Sub(String te/t*7

UU super(te/t*; UU-- choice ZM

UU problems here===
UU since if you donFt, then a default
UU super(*; UUis generated by compiler

i 8 B;
>
public static void main(String args^_*7
Sub sub 8 new Sub()'ello)*;
System.out.println(sub.i*;
>
>
1. %an ' specify void as the return type of constructor? 't compiles.
A: 9o, you cannot=
'owever, why it compilesE &es, it you code it tricky enough, it will compile without any error
message=SurprisedE $rovedE 'a, ha, Aoseanne is wrongE= Wait a minute, hmmm... it is not a
constructor any more= It is 3ust a method happen to have the same name as the class name Try
the following code= $lease= It will be a very very interesting e/perience and lots of fun too=
public class A 7
UU this is a constructor of class A
public A(int i* 7
System.out.println()We are in contructor: A(int i*)*;
System.out.println()The i value is ) , i*;
>
UU this is a method A
void A(* 7
System.out.println()We are in method: void A(*)*;
>
public static void main(String^_ args* 7
UU They are fine here=
A aM 8 new A(@*;
aM.A(*;

UU #ompile time error
UU cannot resolve symbol constructor A(*
UU A aB 8 new A(*;
>
>
UU output
UU We are in contructor: A(int i*
UU The i value is @
UU We are in method: void A(*
)eriali<ation
1.What class can 5e seriali<ed? What cannot?
A: Almost all %!I classes are seriali?able e/cept
#lasses with only static andUor transient fields. Gor e/ample, 0ath, Arrays, etc.
#lasses representing specifics of a virtual machine. Gor e/ample, Thread, $rocess,
Auntime, almost all classes in the 3ava.io and many classes in 3ava.net packages are not
seriali?able
'D# )treams9 BeaderDWriter
2. %reatin" a Jile o5!ect does not mean creation of any file or directory9 and then when
does the creation of physical file ta3e place?
A: The answer is it depends...
The physical file might be created MC years ago by one of your long gone colleagues , or will be
created on the ne/t step of running when your program tries to write something onto the not-yet-
e/ist file by using GileutputStream or GileWriter.
&ou can also call create9ewGile(* of the 3ava.io.Gile ob3ect to create a new, empty file named by
its abstract pathname if and only if a file with this name does not yet e/ist.
The file might never be created since the program does not have write permission (of
3ava.io.Gile$ermission* in that specified directory.
The file might never be created simply because the program never try to do anything on it,
absentminded programmer, of course.
The 3ava.io.Gile ob3ect might 3ust represent a directory, which might not be a file at all.
Aead The %ava Tutorial It is free. Aead 3avadoc, and compare the e/ception thrown by Gile and
GileWriter constructors will help as well.
3. 's it possi5le to chan"e directory 5y usin" Jile o5!ect?
A: 9o, &ou cannot change the directory by using a file ob3ect.
Instances of the Gile class are immutable; that is, once created, the abstract pathname
represented by a Gile ob3ect will never change.
'owever, you can use one Gile ob3ect to find the directory you want, and then create another Gile
ob3ect for the directory you want to go to.
. 2ow to create a new directory 5y usin" Jile o5!ect?
A: :sing class Gile method mkdir(* or mkdirs(*. See code here:
UU 0ake!ir.3ava
import 3ava.io.5;
public class 0ake!ir 7
public static void main(String args^_*7
UU make sure sub-directory )mmm) does not e/ist
Gile dir8new Gile()mmm)*;
System.out.println(dir.mkdir(**;UU true


UU make sure at least two of )hhhYYlllYYnnn) does not e/ist
Gile multidir8new Gile()hhhYYlllYYnnn)*;
System.out.println(multidir.mkdir(**; UU false
System.out.println(multidir.mkdirs(**; UU true

UU make sure at least two of )..YYcccYYdddYYeee) does not e/ist
Gile updir8new Gile()..YYcccYYdddYYeee)*;
System.out.println(updir.mkdir(**; UU false
System.out.println(updir.mkdirs(**; UU true

UU If you run the code second time,
UU the result will be different. WhyE
>
>
&. What are the differences 5etween Jile'nput)treamDJile#utput)tream and
BandomAccessJile? $o you have a "ood e7ample on it?
A: Aemember never mi/ing AandomAccessGile with Streams=== AandomAccessGile class is more
or less a legacy from c language, the Stream conceptsU#,, were not invented then.
This e/ample deals with Gile, GileInputStream, !atautputStream, AandomAccessGile. $lay with
it; try to understand every bit of the output. ITest.3ava
(. What are the difference 5etween Jile."etA5solute>ath./ and Jile."et%anonical>ath./?
%an they return different result?
A: Gind your answer by reading this:
http:UU3ava.sun.comU3BseUM.@UdocsUapiU3avaUioUGile.html
&es, they can return different results= See the following e/ample. $ay attention to the comments.
import 3ava.io.5;
public class T
7
static void test$ath(*7
Gile fM 8 new Gile()UhomeU3cU..Ur?Ur?.?ip)*; UU file does not e/ist
Gile fB 8 new Gile()T.class)*; UU file in r? dir under UhomeUr?hang
UU no tryUcatch block needed
UU return )UhomeU3cU..Ur?Ur?.?ip) always
System.out.println()Absolute path for fM: ) , fM.getAbsolute$ath(**;
UU return )UhomeUr?hangUr?UT.class)
System.out.println()Absolute path for fB: ) , fB.getAbsolute$ath(**;
try 7
UU not compilable if neither tryUcatch block nor throws present
UU return )UhomeUr?Ur?.?ip)
System.out.println()#anonical path for fM: ) , fM.get#anonical$ath(**;
UU return )UhomeUr?hangUr?UT.class)
System.out.println()#anonical path for fB: ) , fB.get#anonical$ath(**;
>
catch (I./ception ioe*
7
ioe.printStackTrace(*;
>
>
public static void main(String^_ args*7
T.test$ath(*;
>
>
*. Which one of the followin" will create an 'nput)treamBeader correctly?
1. new InputStreamAeader(new GileInputStream()data)**;
2. new InputStreamAeader(new GileAeader()data)**;
3. new InputStreamAeader(new "ufferedAeader()data)**;
4. new InputStreamAeader()data)*;
Q. new InputStreamAeader(System.in*;
A:
The leagal constructors for InputStreamAeader are
InputStreamAeader(InputStream in*
InputStreamAeader(InputStream in, String enc*
M. If you compile this line without a tryUcatch block, you will get a compile error: ./ception
3ava.io.Gile9otGound./ception must be caught, or it must be declared in the throws
clause of this method.
'ow to do it correctlyE
B. try 7
@. new InputStreamAeader(new GileInputStream()data)**;
P. >
Q. catch (3ava.io.Gile9otGound./ception fnfe* 7
R. >
Answer: If they let you choose one, choose e. If they let you choose two, choose a and e.
7. .rror ZM: GileAeader is not an InputStream.
.rror ZB: The same problems as a*, ./ception 3ava.io.Gile9otGound./ception must be
caught
8. .rror ZM: "ufferedAeader is not an InputStream. .rror ZB: There is no contructor of
"ufferedAeader to take string as argument.
9. String )data) is not an InputStream.
10. %orrect, since System.in is an InputStream.
1. Why only read./ methods in ByteArray'nput)tream does not throw '#07ception?
A: &ou are right, read(* methods of all other InputStreams throw I./ception e/cept
"yteArrayInputStream.
This is because the entire byte array is in memory; there is no circumstance in which an
I./ception is possible.
'owever, close(* and reset(* methods of "yteArrayInputStream still can throw I./ception.
6. 2ow does 'nput)tream.read./ method wor3? %an you "ive me some sample code?
A:'ere is the sample code; the e/planation is in the comments. 0ake sure you compile it, run it,
and try to understand it.
UU TestAead.3ava
import 3ava.io.5;
public class TestAead 7
public static void main(String argv^_* 7
try 7
byte^_ bary 8 new byte^_7-M, C, MB, B@, QR, OT, B@, MBS, -MBT>;
"yteArrayInputStream bais 8 new "yteArrayInputStream(bary*;
System.out.print()7 )*;
while (test(bais**7
System.out.print(), )*;
>
System.out.println() >)*;
UU output: 7 BQQ, C, MB, B@, QR, OT, B@, MBS, MBT, -M >
UU 9otice B negative byte value becomes positive
UU -M is added to the end to signal .G.
>
catch (I./ception e* 7
System.out.println(e*;
>
>
public static boolean test(InputStream is* throws I./ception 7
UU Aead one byte at a time and
UU put it at the lower order byte of an int
UU That is why the int value will be always positive
UU unless .G, which will be -M
int value 8 is.read(*;
System.out.print(value*;

UU return true as long as value is not -M
return value 88 (value H C/ff*;
>
>
18. 2ow to read data from soc3et? What is the correct selection for the question?
A socket ob3ect (s* has been created and connected to a standard Internet service
on a remote network server.
Which of the following gives suitable means for reading AS#II data,
one line at a time from the socketE
A. s.getInputStream(*;
". new !ataInputStream(s.getInputStream(**;
#. new "yteArrayInputStream(s.getInputStream(**;
!. new "ufferedAeader(new InputStreamAeader(s.getInputStream(***;
.. new "ufferedAeader(new InputStreamAeader(s.getInputStream(**,)TTQO-M)*;
A:
A. InputStream does not read1ine(*
". !ataInputStream.rea1ine(* deprecated
#. "yteArrayInputStream does not read1ine(*
!. the only correct answer.
.. encoding put in the wrong place. The correct way is
new "ufferedAeader(new InputStreamAeader(s.getInputStream(*, )TTQO-M)**;
See sample from the Sun: Aeading from and Writing to a Socket
11.2ow to use #5!ect#utput)treamD#5!ect'nput)tream?
A:
A sample code here, which writes to b3ectutputStream, and reads it back from
b3ectInputStream. The program not only deals with instance ob3ect, but also #lass ob3ect. In
addition, it uses reflection to analy?e how it works.
Gind it at TestSeriali?ation.3ava $retty heavy iUo, seriali?ation, reflection, transientUstatic stuff, if it is
too over your head, skip it.
12. 2ow to compare two .5inaryDnot/ files to see if they are identical?
A:
M* pen B streams
B* #ompare their length first, if not the same, done
@* If the same lengths, then compare byte to byte, until you find anything not the same, or end-of-
file
P* &ou get your answer
13. When ' use the followin" code to write to a file9 why the file has no data in it?
UU WriteGile.3ava
import 3ava.io.5;
public class WriteGile 7
public static void main(String^_args*throws ./ception 7
GileutputStream fos 8 new GileutputStream()out.t/t)*;
$rintWriter pw 8 new $rintWriter(fos*;
pw.print(true*;
pw.println()short content file)*;
>
>
A:
When you open out.t/t, it is an empty file, correct. Try to write a lot of te/t on to the file, and then
you get something back, but not all of them.
WhyE The reason is for efficiency, the %40 or S tries to buffer the data to reduce the hit of hard
disk or other media. If you do not flush and close, the data might be lost.
I remember when I was coding in $ascal (#E*, I had e/act the same problem. I learned a lesson
that always closing you file or stream after finishing readUwrite to it.
If you change you code to the forlowing, everything will be ok=
UU WriteGile.3ava
import 3ava.io.5;
public class WriteGile 7
public static void main(String^_args*throws ./ception 7
GileutputStream fos 8 new GileutputStream()out.t/t)*;
$rintWriter pw 8 new $rintWriter(fos*;
pw.print(true*;
pw.println()short content file)*;
pw.close(*;
fos.close(*;
>
>
?ar5a"e %ollection
1. Will finali<e method of all o5!ects eventually 5e called?
A: The answer is yes, with an e/ception of %40 being killed abruptly for internal or e/ternal
reasons.
If the your application is terminated normally, the finali?e method of all ob3ects eventually will be
called. The simlest way to prove it would be writing a very small application with a few ob3ects
instantiali?ed. All ob3ects in your application have a finali?e method with a println()\\\ ob3ect
finali?e method is called now.)*; in it. Aun it and see the result. This is because %40 will take care
of it before normal e/it. All ob3ects are eligible for J# and will be J#ed before %40 terminates. f
course, we are not considering the special case that %40 might have a bug. :*
However, what is the e"ception!
%40 is killed internally, by
1. System.e/it(M*;
2. :ncaught ./ception being thrown at the top level.
@. &ou may add more...
%40 is killed e/ternally, by
1. :ser use ctrl # or other system commands to kill it on windows, uni/, or ...
2. System power off.
@. &ou may add more...
1&. Any class that includes a finali<e method should invo3e its superclassL finali<e method9
why?
A:
The point is that finali?e methods are not automatically )chained) - if you subclass a class that
has an important finali?e, your finali?e method should call it. bviously if you donFt know what the
superclass finali?e method does, you should call it anyway, 3ust to be safe.
"y contrast, When you create an ob3ect with the new keyword, the superclass constructor(s* are
called first. This is automatically )chained).
1(. When an o5!ect 5ecomes eli"i5le for "ar5a"e collection?
A:
,he o5!ect is no lon"er referenced or referenced only 5y o5!ects9 which are eli"i5le for
?%.An ob3ect becomes eligible for garbage collection when there is no way for any active thread
to reach that ob3ect through a reference or chain of references. (An e+uivalent answer by %im
&ingst*Set all references to an ob3ect to null is sufficient for an ob3ect eligible to J#, but not
necessary.
'ere are two simple e/amples with proper comments:
public class TestM7
public static void main(String^_ args* 7
b3ect a 8 new b3ect(*;
b3ect b 8 a;
a 8 null;
UU the b3ect is still referred by b.
UU which is not eligible for garbage collection.
UU an infinite loop here
int i 8 C;
while (true*7
i 8 i,,;
>
UU:sing ctrl # to kill it, sorry=
>
>

public class TestB7
public static void main(String^_ args* 7
b3ect^_ ary 8 new b3ect^Q_;
for (int i8C; iKQ; i,,* 7
ary^i_ 8 new b3ect(*;
>
UU do something here
ary 8 null;
UU9ow all ob3ects in the array are eligible for J#
UU even none of their references are null.
>
>
1*. %an circular reference prevent o5!ects from 5e "ar5a"e collected?
A: 9o= $rove by counter e/ample:
class TestM 7
public static void main(String arg^_* throws ./ception7
0yb3 a 8 new 0yb3()a)*;
0yb3 b 8 new 0yb3()b)*;

UUcircular reference here
a.o 8 b;
b.o 8 a;
a 8 null;
b 8 null;
UU a and b are both eligible for J# now

0yb3 c 8 new 0yb3()c)*;
c.o 8 new 0yb3()d)*; UUwhen c dies, d dies too.
c 8 null;

UU an infinite loop here
UU use `c to kill it

0yb3^_ ob3Ary 8 new 0yb3^MCBP_;
int i 8 C;
while (true*7
UU suggest %40 to J#
System.gc(*;

UU use more memory here
i W8 MCBP;
ob3Ary^i_ 8 new 0yb3()\) , i*;

i,,;
Thread.sleep(Q*; UU Jive #$: some breath time
>
>
>
class 0yb3 7
0yb3 o;
String s;
long^_ ary 8 new long^PCOR_; UU make 0yb3 big

0yb3(String s* 7
this.s 8 s;
>

protected void finali?e(* throws Throwable 7
UU 0ake J# visible
System.out.println(s , ): I am dying)*;
super.finali?e(*;
>
>
11. 2ow many o5!ects are eli"i5le for ?% in the followin" code after d M null?
public class Test7
public static void main(String^_ args* 7
b3ect a 8 new b3ect(*; UU the ob3ect original referenced by ob3ect reference a
b3ect b 8 new b3ect(*;
b3ect c 8 new b3ect(*;
b3ect d 8 new b3ect(*;
d8c8b8a;
d8null;
>
>
A:
%ust remember that operator M is ri"ht associate, and then you should be able to figure out the
answer by yourself. The e+uivalent statement is dM.cM.5Ma//N The e/ample in here following can
be used to get the answer you need too, minor change re+uired.
Answer: Three.
M* After b8a, the ob3ect original referenced by b is eligible for J#.
B* After c8(b8a*, the ob3ect original referenced by c is eligible for J#.
@* After d8(c8(b8a**, the ob3ect original referenced by d is eligible for J#.
P* After d8null, nothing new is eligible for J#.
Q* The ob3ect original referenced by a is not eligible for J#, since it is still referred by references
a, b, c. R* 0ake sure you understand the differences between physical ob3ect and ob3ect
reference (pointer to ob3ect*.
16. 'n "ar5a"e collection mechanism9 what is vendorDplatform dependent? What is not?
A:
'ow J# implemented is vender and platform dependent. Which means:
't is vender and platform dependent that when and in what order the eli"i5le for ?% o5!ects
will 5e ?%ed.
'owever, which ob3ects are eligible for J# is independent of implementations. !ifferent vendor
may use different algorithms. What algorithm used to find the ob3ects, which are eligible for J#
does not matter. What really matters is that they use the same principle.
,he o5!ect is no lon"er referenced or referenced only 5y o5!ects9 which are eli"i5le for ?%.
:nless they have a bug...
28.%an an o5!ect 5e "ar5a"e collected9 5ut a field of it is still alive?
A: Sure, as long as it is still referred by something.
Actually, this is used by many design patterns, e.g. Gactory 0ethod pattern. See the following
e/ample, read the comments carefully=
UU :seSimple.3ava
class Simple 7
void writeSomething(String msg* 7
System.out.println()Simple.writeSomething: ) , msg*;
>

protected void finali?e(*throws Throwable7
System.out.println()Ginali?e:Simple)*;
super.finali?e(*;
>
>
class #ombineSimple7
private Simple simGld;

Simple getSimpleGield(* 7
if( simGld 88 null * 7
simGld 8 new Simple(*;
>
return simGld;
>
protected void finali?e(*throws Throwable7
System.out.println()Ginali?e:#ombineSimple)*;
super.finali?e(*;
>
>
public class :seSimple 7
public static void main(String^_ args* 7
#ombineSimple csb3 8 new #ombineSimple(*;
Simple simb3 8 csb3.getSimpleGield(*;
csb3 8 null;

UU Since J# cannot be forced
UU we make sure csb3 is J#ed.
System.gc(*;
for (int i8C; iK@; i,,*7
try 7
Thread.sleep(MCCC*;
>
catch (Interrupted./ception e* 7
>
System.gc(*;
>

UU The simGld field of csb3 will be still alive
UU since it is still referred by simb3
simb3.writeSomething()I am still alive=)*;
>
>
21. What is mar3 and sweep "ar5a"e collection al"orithm9 is there other al"orithms?
A:
The +uestion is out of the scope of S#%$, however, it will help you in 3ob-hunting process. 'ere is
a beautiful applet, which will give you the basics, and have fun: 'eap of Gish, A Simulation of a
Jarbage-#ollected 'eap

You might also like