SlideShare a Scribd company logo
1 of 91
Learn Java/J2EE core concepts and design/coding issues With Java/J2EE Job
Interview Companion By K.Arulkumaran Technical Reviewers Craig Malone Lara D
Albreo Stuart Watson Acknowledgements A. Sivayini R.Kumaraswamipillai Cover
Design K. Arulkumaran A.Sivayini
Java/J2EE Job Interview Companion Copy Right 2005 K.Arulkumaran The author has
made every effort in the preparation of this book to ensure the a ccuracy of the
information. However, information in this book is sold without warranty either
express or imp lied. The author will not be held liable for any damages caused
or alleged to be caused either directly or indirec tly by this book.
Outline SECTION DESCRIPTION What this book will do for you? Motivation for this
book Key Areas index SECTION 1 Interview questions and answers on: Java ..
Language Fundamentals .. Swing .. Applet . Performance and memory Leaks. ..
Personal SECTION 2 Interview questions and answers on: Enterprise Java ..
J2EE .. Servlet .. JSP .. JDBC .. JNDI .. RMI .. EJB .. JMS .. XML . SQL,
Database tuning and O/R mapping . RUP & UML .. Struts . Web and Application
servers. . Best practices and performance considerations. . Testing and
deployment. .. Personal SECTION 3 Putting it all together section. How would you
go about ? 1. How would you go about documenting your Java/J2EE application? 2.
How would you go about designing a Java/J2EE application? 3. How would you go
about identifying performance problems and/or memory leaks i n your Java
application? 4. How would you go about minimising memory leaks in your Java/J2EE
application? 5. How would you 6. How would you Java/J2EE application? 7. How
would you Java/J2EE application? 8. How would you our Java/J2EE go about
improving performance of your Java/J2EE application? go about identifying any
potential thread-safety issues in your go about identifying any potential
transactional issues in your go about applying the Object Oriented (OO) design
concepts in y
application? 9. How would you go about applying the UML diagrams in your
Java/J2EE project? 10. How would you go about describing the software
development processes you are familiar with? 11. How would you go about applying
the design patterns in your Java/J2EE applic ation? 12. How would you go about
determining the enterprise security requirements for your Java/J2EE application?
13. How would you go about describing the open source projects like JUnit (unit
testing), Ant (build tool), CVS (version control system) and log4J (logging
tool) which are integral part of most Java/J2EE projects? 14. How would you go
about describing Web services? SECTION 4 Emerging Technologies/Frameworks . Test
Driven Development (TDD). . Aspect Oriented Programming (AOP). . Inversion of
Control (IOC) (Also known as Dependency Injection). .. Annotations or attributes
based programming (xdoclet etc). .. Spring framework. .. Hibernate framework. ..
EJB 3.0. . JavaServer Faces (JSF) framework. SECTION 5 Sample interview
questions . Java . Web Components . Enterprise . Design . General GLOSSARY OF
TERMS RESOURCES INDEX
Table of contents Outline
________________________________________________________________________ 3 Table
of contents ______________________________________________________________ __ 5
What this book will do for you? ________________________________________________
_____ 6 Motivation for this
book________________________________________________________ ___ 7 Key Areas
Index ________________________________________________________________ _ 9 Java
Interview questions & answers______________________________________________ _ 10
Java Language Fundamentals _____________________________________________________
__ 11 Java Personal
__________________________________________________________________ ___ 37 Java
Key Points ________________________________________________________________ ___
40 GLOSSARY OF TERMS _________________________________________________________
43 RESOURCES __________________________________________________________________
45 INDEX _______________________________________________________________________
47
What this book will do for you? Have you got the time to read 10 or more books
and articles to add value prior t o the interview? This book has been written
mainly from the perspective of Java/J2EE job seekers and interviewers. T here
are numerous books and articles on the market covering specific topics like
Java, J2EE, EJB, Design Patterns, AN T, CVS, Multi-Threading, Servlets, JSP,
emerging technologies like AOP (Aspect Oriented Programming), Test Driven Develo
pment (TDD), Inversion of Control (IoC) etc. But from an interview perspective
it is not possible to brush up on a ll these books where each book usually has
from 300 pages to 600 pages. The basic purpose of this book is to cover all the
core concepts and design/coding issues which, all Java/J2EE developers,
designers and architects should be conversant w ith to perform well in their
current jobs and to launch a successful career by doing well at interviews. The
interviewer c an also use this book to make sure that they hire the right
candidate depending on their requirements. This book contain s a wide range of
topics relating to Java/J2EE development in a concise manner supplemented with
diagrams, tables, sa mple codes and examples. This book is also appropriately
categorised to enable you to choose the area of inter est to you. This book will
assist all Java/J2EE practitioners to become better at what they do. Usually it
takes years to understand all the core concepts and design/coding issues when
you rely only on your work exper ience. The best way to fast track this is to
read appropriate technical information and proactively apply these in your work
environment. It worked for me and hopefully it will work for you as well. I was
also at one stage undecided whethe r to name this book Java/J2EE core concepts
and solving design/coding issues or Java/J2EE Job Interview Companion . The
reason I chose Java/J2EE Job Interview Companion is because these core concepts
and design/coding issues helped me to be successful in my interviews and also
gave me thumbs up in code reviews.
Motivation for this book I started using Java in 1999 when I was working as a
junior developer. During th ose two years as a permanent employee, I pro-
actively spent many hours studying the core concepts behind Java/J2EE in a
ddition to my hands on practical experience. Two years later I decided to start
contracting. Since I started cont racting in 2001, my career had a muchneeded
boost in terms of contract rates, job satisfaction, responsibility etc. I moved
from one contract to another with a view of expanding my skills and increasing
my contract rates. In the last 5 years of contracting, I have worked for 5
different organisations both medium and large on 8 different projects. For each
contract I held, on average I attended 6-8 interviews with di fferent companies.
In most cases multiple job offers were made and consequently I was in a position
to negotiate my contra ct rates and also to choose the job I liked based on the
type of project, type of organisation, technology used, etc. I have also sat for
around 10 technical tests and a few preliminary phone interviews. The success in
the interviews did not come easily. I spent hours prior to each s et of
interviews wading through various books and articles as a preparation. The
motivation for this book was to collate all this information into a single book,
which will save me time prior to my interviews but also can benefit others in th
eir interviews. What is in this book has helped me to go from just a Java/J2EE
job to a career in Java/J2EE in a short ti me. It has also given me the job
security that I can find a contract/permanent job opportunity even in the
difficu lt job market . I am not suggesting that every one should go contracting
but by performing well at the interviews you can be in a position to pick the
permanent role you like and also be able to negotiate your salary pa ckage.
Those of you who are already in good jobs can impress your team leaders,
solution designers and/or architects fo r a possible promotion by demonstrating
your understanding of the key areas discussed in this book. You can discuss with
your senior team members about perfomance issues, transactional issues,
threading issues (concurrency issues) a nd memory issues. In most of my previous
contracts I was in a position to impress my team leads and architect s by
pinpointing some of the critical For example: performance, memory, transactional
and threading issues with the code and subseq uently fixing them. Trust me it is
not hard to impress someone if you understand the key areas. . Struts action
classes are not thread-safe (Refer Q113 in Enterprise section). . JSP variable
declaration is not thread-safe (Refer Q34 in Enterprise section). . Valuable
resources like database connections should be closed properly to avoid any
memory and performance issues (Refer Q45 in Enterprise section). .
Throwing an application exception will not rollback the transaction in EJB. (Ref
er Q77 in Enterprise section). The other key areas, which are vital to any
software development, are a good und erstanding of some of key design concepts,
design patterns, and a modelling language like UML. These key areas ar e really
worthy of a mention in your resume and interviews. For example: . Know how to
use inheritance, polymorphism and encapsulation (Refer Q5, Q6, Q7, a nd Q8 in
Java section.). . Why use design patterns? (Refer Q5 in Enterprise section). .
Why is UML important? (Refer Q106 in Enterprise section). If you happen to be in
an interview with an organization facing serious issues w ith regards to their
Java application relating to memory leaks, performance problems or a crashing
JVM etc then you ar e likely to be asked questions on these topics. Refer Q 63 Q
65 in Java section and Q123, Q125 in Enterprise secti on. Another good reason
why these key areas like transactional issues, design concep ts, design patterns
etc are vital are because solution designers, architects, team leads, and/or
senior developers are usually responsible for conducting the technical
interviews. These areas are their favourite topics because these are e ssential
to any software development. Some interviewers request you to write a small
program during interview or prior to getting to the interview stage. This is to
ascertain that you can code using object oriented concepts and design pattern s.
So I have included a coding key area to illustrate what you need to look for
while coding.
. Apply OO concepts like inheritance, polymorphism and encapsulation: Refer Q08
in Java section. . Program to interfaces not to implementations: Refer Q08, Q15
in Java section. . Use of relevant design patterns: Refer Q11 in How would you
go about section. . Use of Java collection API and exceptions correctly: Refer
Q15, Q34, and Q35 in Java section. . Stay away from hard coding values: Refer
Q04 in Java section. L a ngu a g e F und a m e n t a ls D es i g n C onc e p t s
D es ig n P a tte r n s SE cu r it y C on c u r r e nc y Iss u e s P e r f o r m
an ce Issu es M em o r y Iss u e s S ca l a b il i t y Iss u e s S p eci f i cat
i o n F u nda m e nt a ls E xce p t io n H a n d lin g T r a n sac t i o n al
Issu e s B est P ra c t i c e s S o ftw a r e D eve lo p m en t P r o ces s CO
di n g LF DC DP SF CI PI MI SI SE EH TI BP SD CO H o w m a n y b o o k s d o I h
a v e to r e a d to unde r s ta nd and pu t to geth er all th es e ke y ar e a
s? H o w m a ny y e a r s o f ex per ie nc e s hou ld I hav e to un der s ta n d
a ll th e s e ke y ar e a s? W ill th e s e k e y a r e a s h e lp m e pr og r e
s s in m y c a r eer ? W ill th e s e k e y a r e a s h e lp m e c u t quality c
ode ? This book aims to solve the above dilemma.
My dad keeps telling me to find a permanent job (instead of contracting), which
in his view provides better job security but I keep telling him that in my view
in Information Technology the job security is achieved only by keeping your
knowledge and skills sharp and up to date. The 8 contract positions I held over
the last 5 .5 years have given me broader experience in Java/J2EE and related
technologies. It also kept me motivated since there was always something new to
learn in each assignment, and not all companies will appreciate your skills and
expertise unti l you decide to leave. Do the following statements sound familiar
to you when you hand in your resignation or decide not to extend your contract
after getting another job offer? Can I tempt you to come back? What can I do to
keep you here? tc. You might even think why you waited so long. The best way to
make an impression in any organisations is to un derstand and proactively apply
and resolve the issues relating to the Key Areas discussed in the next section.
But be a team player, be tactful and don t be critical of everything, do not act
in a superior way and have a sense of humo ur. Technical skills must be
complemented with interpersonal skills. Quick Read guide: It is recommended that
you go through all the questions in all the sections but if you are pressed for
time or would like to read it just before an interview then follow the steps
shown below: 1. Read/Browse 2. Read/Browse 3. Read/Browse 4. Read/Browse sed in
detail.
e
Popular Questions in Java and Enterprise Java sections. Key Points in Java and
Enterprise Java sections. through Emerging Technologies/Frameworks section. How
would you go about section excluding Q11 & Q13, which are discus
Key Areas Index I have categorised the core concepts and issues into 14 key
areas as listed belo w. These key areas are vital for any good software
development. This index will enable you to refer to the questions based on key
areas. Also note that each question has an icon next to it to indicate which key
area or areas it belongs t o. Additional reading is recommended for beginners in
each of the key areas. Key Areas icon Question Numbers Java section Enterprise
section How would you go about ? Emerging Technologies /Frameworks Language
Fundamentals LF Q1-Q4, Q10-Q14, Q16Q20, Q22-Q27, Q30Q33, Q36-Q43, Q47-Q62 -Q10,
Q15, Q17, Q19 Specification Fundamentals SF -Q1-Q19, Q26-Q33, Q35Q38, Q41, Q42,
Q44, Q46Q81, Q89-Q97, Q99, 102, Q110, Q112-Q115, Q118Q119, Q121, Q126, Q127,
Q128 Q14 Design Concepts DC Q5-Q9, Q10, Q13, Q22, Q49 Q2, Q3, Q19, Q20, Q21,
Q31, Q45, Q98, Q106, Q107, Q108, Q109, 101, Q111 Q02, Q08, Q09 Q3-Q9, Q11, Q13,
Q14, Q16, Q18, Q20 Design Patterns DP Q10, Q14, Q20, Q31, Q45, Q46, Q50, Q54,
Q66 Q5, Q5, Q22, Q24, Q25, Q83, Q84, Q85, Q86, Q87, Q88, Q110, Q111, Q116 Q11
Q12 Transactional Issues TI -Q43, Q71, Q72, Q73, Q74, Q75, Q77, Q78, Q79 Q7
Concurrency Issues CI Q13, Q15, Q29, Q36,
Q40, Q53 Q16, Q34, Q113 Q6 Performance Issues PI Q13, Q15 -Q22, Q40, Q53, Q63.
Q10, Q16, Q43, Q45, Q46, Q72, Q83-Q88, Q97, Q98, Q100, Q102, Q123, Q125, Q128
Q3, Q5 Memory Issues MI Q22, Q29, Q32, Q33, Q36, Q45, Q64, Q65. Q45, Q93 Q3, Q4
Scalability Issues SI Q19, Q20 Q20, Q21, Q120, Q122 Exception Handling EH
Q34,Q35 Q76, Q77 Security SE Q61 Q12, Q13, Q23, Q35, Q46, Q51, Q58, Q81 Q12 Best
Practices BP Q15, Q21, Q34, Q63, Q64 Q10, Q16, Q39, Q40, Q46, Q82, Q124, Q125
Software Development Process SD -Q103-Q109, Q129, Q133, Q134, Q136 Q1, Q10, Q13
Q1, Q2 Coding1 CO Q04, Q08, Q10, Q12, Q13, Q15, Q16, Q17, Q21, Q34, Q45, Q46
Q10, Q18, Q21, Q23, Q36, Q38, Q42, Q43, Q45, Q74, Q75, Q76, Q77, Q112, Q114,
Q127, Q128 Q11 1 Some interviewers request you to write a small program during
interview or pri or to getting to the interview stage. This is to ascertain that
you can code using object oriented concepts and design patterns. I have inc
luded a coding key area to illustrate what you need to look for while coding.
Unlike other key areas, the CO is not always shown agains t the question but
shown above the actual section of relevance within a question.
10 Java SECTION ONE Java Interview questions & answers
K E Y A R E A S .. Language Fundamentals LF .. Design Concepts DC .. .. .. .. ..
.. Design Patterns DP Concurrency Issues CI Performance Issues PI Memory Issues
MI Exception Handling EH Security SE
.. Scalability Issues SI .. Coding1 CO Popular Questions: Q01, Q04, Q07, Q08,
Q13, Q16, Q17, Q18, Q19, Q25, Q27, Q29, Q 32, Q34, Q40, Q45, Q46, Q50, Q51, Q53,
Q54, Q55, Q63,Q64, Q66, Q67 Unlike other key areas, the CO is not always shown
against the question but sho wn above the actual subsection of relevance within
a question.
Java 11 Java Language Fundamentals Q 01: Give a few reasons for using Java? LF
DC A 01: Java is a fun language. Let s look at some of the reasons: . Built-in
support for multi-threading, socket communication, and memory managemen t
(automatic garbage collection). . Object Oriented (OO). . Better portability
than other languages across operating systems. . Supports Web based applications
(Applet, Servlet, and JSP), distributed applicat ions (sockets, RMI. EJB etc)
and network protocols (HTTP, JRMP etc) with the help of extensive standardised A
PIs (Application Program Interfaces). Q 02: What is the main difference between
the Java platform and the other softwa re platforms? LF A 02: Java platform is a
software-only platform, which runs on top of other hard ware-based platforms
like UNIX, NT etc. The Java platform has 2 components: . Java Virtual Machine
(JVM) JVM is a software that can be ported onto various hardw are platforms.
Byte codes are the machine language of the JVM. . Java Application Programming
Interface (Java API) Q 03: What is the difference between C++ and Java? LF A 03:
Both C++ and Java use similar syntax and are Object Oriented, but: . Java does
not support pointers. Pointers are inherently tricky to use and troubl esome. .
Java does not support multiple inheritances because it causes more problems than
it solves. Instead Java supports multiple interface inheritance, which allows an
object to inherit many method signatures from different interfaces with the
condition that the inheriting object must implemen t those inherited methods.
The multiple interface inheritance also allows an object to behave
polymorphically o n those methods. [Refer Q 8 and Q 10 in Java section.] . Java
does not support destructors but rather adds a finalize() method. Finalize
methods are invoked by the garbage collector prior to reclaiming the memory
occupied by the object, which h as the finalize() method. This
means you do not know when the objects are going to be finalized. Avoid using fi
nalize() method to release non-memory resources like file handles, sockets,
database connections et c because Java has only a finite number of these
resources and you do not know when the garbage collecti on is going to kick in
to release these resources through the finalize() method. . Java does not
include structures or unions because the traditional data structur es are
implemented as an object oriented framework (Java collection framework Refer
Q14, Q15 in Java sect ion).
12 Java . All the code in Java program is encapsulated within classes therefore
Java does not have global variables or functions. . C++ requires explicit memory
management, while Java includes automatic garbage c ollection. [Refer Q32 in
Java section]. Q 04: Explain Java class loaders? Explain dynamic class loading?
LF A 04: Class loaders are hierarchical. Classes are introduced into the JVM as
the y are referenced by name in a class that is already running in the JVM. So
how is the very first class loaded? The very f irst class is specially loaded
with the help of static main() method declared in your class. All the
subsequently lo aded classes are loaded by the classes, which are already loaded
and running. A class loader creates a namespac e. All JVMs include at least one
class loader that is embedded within the JVM called the primordial (or bootstrap
) class loader. Now let s look at non-primordial class loaders. The JVM has
hooks in it to allow user defined clas s loaders to be used in place of
primordial class loader. Let us look at the class loaders created by the JVM.
CLASS LOADER reloadable? Explanation Bootstrap (primordial) No Loads JDK
internal classes, java.* packages. (as defined in the sun.boot.clas s.path
system property, typically loads rt.jar and i18n.jar) Extensions No Loads jar
files from JDK extensions directory (as defined in the j ava.ext.dirs system
property usually lib/ext directory of the JRE) System No Loads classes from
system classpath (as defined by the java.class.path property, which is set by
the CLASSPATH environment variable or classpath or cp command line options)
Bootstrap (primordial) (rt.jar, i18.jar) Extensions (lib/ext) System (-
classpath) Sibling1 classloader Sibling2 classloader JVM class loaders Classes
loaded by Bootstrap class loader have no visibility into classes loaded by its
descendants (ie Extensions and Systems class loaders). The classes loaded by
system class loader have visibility into classes loaded by its parents (ie
Extensions and Bootstrap class loaders). If there were any sibling class loaders
they cannot see classes loaded by each other. They can only see the classes
loaded by their parent class loader. For example Sibling1 class loader cannot
see classes loaded by
Sibling2 class loader Both Sibling1 and Sibling2 class loaders have visibilty
into classes loaded by their parent class loaders (eg: System, Extensions, and
Bootstrap) Class loaders are hierarchical and use a delegation model when
loading a class. Class loaders request their parent to load the class first
before attempting to load it themselves. When a c lass loader loads a class, the
child class loaders in the hierarchy will never reload the class again. Hence
uniquene ss is maintained. Classes loaded by a child class loader have
visibility into classes loaded by its parents up th e hierarchy but the reverse
is not true as explained in the above diagram. Important: Two objects loaded by
different class loaders are never equal even if they carry the same values,
which mean a class is uniquely identified in the context of the associated class
loader. This applies to singletons too, where each class loader will have its
own singleton. [Refer Q45 in Java section for singleton des ign pattern] Explain
static vs dynamic class loading? Static class loading Classes are statically
loaded with Java s new operator. class MyClass { public static void main(String
args[]) { Car c = new Car(); } } Dynamic class loading Dynamic loading is a
technique for programmatically invoking the functions of a class loader at run
time. Let us look at how to load classes dynamically. Class.forName (String
className); //static method which returns a Class The above static method
returns the class object associated with the class name. The string className
can be supplied dynamically at run time. Unlike the static loading, the dynamic
loading will decide whether to load the class Car or the class Jeep at runtime
based on a properties file and/or other runtime
Java 13 conditions. Once the class is dynamically loaded the following method
returns an instance of the loaded class. It s just like creating a class object
with no arguments. class.newInstance (); //A non-static method, which creates an
instance of a class (ie creates an object). Jeep myJeep = null ; //myClassName
should be read from a properties file or Constants interface. //stay away from
hard coding values in your program. CO String myClassName = "au.com.Jeep" ;
Class vehicleClass = Class.forName(myClassName) ; myJeep = (Jeep)
vehicleClass.newInstance(); myJeep.setFuelCapacity(50); A
NoClassDefFoundException is A ClassNotFoundException is thrown when an applica
tion tries to load in a thrown if a class is referenced with class through its
string name using the fol lowing methods but no definition for the Java s new
operator (i.e. static loading) class with the specified name could be fou nd:
but the runtime system cannot find the referenced class. . The forName(..)
method in class - Class. . The findSystemClass(..) method in class -
ClassLoader. . The loadClass(..) method in class - ClassLoader. What are static
initializers or static blocks with no function names ? When a class i s loaded,
all blocks that are declared static and don t have function name (ie static
initializers) are executed even before the constructors are executed. As the
name suggests they are typically used to initi alize static fields. CO public
class StaticInitilaizer { public static final int A = 5; public static final int
B; //Static initializer block, which is executed only once when the class is
loade d. static { if(A == 5) B = 10; else B = 5; } public StaticInitilaizer()
{} // constructor is called only after static initial izer block } The following
code gives an Output of A=5, B=10. public class Test {
System.out.println("A =" + StaticInitilaizer.A + ", B =" + StaticInitilaizer.B);
} Q 05: What are the advantages of Object Oriented Programming Languages (OOPL)?
D C A 05: The Object Oriented Programming Languages directly represent the real
life objects like Car, Jeep, Account, Customer etc. The features of the OO
programming languages like polymorphism, in heritance and encapsulation make it
powerful. [Tip: remember pie which, stands for Polymorphis m, Inheritance and
Encapsulation are the 3 pillars of OOPL] Q 06: How does the Object Oriented
approach improve software development? DC A 06: The key benefits are: . Re-use
of previous work: using implementation inheritance and object composition . .
Real mapping to the problem domain: Objects map to real world and represent vehi
cles, customers, products etc: with encapsulation. . Modular Architecture:
Objects, systems, frameworks etc are the building blocks o f larger systems.
14 Java The increased quality and reduced development time are the by-products
of the ke y benefits discussed above. If 90% of the new application consists of
proven existing components then only t he remaining 10% of the code have to be
tested from scratch. Q 07: How do you express an is a relationship and a has a
heritance and composition? What is the difference between composition and
aggregation? relationship or explain in
DC A 07: The is a relationship is expressed with inheritance and has a
relationship is expressed with composition. Both inheritance and composition
allow you to place sub-objects inside your new class . Two of the main
techniques for code reuse are class inheritance and object composition.
Inheritance [ is a ] Vs Composition [ has a ] Building Bathroom House class
Building{ ....... } class House extends Building{ ......... } is a [House is a
Building] class House { Bathroom room = new Bathroom() ; .... public void
getTotMirrors(){ room.getNoMirrors(); .... } } has a [House has a Bathroom] is a
has a Inheritance is uni-directional. For example House is a Building. But
Building is not a House. Inheritance uses extends key word. Composition: is used
when House has a Bathroom. It is incorrec t to say House is a Bathroom.
Composition simply means using instance variables that refer to other objects.
The class House will have an instance variable, which refers to a Bathroom
object. Which one to use? The guide is that inheritance should be only used when
subclas s is a superclass. . Don t use inheritance just to get code reuse. If
there is no is a relationship then use composition for code reuse. Overuse of
implementation inheritance (uses the extends key word) can break all the
subclasses, if the superclass is modified.
. Do not use inheritance just to get polymorphism. If there is no is a
relationship and all you want is polymorphism then use interface inheritance
with composition, which gives you co de reuse (Refer Q8 in Java section for
interface inheritance). What is the difference between aggregation and
composition? Aggregation Aggregation is an association in which one class
belongs to a collection. This is a part of a whole relationship where a part can
exist without a whole. For example a line item is a whole and product is a part.
If a line item is deleted then corresponding product need not be deleted. So
aggregation has a weaker relationship. Composition Composition is an association
in which one class belongs to a collection. This is a part of a whole
relationship where a part cannot exist without a whole. If a whole is deleted
then all parts are deleted. For example An order is a whole and line items are
parts. If an order deleted then all corresponding line items for that order
should be deleted. So composition has a stronger relationship. Q 08: What do you
mean by polymorphism, inheritance, encapsulation, and dynamic binding? DC A 08:
Polymorphism means the ability of a single variable of a given type to be used
to reference objects of different types, and automatically call the method that
is specific to the type of object the variable references. In a nutshell,
polymorphism is a bottom-up method call. The benefit of polymorphism is that it
is very easy to add new classes of derived objects without breaking the calling
code (i.e. getTotArea() in the s ample code shown below) that uses the
polymorphic classes or interfaces. When you send a message to an object even
though you don t know what specific type it is, and the right thing happens,
that s called polymorphism. The process used by objectoriented programming
languages to implement polymorphism is called dynamic bindi ng. Let us look at
some sample code to demonstrate polymorphism: CO
Java 15 Sample code: //client or calling code double dim = 5.0; //ie 5 meters
radius or width List listShapes = new ArrayList(20); Shape s = new Circle();
listShapes.add(s); //add circle s = new Square(); listShapes.add(s); //add
square getTotArea (listShapes,dim); //returns 78.5+25.0=103.5 //Later on, if you
decide to add a half circle then define //a HalfCircle class, which extends
Circle and then provide an //area(). method but your called method
getTotArea(...) remains //same. s = new HalfCircle(); listShapes.add(s); //add
HalfCircle getTotArea (listShapes,dim); //returns 78.5+25.0+39.25=142.75 /**
called method: method which adds up areas of various ** shapes supplied to it.
**/ public double getTotArea(List listShapes, double dim){ Iterator it =
listShapes.iterator(); double totalArea = 0.0; //loop through different shapes
while(it.hasNext()) { Shape s = (Shape) it.next(); totalArea += s.area(dim);
//polymorphic method call } return totalArea ; } For example: given a base
class/interface Shape, polymorphism allows the programmer to define different
area(double dim1) methods for any number of derived classes such as Circle,
Square etc. No matter what shape an object is, applying the area method to it
will return the right results. Later on HalfCicle can be added without breaking
your called code i.e. method getTotalArea(...) Depending on what the shape is,
appropriate area(double dim) method gets called and calculated. Circle .. area
is 78.5sqm Square .. area is 25sqm HalfCircle .. area is 39.25 sqm +area() :
double <<abstract>>
Shape +area() : double Circle +area() : double HalfCircle +area() : double
Square +area() : double Circle +area() : double HalfCircle +area() : double
Square +area() : double «interface» Shape Inheritance is the inclusion of
behaviour (i.e. methods) and state (i.e. variabl es) of a base class in a
derived class so that they are accessible in that derived class. The key benefit
of Inhe ritance is that it provides the formal mechanism for code reuse. Any
shared piece of business logic can be moved from t he derived class into the
base class as part of refactoring process to improve maintainability of your cod
e by avoiding code duplication. The existing class is called the superclass and
the derived class is called the subc lass. Inheritance can also be defined as
the process whereby one object acquires characteristics from one or m ore other
objects the same way children acquire characteristics from their parents. There
are two types of inheritances: 1. Implementation inheritance (aka class
inheritance): You can extend an applica tions functionality by reusing
functionality in the parent class by inheriting all or some of the operations al
ready implemented. In Java, you can only inherit from one superclass.
Implementation inheritance promotes reusabilit y but improper use of class
inheritance can cause programming nightmares by breaking encapsulation and makin
g future changes a problem. With implementation inheritance, the subclass
becomes tightly coupled with the s uperclass. This will make the design fragile
because if you want to change the superclass, you must know all t he details of
the subclasses to avoid breaking them. So when using implementation inheritance,
make sure that th e subclasses depend only on the behaviour of the superclass,
not on the actual implementation. For exampl e in the above diagram the
subclasses should only be concerned about the behaviour known as area() but not
how it is implemented. 2. Interface inheritance (aka type inheritance): This is
also known as subtyping . Interfaces provide a mechanism for specifying a
relationship between otherwise unrelated classes, typically by specifying a set
of common methods each implementing class must contain. Interface inheritance
promotes the design concept of program to interfaces not to implementations.
This also reduces the coupling or implementat ion dependencies between systems.
In Java, you can implement any number of interfaces. This is more flexi
ble than implementation inheritance because it won t lock you into specific
implementations which make sub classes difficult to maintain. So care should be
taken not to break the implementing classes by modifying the inte rfaces. Which
one to use? Prefer interface inheritance to implementation inheritance bec ause
it promotes the design concept of coding to an interface and reduces coupling.
Interface inheritance ca n achieve code reuse with the help of object
composition. If you look at Gang of Four (GoF) design patterns, y ou can see
that it favours interface inheritance to implementation inheritance. CO
16 Java Implementation inheritance Interface inheritance Let s assume that
savings account and term deposit account have a similar behaviour in terms of
depositing and withdrawing money, so we will get the super class to implement
this behaviour and get the subclasses to reuse this behaviour. But saving
account and term deposit account have specific behaviour in calculating the
interest. public abstract class Account { public void deposit(double amount)
{ //deposit logic } public void withdraw(double amount) { //withdraw logic }
public abstract double calculateInterest(double amount); } public class
SavingsAccount extends Account { public double calculateInterest(double amount)
{ //calculate interest for SavingsAccount } } public class TermDepositAccount
extends Account { public double calculateInterest(double amount) { //calculate
interest for TermDeposit } } The calling code can be defined as follows for
illustration purpose only: public class Test { public static void main(String[]
args) { Account acc1 = new SavingsAccount(); acc1.deposit(5.0);
acc1.withdraw(2.0); Account acc2 = new TermDepositAccount(); acc2.deposit(10.0);
acc2.withdraw(3.0); acc1.calculateInterest(500.00);
acc2.calculateInterest(500.00); } } Let s look at an interface inheritance code
sample, which makes use of composition for reusability. In the following example
the methods deposit( ) and withdraw( ) share the same piece of code in
AccountHelper class. The method calculateInterest( ) has its specific
implementation in its own class. public interface Account { public abstract void
deposit(double amount); public abstract void withdraw(double amount); public
abstract int getAccountType(); } public interface SavingsAccount extends
Account{ public abstract double calculateInterest(double amount); } public
interface TermDepositAccount extends Account{ public abstract double
calculateInterest(double amount); } The classes SavingsAccountImpl,
TermDepositAccountImpl
should implement the methods declared in its interfaces. The class AccountHelper
implements the methods deposit( ) and withdraw( ) public class
SavingsAccountImpl implements SavingsAccount{ private int accountType = 1;
//helper class which promotes code reuse through composition AccountHelper
helper = new AccountHelper(); public void deposit(double amount)
{ helper.deposit(amount, getAccountType()); } public void withdraw(double
amount) { helper.withdraw(amount, getAccountType()); } public double
calculateInterest(double amount) { //calculate interest for SavingsAccount }
public int getAccountType(){ return accountType; } } public class
TermDepositAccountImpl implements TermDepositAccount { private int accountType =
2; //helper class which promotes code reuse through composition AccountHelper
helper = new AccountHelper(); public void deposit(double amount)
{ helper.deposit(amount, getAccountType()); } public void withdraw(double
amount) { helper.withdraw(amount, getAccountType()); } public double
calculateInterest(double amount) { //calculate interest for TermDeposit } public
int getAccountType() { return accountType; } } The calling code can be defined
as follows for illustration purpose only: public class Test { public static void
main(String[] args) {
Java 17 } } Account acc1 = new SavingsAccountImpl(); acc1.deposit(5.0); Account
acc2 = new TermDepositAccountImpl(); acc2.deposit(10.0); if
(acc1.getAccountType() == 1) { ((SavingsAccount)
acc1).calculateInterest(500.00); } if (acc2.getAccountType() == 2)
{ ((TermDepositAccount) acc2).calculateInterest(500.00); } Encapsulation refers
to keeping all the related members (variables and methods) together in an
object. Specifying members as private can hide the variables and methods.
Objects should hide their inner workings from the outside view. Good
encapsulation improves code modularity by preventing obje cts interacting with
each other in an unexpected way, which in turn makes future development and refa
ctoring efforts easy. Being able to encapsulate members of a class is important
for security and integ rity. We can protect variables from unacceptable values.
The sample code below describes how encapsulation can be used to protect the
MyMarks object from having negative values. Any modification to member variable
v marks can only be carried out through the setter method setMarks(int mark).
This prevents the object MyMark s from having any negative values by throwing an
exception. CO Sample code setName(Stringname) StringgetName() intgetMarks()
setMarks(intmark) private int vmarks; private String name; Class MyMarks
{ private int vmarks = 0; private String name; public void setMarks(int mark)
throws MarkException { if(mark > 0) this.vmarks = mark; else { throw new
MarkException("No negative Values"); } } public int getMarks(){ return vmarks; }
//getters and setters for attribute name goes here.
} Member variables are encapsulated, so that they can only be accessed via
encapsulating methods. Q 09: What is design by contract? Explain the assertion
construct? DC A 09: Design by contract specifies the obligations of a calling-
method and calle d-method to each other. Design by contract is a valuable
technique, which should be used to build well-defined int erfaces. The strength
of this programming methodology is that it gets the programmer to think clearly
about wh at a function does, what pre and post conditions it must adhere to and
also it provides documentation for the caller. Java uses the assert statement to
implement pre- and post-conditions. Java s exceptions handling also s upport
design by contract especially checked exceptions (Refer Q34 in Java section for
checked exceptions) . In design by contract in addition to specifying
programming code to carrying out intended operations of a method the programmer
also specifies: 1. Preconditions This is the part of the contract the calling-
method must agree to. Preconditions specify the conditions that must be true
before a called method can execute. Preconditions i nvolve the system state and
the arguments passed into the method at the time of its invocation. If a
preconditio n fails then there is a bug in the calling-method or calling
software component.
18 Java On public methods On non-public methods Preconditions on public methods
are enforced by explicit checks that throw particular, specified exceptions. You
should not use assertion to check the parameters of the public methods but can
use for the non-public methods. Assert is inappropriate because the method
guarantees that it will always enforce the argument checks. It must check its
arguments whether or not assertions are enabled. Further, assert construct does
not throw an exception of a specified type. It can throw only an AssertionError.
public void setRate(int rate) { if(rate <= 0 rate > MAX_RATE){ throw new
IllegalArgumentException( Invalid rate .. + rate); } setCalculatedRate(rate); }
You can use assertion to check the parameters of the non-public methods. private
void setCalculatedRate(int rate) { assert (rate > 0 && rate < MAX_RATE) :
rate; //calculate the rate and set it. } Assertions can be disabled, so programs
must not assume that assert construct will be always executed: //Wrong: if
assertion is disabled, CarpenterJob never //Get removed assert
jobsAd.remove(PilotJob); //Correct: boolean pilotJobRemoved =
jobsAd.remove(PilotJob); assert pilotJobRemoved; 2. Postconditions This is the
part of the contract the called-method agrees to. What must be true after a
method completes successfully. Postconditions can be used with assertions in bot
h public and non-public methods. The postconditions involve the old system
state, the new system state, the method arguments and the method s return value.
If a postcondition fails then there is a bug in the calledmethod or called
software component. public double calcRate(int rate) { if(rate <= 0 rate >
MAX_RATE){ throw new IllegalArgumentException( Invalid rate !!! ); } //logic to
calculate the rate and set it goes here assert this.evaluate(result) < 0 : this;
//this .. message sent to AssertionErro r on failure return result; } 3. Class
invariants - what must be true about each instance of a class? A class invariant
as an internal invariant that can specify the relationships among multiple
attributes, and should be true before and after any method
completes. If an invariant fails then there could be a hod or called-method.
There is no particular mechanism for checking invariants but ne all the
expressions required for checking invariants into a single internal method that
ns. For example if you have a class, which deals with negative integers then you
define the nternal method: class NegativeInteger { Integer value = new Integer
(-1); //invariant //constructor public NegativeInteger(Integer int) {
//constructor logic goes here assert isNegative(); }
bug in either calling-met it is convenient to combi can be called by assertio
isNegative() convenient i
//rest of the public and non-public methods goes here. public methods should ca
ll assert isNegative(); prior to its return //convenient internal method for
checking invariants. Returns true if the integ er value is negative private
boolean isNegative(){ return value.intValue() < 0 ; } } The isNegative() method
should be true before and after any method completes, ea ch public method and
constructor should contain the following assert statement immediately prior to i
ts return. assert isNegative(); Explain the assertion construct? The assertion
statements have two forms as show n below: assert Expression1;
Java 19 assert Expression1 : Expression2; Where: . Expression1 Æ is a boolean
expression. If the Expression1 evaluates to false, it throws an Ass ertionError
without any detailed message. . Expression2 .. if the Expression1 evaluates to
false throws an AssertionError wi th using the value of the Expression2 as the
errors detailed message. Note: If you are using assertions (available from
JDK1.4 onwards), you should su pply the JVM argument to enable it by package
name or class name. Java -ea[:packagename... :classname] or Java
-enableassertions[:packagename... : classname] Java ea:Account Q 10: What is the
difference between an abstract class and an interface and when should you use
them? LF DP DC A 10: In design, you want the base class to present only an
interface for its de rived classes. This means, you don t want anyone to
actually instantiate an object of the base class. You only want to upc ast to it
(implicit upcasting, which gives you polymorphic behaviour), so that its
interface can be used. This is acc omplished by making that class abstract using
the abstract keyword. If anyone tries to make an object of an abs tract class,
the compiler prevents it. The interface keyword takes this concept of an
abstract class a step further by preventing any method or function
implementation at all. You can only declare a method or function but not provide
the implementation. The class, which is implementing the interface, should
provide the actual implementation. T he interface is a very useful and commonly
used aspect in OO design, as it provides the separation of interface an d
implementation and enables you to: ..Capture similarities among unrelated
classes without artificially forcing a cl ass relationship. ..Declare methods
that one or more classes are expected to implement. ..Reveal an object's
programming interface without revealing its actual implemen tation. ..Model
multiple interface inheritance in Java, which provides some of the benef its of
full on multiple inheritances, a feature that some object-oriented languages
support that allow a class to have more than one superclass. Shape Circle Square
CircleOnSquare
Diamond problem & use of interface No multiple inheritance in JAVA Circle Square
CircleOnSquare <<Interface>> ShapeIF <<Interface>> CircleIF <<Interface>>
SquareIF Multiple interface inheritance in JAVA Abstract class Interface Have
executable methods and abstract methods. Have no implementation code. All m
ethods are abstract. Can only subclass one abstract class. A class can implement
any number of interf aces. Can have instance variables, constructors and any
visibility: public, private, protected, none (aka package). Cannot have instance
variables, constructors and can have only public and none (aka package)
visibility. When to use an abstract class?: In case where you want to use
implementation inh eritance then it is usually provided by an abstract base
class. Abstract classes are excellent candidates in side of application
frameworks. Abstract classes let you define some default behaviour and force
subclasses to p rovide any specific behaviour. Care should be taken not to
overuse implementation inheritance as discussed in Q 8 in Java section.
20 Java When to use an interface?: For polymorphic interface inheritance, where
the clie nt wants to only deal with a type and does not care about the actual
implementation use interfaces. If you need to change your design frequently, you
should prefer using interface to abstract. CO Coding to an interface reduces
coupling and interface inheritance can achieve code reuse with the help of
object composition. Another justification for using interfaces is that they
solve the diamond problem of traditional multiple inheritance as show n in the
figure. Java does not support multiple inheritances. Java only supports multiple
interface inheritance . Interface will solve all the ambiguities caused by this
diamond problem . Design pattern: Strategy design pattern lets you swap new
algorithms and process es into your program without altering the objects that
use them. Strategy design pattern: Refer Q11 in How wo uld you go about section.
Q 11: Why there are some interfaces with no defined methods (i.e. marker interfa
ces) in Java? LF A 11: The interfaces with no defined methods act like markers.
They just tell th e compiler that the objects of the classes implementing the
interfaces with no defined methods need to be treated different ly. Example
Serializable (Refer Q19 in Java section), Cloneable etc Q 12: When is a method
said to be overloaded and when is a method said to be ove rridden? LF CO A 12:
Method Overloading Method Overriding Overloading deals with multiple methods in
the same class with the same name but different method signatures. class MyClass
{ public void getInvestAmount(int rate) { } public void getInvestAmount(int
rate, long principal) { } } Both the above methods have the same method names
but different method signatures, which mean the methods are overloaded.
Overriding deals with two methods, one in the parent class and the other one in
the child class and has the same name and signatures. class BaseClass{ public
void getInvestAmount(int rate) { } } class MyClass extends BaseClass { public
void getInvestAmount(int rate) { } } Both the above methods have the same method
names and the signatures but the method in the subclass MyClass overrides the
method in the superclass BaseClass. Overloading lets you define the same
operation in
different ways for different data. Overriding lets you define the same operation
in different ways for different object types. Q 13: What is the main difference
between an ArrayList and a Vector? What is the main difference between Hashmap
and Hashtable? LF DC PI CI A 13: Vector / Hashtable ArrayList / Hashmap Original
classes before the introduction of Collections API. Vector & Hashtable are
synchronized. Any method that touches their contents is thread-safe. So if you
don t need a thread safe collection, use the ArrayList or Hashmap. Why pay the
price of synchronization unnecessarily at the expense of performance
degradation. So which is better? As a general rule, prefer ArrayList/Hashmap to
Vector/Hashta ble. If your application is a multithreaded application and at
least one of the threads either adds or deletes an entry into the collection
then use new Java collection API s external synchronization facility as shown
belo w to temporarily synchronize your collections as needed: CO Map myMap =
Collections.synchronizedMap (myMap); List myList = Collections.synchronizedList
(myList); Java arrays are even faster than using an ArrayList/Vector and perhaps
therefore may be preferable. ArrayList/Vector internally uses an array with some
convenient methods like add( ..), remove( ) etc. Q 14: Explain the Java
Collection framework? LF DP
Java 21 A 14: The key interfaces used by the collection framework are List, Set
and Map. The List and Set extends the Collection interface. Should not confuse
the Collection interface with the Colle ctions class which is a utility class. A
Set is a collection with unique elements and prevents duplication within the c
ollection. HashSet and TreeSet are implementations of a Set interface. A List is
a collection with an ordered s equence of elements and may contain duplicates.
ArrayList, LinkedList and Vector are implementations of a Li st interface. The
Collection API also supports maps, but within a hierarchy distinct from the
Collection interface. A Map is an object that maps keys to values, where the
list of keys is itself a collection o bject. A map can contain duplicate values,
but the keys in a map must be distinct. HashMap, TreeMap and Hashtable a re
implementations of a Map interface. How to implement collection ordering?
SortedSet and SortedMap interfaces maintai n sorted order. The classes, which
implement the Comparable interface, impose natural order. For cla sses that don
t implement comparable interface, or when one needs even more control over
ordering based on multiple attributes, a Comparator interface should be used.
Design pattern: What is an Iterator? An Iterator is a use once object to access
the objects stored in a collection. Iterator design pattern (aka Cursor) is
used, which is a behavioural design patt ern that provides a way to access
elements of a collection sequentially without exposing its internal representati
on. JAVA collection framework ex tends ArrayList AbstractCollection AbstractL
ist AbstractS et AbstractMap Ab stract Sequ en tial List LinkedList V ector
TreeS et HashS et TreeMap HashMap Weak HashMap Linked HashMap Id entity
HashMap < interface> So rted Map < in terface> So rted Set Linked HashS et <
interface> Collectio n < interface> List <interface> Set < interface> Map < in
terface> Random Acess < interface> Com p arato r Arrays implements Stack asList
java.util.Collections (Diagram sourced from:
http://www.wilsonmar.com/1arrays.htm) What are the benefits of the Java
collection framework? Collection framework pro vides flexibility, performance,
and robustness. . Polymorphic algorithms sorting, shuffling, reversing, binary
search etc.
. Set algebra - such as finding subsets, intersections, and unions between
objects . . Performance - collections have much better performance compared to
the older Vec tor and Hashtable classes with the elimination of synchronization
overheads. . Thread-safety -when synchronization is required, wrapper
implementations are pro vided for temporarily synchronizing existing collection
objects. . Immutability -when immutability is required wrapper implementations
are provided for making a collection immutable. . Extensibility - interfaces and
abstract classes provide an excellent starting po int for adding functionality
and features to create specialized object collections. Q 15: What are some of
the best practices relating to Java collection? BP PI CI A 15: .
Use ArrayLists, HashMap etc as opposed to Vector, Hashtable etc, where possible
to avoid any synchronization overhead. Even better is to use just arrays where
possible. If m ultiple threads concurrently access a collection and at least one
of the threads either adds or deletes an en try into the collection, then the
collection must be externally synchronized. This is achieved by: Map myMap =
Collections.synchronizedMap (myMap);
22 Java List myList = Collections.synchronizedList (myList); . Set the initial
capacity of a collection appropriately (e.g. ArrayList, HashMap etc). This is
because collection classes like ArrayList, HashMap etc must grow periodically to
accommodate new el ements. But if you have a very large array, and you know the
size in advance then you can speed things up by setting the initial size
appropriately. For example: HashMaps/Hashtables need to be created with
sufficiently large capacity to minim ise rehashing (which happens every time the
table grows). HashMap has two parameters initial capacity and load factor that
affect its performance and space requirements. Higher load fact or values
(default load factor of 0.75 provides a good trade off between performance and
space) will reduce the space cost but will increase the lookup cost of
myMap.get( ) and myMap.put( ) methods. When the number o f entries in the
HashMap exceeds the current capacity * loadfactor then the capacity of the HasMa
p is roughly doubled by calling the rehash function. It is also very important
not to set the initial ca pacity too high or load factor too low if iteration
performance or reduction in space is important. . Program in terms of interface
not implementation: For example you might decide a LinkedList is the best choice
for some application, but then later decide ArrayList might be a better c hoice
for performance reason. CO Use: List list = new ArrayList(100); //program in
terms of interface & set the initia l capacity. Instead of: ArrayList list = new
ArrayList(); ..Avoid storing unrelated or different types of objects into same
collection: Th is is analogous to storing items in pigeonholes without any
labelling. To store items use value objects or data objects (as oppose to
storing every attribute in an ArrayList or HashMap). Provide wrapper classes aro
und your collection API classes like ArrayList, Hashmap etc as shown in better
approach column. Also whe re applicable consider using composite design pattern,
where an object may represent a single object or a collection of objects. Refer
Q52 in Java section for UML diagram of a composite design pattern. CO Avoid
where possible Better approach The code below is hard to maintain and understand
by others. Also gets more complicated as the requirements
grow in the future because we are throwing different types of objects like
Integer, String etc into a list just based on the indices and it is easy to make
mistakes while casting the objects back during retrieval. When storing items
into a collection define value objects as shown below: (VO is an acronym for
Value Object). public class LineItemVO { private int itemId; private String
productName; List myOrder = new ArrayList() ResultSet rs = While (rs.hasNext())
{ List lineItem = new ArrayList(); lineItem.add (new
Integer(rs.getInt( itemId ))); lineItem.add (rs.getString( description )); .
myOrder.add( lineItem); } public int getLineItemId(){return accountId ;} public
int getAccountName(){return accountName;} public void setLineItemId(int
accountId ){ this.accountId = accountId } //implement other getter & setter
methods } Now let s define our base wrapper class, which represents an order:
public abstract class Order { int orderId; return myOrder; Example 2: List
myOrder = new ArrayList(10); //create an order OrderVO header = new OrderVO();
header.setOrderId(1001); //add all the line items LineItemVO line1 = new
LineItemVO(); line1.setLineItemId(1); LineItemVO line2 = new LineItemVO();
Line2.setLineItemId(2); List lineItems = null; public abstract int
countLineItems(); public abstract boolean add(LineItemVO itemToAdd); public
abstract boolean remove(LineItemVO itemToAdd); public abstract Iterator
getIterator(); public int getOrderId(){return this.orderId; } } Now a specific
implementation of our wrapper class: public class OverseasOrder extends Order
{ public OverseasOrder(int inOrderId) { this.lineItems = new ArrayList(10);
this.orderId = inOrderId; }
Java 23 List lineItems = new ArrayList(); lineItems.add(line1);
lineItems.add(line2); //to store objects myOrder.add(order);// index 0 is an
OrderVO object myOrder.add(lineItems);//index 1 is a List of line items //to
retrieve objects myOrder.get(0); myOrder.get(1); Above approaches are bad
because disparate objects are stored in the lineItem collection in example-1 and
example-2 relies on indices to store disparate objects. The indices based
approach and storing disparate objects are hard to maintain and understand
because indices are hardcoded and get scattered across the code. If an index
position changes for some reason, then you will have to change every occurence,
otherwise it breaks your application. The above coding approaches are analogous
to storing disparate items in a storage system without proper labelling and just
relying on its grid position. public int countLineItems() { //logic to count }
public boolean add(LineItemVO itemToAdd){ //additional logic or checks return
lineItems.add(itemToAdd); } public boolean remove(LineItemVO itemToAdd){ return
lineItems.remove(itemToAdd); } public ListIterator getIterator(){ return
lineItems.Iterator();} } Now to use: Order myOrder = new OverseasOrder(1234) ;
LineItemVO item1 = new LineItemVO(); Item1.setItemId(1);
Item1.setProductName( BBQ ); LineItemVO item2 = new LineItemVO();
Item1.setItemId(2); Item1.setProductName( Outdoor chair ); //to add line items
to order myOrder.add(item1); myOrder.add(item2); Q 16: When providing a user
defined key class for storing objects in the Hashmap s or Hashtables, what
methods do you have to provide or override (ie method overriding)? LF PI CO A
16: You should override the equals() and hashCode() methods from the Object cl
ass. The default implementation of the equals() and hashcode(), which are
inherited from the java.lang.Object uses an object instance s memory location
(e.g. MyObject@6c60f2ea). This can cause problems when two instances of the car
objects have the same color but the inherited equals() will return false because
it uses the memo ry location, which is different for the two instances. Also the
toString() method can be overridden to provide a pro per string representation
of your
object. Points to consider: If a class overrides equals(), it must override
hashCode(). If 2 objects are equal, then their hashCode values must be equal as
well. If a field is not used in equals(), then it must not be used in
hashCode(). If it is accessed often, hashCode() is a candidate for caching to
enhance perfor mance. Note: Java 1.5 introdces enumerated constants, which
improves readability and ma intainability of your code. Java programming
language enums are more powerful than their counterparts in other la nguages.
E.g. A class like Weather can be built on top of simple enum type Season and the
class Weather can be made immutable, and only one instance of each Weather can
be created, so that your Weather class does not have to override equals() and
hashCode() methods. public class Weather { public enum Season {WINTER, SPRING,
SUMMER, FALL} private final Season season; private static final List<Weather>
listWeather = new ArrayList<Weather> (); private Weather (Season season)
{ this.season = season;} public Season getSeason () { return season;} static
{ for (Season season : Season.values()) { listWeather.add(new
Weather(season)); } } public static ArrayList<Weather> getWeatherList ()
{ return listWeather; } public String toString(){ return season;} // takes
advantage of toString() metho d of Season. }
24 Java Q 17: What is the main difference between a String and a StringBuffer
class? LF PI CI CO A 17: String StringBuffer / StringBuilder String is
immutable: you can t modify a string StringBuffer is mutable: use String Buffer
or StringBuilder when you want to object but can replace it by creating a new
modify the contents. StringBuilder w as added in Java 5 and it is identical in
instance. Creating a new instance is rather all respects to StringBuffer except
that it is not synchronised, which makes expensive. it slightly faster at the
cost of not being thread-safe. //Inefficient version using immutable String
//More efficient version using muta ble StringBuffer String output = Some text
StringBuffer output = new StringBuffer(110); Int count = 100;
Output.append( Some text ); for(int I =0; i<count; i++) { for(int I =0; i<count;
i++) { output += i; output.append(i); } } return output; return
output.toString(); The above code would build 99 new String objects, of which 98
would be thrown away The above code creates only two new ob jects, the
StringBuffer and the final immediately. Creating new objects is not String that
is returned. StringBuffer e xpands as needed, which is costly efficient.
however, so it would be better to initilise the StringBuffer with the correct
size from the start as shown. Another important point is that creation of extra
strings is not limited to overl oaded mathematical operators ( + ) but there are
several methods like conact(), trim(), substring(), and replace() in S tring
classes that generate new string instances. So use StringBuffer or StringBuilder
for computation intensive operations, which offer better performance. Q 18: What
is the main difference between pass-by-reference and pass-by-value? L F PI A 18:
Other languages use pass-by-reference or pass-by-pointer. But in Java no m atter
what type of argument you pass the corresponding parameter (primitive variable
or object reference) will g et a copy of that data, which is exactly how pass-
by-value (ie copy-by-value) works. In Java, if a calling method passes a
reference of an object as an argument to t he called method then the passedin
reference gets copied first and then passed to the called method. Both the or
iginal reference that was passed-in and the copied reference will be pointing to
the same object. So no ma tter which reference you use, you will be always
modifying the same original object, which is how the pass-by-refe rence works as
well. ref d Pass-by-value for primitive variables vs Object references public
void first(){
int i= 10; int x = second(i); //A t this point //value of i is still 10 //value
of x is 11 } public int second(int k) { k++; return k ; } i = 10 k = 10 k = 11
Copy of i stores i copiesi acts on k ref public void first(){ Car c = new
Car("red") //A t this point //color is Red second(c); //A t this point //color
is Blu e } public void second(C ar d) { d.setC olor(blue); //color is blue } C
ar object S tring colo r = red ref c copyofc Primitive variables Object
references m odifies th e orig in al object through c opied referen ce m odifies
th e c opy k but no t th e orig inal. C hanges color = blue If your method call
involves inter-process (e.g. between two JVMs) communication , then the
reference of the calling method has a different address space to the called
method sitting in a s eparate processs (i.e separate JVM). Hence inter-process
communication involves calling method passing objects as arguments to called
method by-value in a serialized form, which can adversely affect performance due
to mar shalling and unmarshalling cost. Note: As discussed in Q69 in Enterprise
section, EJB 2.x introduced local interf aces, where enterprise beans that can
be used locally within the same JVM using Java s form of pass-by-reference,
hence improvin g performance.
to code but will have performance implications (Refer Q22 in Java section). to c
ode but will have performance implications (Refer Q22 in Java section). Java 25
Q 19: What is serialization? How would you exclude a field of a class from seria
lization or what is a transient variable? What is the common use? LF SI PI A 19:
Serialization is a process of reading or writing an object. It is a proces s of
saving an object s state to a sequence of bytes, as well as a process of
rebuilding those bytes back into a live object at some future time. An object is
marked serializable by implementing the java.io.Serializable interface, which is
only a marker interface -- it simply allows the serialization mechanism to
verify that the class can be persisted, ty pically to a file. byte stream
writeto Serialization File class Car implements Serializable { String color =
null; transient File fh = null; } Car Object1 Class Car implements Serializable
{ String color = null; } Car Object 2 deserialize serialize deserialize
Transient variables cannot be serialized. The fields marked transient in a seria
lizable object will not be transmitted in the byte stream. An example would be a
file handle or a database connection. Such objects are only meaningful locally.
So they should be marked as transient in a serializable clas s. Serialization
can adversely affect performance since it: .. Depends on reflection. . Has an
incredibly verbose data format. . Is very easy to send surplus data. When to use
serialization? Do not use serialization if you do not have to. A com mon use of
serialization is to use it to send an object over the network or if the state of
an object needs to be p ersisted to a flat file or a database. (Refer Q57 on
Enterprise section). Deep cloning or copy can be achieved through serialization.
This may be fast The objects stored in an HTTP session should be serializable to
support in-memor y replication of sessions to achieve scalability (Refer Q20 in
Enterprise section). Objects are passed in RMI (Remote Method Invocation)
across network using serialization (Refer Q57 in Enterprise section). Q 20:
Explain the Java I/O streaming concept and the use of the decorator design
pattern in Java I/O? LF DP A 20: tream There PI SI Java input and output is
defined in terms of an abstract concept called a , which is a sequence of data.
are 2 kinds of streams. s
. Byte streams (8 bit bytes) .. Abstract classes are: InputStream and
OutputStream . Character streams (16 bit UNICODE) .. Abstract classes are:
Reader and Writer Design pattern: java.io.* classes use the decorator design
pattern. The decorato r design pattern attaches responsibilities to objects at
runtime. Decorators are more flexible than inheri tance because the inheritance
attaches responsibility to classes at compile time. The java.io.* classes use th
e decorator pattern to construct different combinations of behaviour at runtime
based on some basic classes. Attaching responsibilities to classes at compile
time using subclassing. Attaching responsibilities to objects at runtime using a
decorator design pattern. Inheritance (aka subclassing) attaches
responsibilities to classes at compile time. When you extend a class, each
individual changes you make to child class will affect all instances of the
child classes. Defining many classes using inheritance to have all possible
combinations is problematic and inflexible. By attaching responsibilities to
objects at runtime, you can apply changes to each individual object you want to
change. File file = new File( c:/temp ); FileInputStream fis = new
FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis);
Decorators decorate an object by enhancing or restricting functionality of an
object it decorates. The decorators add or restrict functionality to decorated
26 Java objects either before or after forwarding the request. At runtime the
BufferedInputStream (bis), which is a decorator (aka a wrapper around decorated
object), forwards the method call to its decorated object FileInputStream (fis).
The bis will apply the additional functionality of buffering around the lower
level file (i.e. fis) I/O. java.lang.Object java.io.InputStream java.io.Reader
java.io.OutputStream java.io.Writer java.io.BefferedReader
java.io.InputStreamReader java.io.FileReader java.io.OutputStreamWriterr
java.io.FileWriter java.io.FileInputStream java.io.FileoutputStream
java.lang.System java.io.* class hierachy Note: Only a few sub classes of
abstract classes like InputStream are shown for clarity. The New I/O (NIO): more
scalabe and better performance Java has long been not suited for developing
programs that perform a lot of I/O operations. Furthermore, commonly needed
tasks such as file locking, non-blocking and asynchronous I/O op erations and
ability to map file to memory were not available. Non-blocking I/O operations
were achieved through work arounds such as multithreading or using JNI. The New
I/O API (aka NIO) in J2SE 1.4 has changed t his situation. A server s ability to
handle several client requests effectively depends on how it uses I/O streams.
When a server has to handle hundreds of clients simultaneously, it must be able
to use I/O ser vices concurrently. One way to cater for this scenario in Java is
to use threads but having almost one-to-one r atio of threads (100 clients will
have 100 threads) is prone to enormous thread overhead and can result in
performance and scalability problems due to consumption of memory stacks and CPU
context switching. To overcome this problem, a new set of non-blocking I/O
classes have been introduced to the Java platform in java.nio p ackage. The non-
blocking I/O mechanism is built around Selectors and Channels. Channels, Buffers
and Selector s are the core of the NIO. A Channel class represents a bi-
directional communication channel (similar to In putStrean and OutputStream)
between datasources such as a socket, a file, or an application component, which
is capable of performing one or more I/O operations such as reading or writing.
Channels can be non-blocking, wh ich means, no I/O operation will wait for data
to be read or written to the network. The good thing about NIO cha nnels is that
they can be asynchronously interrupted and closed. So if a thread is blocked in
an I/O opera tion on a channel, another thread can interrupt that blocked
thread. Buffers hold data. Channels can fill and drain Buffers. Buffers replace
the need for you to do your own buffer management using byte arrays. There are
different types of Buffers like ByteBuff
er, CharBuffer, DoubleBuffer, etc. A Selector class is responsible for
multiplexing (combining multiple streams int o a single stream) by allowing a
single thread to service multiple channels. Each Channel registers events with a
Selector. When events arrive from clients, the Selector demultiplexes
(separating a single stream into multip le streams) them and dispatches the
events to corresponding Channels. To achieve non-blocking I/O a Channel clas s
must work in conjunction with a Selector class. Design pattern: NIO uses a
reactor design pattern, which demultiplexes events (s eparating single stream
into multiple streams) and dispatches them to registered object handlers. The
reactor pattern is similar to an observer pattern (aka publisher and subscriber
design pattern), but an observer pattern h andles only a single source of events
(i.e a single publisher with multiple subscribers) where a reactor patter n
handles multiple event sources (i.e. multiple publishers with multiple
subscribers). The intent of an observer pattern is to define a one-to-many
depndency so that when one object (i.e the publisher) changes its state, all its
dependents (i.e all its subscribers) are notfied and updated correspondingly.
Another sought after functionality of NIO is its ability to map a file to memory
. There is a specialized form of a Buffer known as MappedByteBuffer, which
represents a buffer of bytes mapped to a file. To map a file to
Java 27 MappedByteBuffer, you must first get a channel for a file. Once you get
a channe l then you map it to a buffer and subsequently you can access it like
any other ByteBuffer. Once you map an input file to a CharBuffer, you can do
pattern matching on the file contents. This is similar to running grep on a UNIX
f ile system. Another feature of NIO is its ability to lock and unlock files.
Locks can be exc lusive or shared and can be held on a contiguous portion of a
file. But file locks are subject to the control of the u nderlying operating
system. Q 21: How can you improve Java I/O performance? PI BP A 21: Java
applications that utilise Input/Output are excellent candidates for p erformance
tuning. Profiling of Java applications that handle significant volumes of data
will show significant time spent in I/O operations. This means substantial gains
can be had from I/O performance tuning. Therefore, I/O efficie ncy should be a
high priority for developers looking to optimally increase performance. The
basic rules for speeding up I/O performance are . Minimise accessing the hard
disk. . Minimise accessing the underlying operating system. . Minimise
processing bytes and characters individually. Let us look at some of the
techniques to improve I/O performance. CO .. Use buffering to minimise disk
access and underlying operating system. As sho wn below, with buffering large
chunks of a file are read from a disk and then accessed a byte or characte r at
a time. W ithout buffering : inefficient code try{ File f = new File("m
yFile.txt"); FileInputStream fis = new FileInputStream (f); int count = 0; int b
= ; while((b = fis.read()) != -1){ if(b== 'n') { count++; } } // fis should be
closed in a finally block. fis.close() ; } catch(IO Exception io){} Note:
fis.read() is a native m ethod call to the underlying system . W ith B uffering:
yields better perform ance try{
File f = new File("myFile.txt"); FileInputStream fis = new FileInputStream (f);
BufferedInputStream bis = new BufferedInputStream (fis); int count = 0; int b
= ; while((b = bis.read()) != -1){ if(b== 'n') { count++; } } //bis should be
closed in a finally block. bis.close() ; } catch(IO Exception io){} Note:
bis.read() takes the next byte from the input buffer and only rarely access the
underlying operating system . Instead of reading a character or a byte at a
time, the above code with bufferin g can be improved further by reading one line
at a time as shown below: FileReader fr = new FileReader(f); BufferedReader br =
new BufferedReader(fr); While (br.readLine() != null) count++; By default the
System.out is line buffered, which means that the output buffer i s flushed when
a new line character is encountered. This is required for any interactivity
between an inpu t prompt and display of output. The line buffering can be
disabled for faster I/O operation as follows: FileOutputStream fos = new
FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos,
1024); PrintStream ps = new PrintStream(bos,false); System.setOut(ps); while
(someConditionIsTrue) System.out.println( blah blah ); } It is recommended to
use logging frameworks like Log4J or apache commons logging , which uses
buffering instead of using default behaviour of System.out.println( ..) for
better performance. Frameworks like Log4J are configurable, flexible, extensible
and easy to use.
28 Java . Use the NIO package, if you are using JDK 1.4 or later, which uses
performance-e nhancing features like buffers to hold data, memory mapping of
files, non-blocking I/O operations etc. . I/O performance can be improved by
minimising the calls to the underlying operat ing systems. The Java runtime
itself cannot know the length of a file, querying the file system for is
Directory(), isFile(), exists() etc must query the underlying operating
system. . Where applicable caching can be used to improve performance by reading
in all th e lines of a file into a Java collection class like an ArrayList or a
HashMap and subsequently access the data from an in-memory collection instead of
the disk. Q 22: What is the main difference between shallow cloning and deep
cloning of ob jects? DC LF MI PI A 22: The default behaviour of an object s
clone() method automatically yields a s hallow copy. So to achieve a deep copy
the classes must be edited or adjusted. Shallow copy: If a shallow copy is
performed on obj-1 as shown in fig-2 then it is copied but its contained objects
are not. The contained objects Obj-1 and Obj-2 are affected by changes to cloned
Obj-2. Java supports shallow cloning of objects by default when a class
implements the java.lang.Cloneable in terface. Deep copy: If a deep copy is
performed on obj-1 as shown in fig-3 then not only obj-1 has been copied but the
objects contained within it have been copied as well. Serialization can be used
to achieve deep cloning. Deep cloning through serialization is faster to develop
and easier to maintain but ca rries a performance overhead. Fig-2:Shallow
cloning Fig-3:Deep cloning Shallow Vs Deep cloning Obj-1 c ontaine d Obj-1
contained Obj-2 Fig-1:O riginal O bject contains contains Obj-1 C loned Obj-2 c
ontaine d Obj-1 contained Obj-2 Obj-1 c ontained Obj-1 c ontained
Obj-2 C loned Obj-2 contain ed Obj-1 contained Obj-2 For example, invoking
clone() method on a HashMap returns a shallow copy of Hash Map instance, which
means the keys and values themselves are not cloned. If you want a deep copy
then a si mple method is to serialize the HashMap to a ByteArrayOutputSream and
then deserialize it. This creates a de ep copy but does require that all keys
and values in the HashMap are Serializable. Its primary advantage is th at it
will deep copy any arbitrary object graph. List some of the methods supported by
Java object class? clone(), toString(), eq uals(Object obj), hashCode() .. refer
Q16 in Java section, wait(), notify() .. refer Q42 in Java section, fin alize()
etc. Q 23: What is the difference between an instance variable and a static
variable? Give an example where you might use a static variable? LF A 23: Static
variable Instance variable Class variables are called static variables. There is
only one occurrence of a class variable per JVM per class loader. When a class
is loaded the class variables (aka static variables) are initialised. Instance
variables are non-static and there is one occurrence of an instance variable in
each class instance (ie each object). A static variable is used in the singleton
pattern. (Refer Q45 in Java section). A static variable is used with a final
modifier to define constants. Q 24: Give an example where you might use a static
method? LF
Java 29 A 24: Static methods prove useful for creating utility classes,
singleton classe s and factory methods (Refer Q45, Q46 in Java section). Utility
classes are not meant to be instantiated. Improper coding of utility classes can
lead to procedural coding. java.lang.Math, java.util.Collections etc are
examples of uti lity classes in Java. Q 25: What are access modifiers? LF A 25:
Modifier Used with Description public Outer classes, interfaces, constructors,
Inner classes, methods and field variables A class or interface may be accessed
from outside the package. Constructors, inner classes, methods and field
variables may be accessed wherever their class is accessed. protected
Constructors, inner classes, methods, and field variables. Accessed by other
classes in the same package or any subclasses of the class in which they are
referred (ie same package or different package). private Constructors, inner
classes, methods and field variables, Accessed only within the class in which
they are declared No modifier: (Package by default). Outer classes, inner
classes, interfaces, constructors, methods, and field variables Accessed only
from within the package in which they are declared. Q 26: Where and how can you
use a private constructor? LF A 26: Private constructor is used if you do not
want other classes to instantiat e the object. The instantiation is done by a
public static method within the same class. . Used in the singleton pattern.
(Refer Q45 in Java section). . Used in the factory method pattern (Refer Q46 in
Java section). . Used in utility classes e.g. StringUtils etc. Q 27: What is a
final modifier? Explain other Java modifiers? LF A 27: A final class can t be
extended i.e. A final class may not be subclassed. A final method can t be
overridden when its class is inherited. You can t change value of a final
variable (i.e. it is a c onstant). Modifier Class Method Property static A
static inner class is just an inner class associated with
the class, rather than with an instance. cannot be instantiated, are called by
classname.method, can only access static variables Only one instance of the
variable exists. abstract Cannot be instantiated, must be a superclass, used
whenever one or more methods are abstract. Method is defined but contains no
implementation code (implementation code is included in the subclass). If a
method is abstract then the entire class must be abstract. N/A synchronized N/A
Acquires a lock on the class for static methods. Acquires a lock on the instance
for non-static methods. N/A transient N/A N/A Field should not be serialized.
final Class cannot be inherited Method cannot be overridden Makes the variable a
constant. native N/A Platform dependent. No body, only signature. N/A Note: Be
prepared for tricky questions on modifiers like, what is a volatile ? Or w hat
is a const ? Etc. The reason it is tricky is that Java does have these keywords
const and volatile as reserved, which means you c an t name your variables with
these names but modifier const is not yet added in the language and the modifier
volatile is very rarely used. The volatile modifier is used on member variables
that may be modified simultaneou sly by other threads. Since other threads
cannot see local variables, there is no need to mark local varibles as volatile.
E.g. volatile int number; volatile private List listItems = null; etc. The
modifier volatile only synchronizes the variable mark ed as volatile whereas
synchronized modifier synchronizes all variables. Java uses the final modifier
to declare constants. A final variable or constant declared as final has a value
that is immutable and cannot be modified to refer to any other objects other
than one it was initi alized to refer to. So the final modifier applies only to
the value of the variable itself, and not to the object referenced by the var
iable. This is where the const modifier can come in very useful if added to the
Java language. A reference variable or a constant ma rked as const refers to an
immutable object that cannot be modified. The reference variable itself can be
modified, if it is not marked as final . The const modifier will be applicable
only to non-primitive types. The primitive types should continue to u se the
modifier final .
30 Java Q 28: What is the difference between final, finally and finalize() in
Java? LF A 28: . final - constant declaration. Refer Q27 in Java section. .
finally - handles exception. The finally block is optional and provides a mechan
ism to clean up regardless of what happens within the try block (except
System.exit(0) call). Use the finally block to close files or to release other
system resources like database connections, statements etc. (Refer Q45 in
Enterprise section) . finalize() - method helps in garbage collection. A method
that is invoked before an object is discarded by the garbage collector, allowing
it to clean up its state. Should not be used to rele ase non-memory resources
like file handles, sockets, database connections etc because Java has only a
finite n umber of these resources and you do not know when the garbage
collection is going to kick in to release these non-memory resources through the
finalize() method. Q 29: How does Java allocate stack and heap memory? Explain
re-entrant, recursiv e and idempotent methods/functions? MI CI A 29: Each time
an object is created in Java it goes into the area of memory kno wn as heap. The
primitive variables like int and double are allocated in the stack, if they are
local method variables an d in the heap if they are member variables (i.e.
fields of a class). In Java methods local variables are pushed i nto stack when
a method is invoked and stack pointer is decremented when a method call is
completed. In a multi-thr eaded application each thread will have its own stack
but will share the same heap. This is why care should be taken in your code to
avoid any concurrent access issues in the heap space. The stack is threadsafe
(each thread will have its own stack) but the heap is not threadsafe unless
guarded with synchronisation through your code. A method in stack is reentrant
allowing multiple concurrent invocations that do not interfere with each other.
A function is recursive if it calls itself. Given enough stack space, recursive
me thod calls are perfectly valid in Java though it is tough to debug. Recursive
functions are useful in removing iteratio ns from many sorts of algorithms. All
recursive functions are re-entrant but not all re-entrant functions are recursiv
e. Idempotent methods are methods, which are written in such a way that repeated
calls to the same method with the same arguments yield same results. For example
clustered EJBs, which are written with idempotent methods, can automatically
recover from a
server failure as long as it can reach another server. Jav a st ack & h e a p m
e m o r y a l l o ca t i o n St a c k He a p p ubl i c c las s S t ac kR ef { p
u b lic v o id f i r s t ( ) { s e c o n d ( ) ; //a f t e r } p u b lic v o id
s e c o n d ( ) { C a r c = n e w C a r ( ) ; } } s e c ond( ) fi r s t( ) s e c
ond( ) r e f c fi r s t( ) Ca r 1 2 3 4 Re f p ubl i c c las s H eapR ef { C a r
c = n e w C a r( ); p u b lic v o id f i r s t ( ) { c = N e w C a r(); } } Ca r
c Re f Ca r c Ca r 2 1 fi r s t( ) Q 30: Explain Outer and Inner classes (or
Nested classes) in Java? When will you use an Inner Class? LF
Java 31 A 30: In Java not all classes have to be defined separate from each
other. You c an put the definition of one class inside the definition of another
class. The inside class is called an inner class and t he enclosing class is
called an outer class. So when you define an inner class, it is a member of the
outer class in m uch the same way as other members like attributes, methods and
constructors. Where should you use inner classes? Code without inner classes is
more maintaina ble and readable. When you access private data members of the
outer class, the JDK compiler creates pac kage-access member functions in the
outer class for the inner class to access the private members. This leave s a
security hole. In general we should avoid using inner classes. Use inner class
only when an inner class is on ly relevant in the context of the outer class
and/or inner class can be made private so that only outer class can access it.
Inner classes are used primarily to implement helper classes like Iterators,
Comparators etc which are used in the context of an outer class. CO Member inner
class Anonymous inner class public class MyStack { private Object[] items =
null; public Iterator iterator() { return new StackIterator(); } //inner class
class StackIterator implements Iterator{ public boolean hasNext(){ } } } public
class MyStack { private Object[] items = null; public Iterator iterator()
{ return new Iterator { public boolean hasNext() { } } } } Explain outer and
inner classes? Class Type Description Example + Class name Outer Package Top
level class. Only type JVM //package scope class member class or interface can
recognize. class Outside{} Outside.class Inner static nested Defined within the
context of the //package scope class class or
interface top-level class. Must be static & can access static members of its
containing class. No relationship between the instances of outside and Inside
classes. class Outside { static class Inside{ } } Outside.class
,Outside$Inside.class Inner Member class Defined within the context of class
Outside{ class outer class, but non-static. Until an object of Outside class has
been created you can t create Inside. class Inside(){} } Outside.class ,
Outside$Inside.class Inner class Local class Defined within a block of code. Can
use final local variables and final method parameters. Only visible within the
block of code that defines it. class Outside { void first() { final int i = 5;
class Inside{} } } Outside.class , Outside$1$Inside.class Inner class Anonymous
class Just like local class, but no name is used. Useful when only one instance
is used in a method. Most commonly used in AWT event model. class Outside{ void
first() { button.addActionListener ( new ActionListener() { public void
actionPerformed(ActionEvent e) { System.out.println( The button was
pressed! ); } }); } } Outside.class , Outside$1.class
32 Java Q 31: What is type casting? Explain up casting vs down casting? When do
you get ClassCastException? LF DP A 31: Type casting means treating a variable
of one type as though it is another type. When up casting primitives as shown
below from left to right, automatic conversi on occurs. But if you go from right
to left, down casting or explicit casting is required. Casting in Java is safer
than in C or other languages that allow arbitrary casting. Java only lets casts
occur when they make sense, such a s a cast between a float and an int. However
you can't cast between an int and a String (is an object in Java). byte .. short
.. int .. long .. float .. double int i = 5; long j = i; //Right. Up casting or
implicit casting byte b1 = i; //Wrong. Compile time error Type Mismatch . byte
b2 = (byte) i ; //Right. Down casting or explicit casting is required. When it
comes to object references you can always cast from a subclass to a supe rclass
because a subclass object is also a superclass object. You can cast an object
implicitly to a super class type (ie upcasting). If this were not the case
polymorphism wouldn t be possible. Ob je c t Ve h ic le Ca r Bu s BM W Vehicle
v1 = new Car(); //Right.upcasting or implicit casting Vehicle v2 = new V
ehicle(); Car c0 = v1; //W rong. com pile tim e error "Type M ism atch".
//Explicit or down casting is required Car c1 = (Car)v1; // Right. down casting
or explicit casting. // v1 has knowledge of Car due to line1 Car c2 =
(Car)v2; //W rong. R untim e exception ClassCastE xception //v2 has no knowledge
of Car. Bus b1 = new BM W (); //W rong. com pile tim e error "Type M ism atch"
Car c3 = new BMW (); //Right.upcasting or implicit casting Car c4 = (BMW )
v1; //W rong. Runtime exception ClassC astException Object o = v1; //v1 can only
be upcast to its parent or Car c5 = (Car)v1; //v1 can be down cast to Car due to
line 1. U p ca st in g vs D o w n ca st in g O b je c ts You can cast down the
hierarchy as well but you must explicitly write the cast a nd the object must be
a legitimate instance of the class you are casting to. The ClassCastException is
t hrown to indicate that code has attempted to cast an object to a subclass of
which it is not an instance. We can deal with the problem of incorrect casting
in two ways: . Use the exception handling mechanism to catch ClassCastException.
try{ Object o = new Integer(1);
System.out.println((String) o); } catch(ClassCastException cce)
{ logger.log( Invalid casting, String is expected Not an Integer );
System.out.println(((Integer) o).toString()); } .. Use the instanceof statement
to guard against incorrect casting. If(v2 instanceof Car) { Car c2 = (Car) v2; }
Design pattern: The instanceof and typecast constructs are shown for the
illustration purpose only.
Using these constructs can be unmaintainable due to large if and elseif statemen
ts and can affect performance if used in frequently accessed methods or loops.
Look at using visit or design pattern to avoid these constructs. (Refer Q11 in
How would you go about section ).
Java 33 Points-to-ponder: We can also get a ClassCastException when two
different class loaders load the same class because they are treated as two
different classes. Q 32: What do you know about the Java garbage collector? When
does the garbage c ollection occur? Explain different types of references in
Java? LF MI A 32: Each time an object is created in Java, it goes into the area
of memory kn own as heap. The Java heap is called the garbage collectable heap.
The garbage collection cannot be forced. The garba ge collector runs in low
memory situations. When it runs, it releases the memory allocated by an unreacha
ble object. The garbage collector runs on a low priority daemon (background)
thread. You can nicely ask the garbage collector to collect garbage by calling
System.gc() but you can t force it. What is an unreachable object? An object s
life has no meaning unless something ha s reference to it. If you can t reach it
then you can t ask it to do anything. Then the object becomes unreach able and
the garbage collector will figure it out. Java automatically collects all the
unreachable objects peri odically and releases the memory consumed by those
unreachable objects to be used by the future reachable objects . G a r b a g e C
o l l e c t i on & U n r e a c ha bl e O b j e c t s re a c h a b l e re a c h a
b l e C ase 1 C a r a = n e w C a r(); Ca r b = n e w Ca r ( ) 1r e f a C a r
obj ec t 2r e f b C a r obj ec t C ase 2 a = n e w Ca r ( ) re a c h a b l e re
a c h a b l e unr e a c h a b l e 2r e f b Ca r o b j e c t 3r e f a Ca r o b j
e c t 1 Ca r o b j e c t C ase 3 a = b un r e a c h a bl e re a c h a b l e u n
r ea c h ab l e refa Ca r o b j e c t r e f b Ca r o b j e c t 1
C a r obj ec t 2 3 C ase 4 a = n u l l ; b = n u l l ; unr e a c h a bl e un r e
a c h a bl e u n r ea ch ab l e Ca r o b j e c t Ca r o b j e c t 1 C a r obj ec
t 2 3 He a p We can use the following options with the Java command to enable
tracing for gar bage collection events. -verbose:gc reports on each garbage
collection event. Explain types of references in Java? java.lang.ref package can
be used to declar e soft, weak and phantom references. . Garbage Collector won t
remove a strong reference. .. A soft reference will only get removed if memory
is low. So it is useful for implementing caches while avoiding memory leaks. ..
A weak reference will get removed on the next garbage collection cycle. Can b e
used for implementing canonical maps. The java.util.WeakHashMap implements a
HashMap with keys held by weak references. .. A phantom reference will be
finalized but the memory will not be reclaimed. C an be useful when you want to
be notified that an object is about to be collected. Q 33: If you have a
circular reference of objects, but you no longer reference i t from an execution
thread, will this object be a potential candidate for garbage collection? LF MI
34 Java A 33: Yes. Refer diagram below. Garbage Collecting Circular References
sample code public void buildCar() { Car c = new Car(); Engine e = new Engine();
//lets create a circular reference c.engine = e; e.car = c; } buildCar() Stack
Heap Car Engine Before buildCar() returns After buildCar() returns Stack Heap
Car Engine Both the Car & Engine are not reachable and potential candidate for
Garbage Collection. Q 34: Discuss the Java error handling mechanism? What is the
difference between Runtime (unchecked) exceptions and checked exceptions? What
is the implication of catching all the exceptions w ith the type Exception ? EH
BP A 34: Errors: When a dynamic linking failure or some other hard failure in
the virtual m achine occurs, the virtual machine throws an Error. Typical Java
programs should not catch Errors. In addit ion, it s unlikely that typical Java
programs will ever throw Errors either. Exceptions: Most programs throw and
catch objects that derive from the Exception class. Exceptions indicate that a
problem occurred but that the problem is not a serious JVM problem. An Ex
ception class has many various types ofsubclasses. These descendants
indicateexceptions that can occur. For example, NegativeArraySizeException
indicates that a program attempted to create an array with a negative size. One
exception subclass has special meaning in the Java language: RuntimeException. A
ll the exceptions except RuntimeException are compiler checked exceptions. If a
method is capable of thro wing a checked exception it must declare it in its
method header or handle it in a try/catch block. Failure to do so raises a
compiler error. So checked exceptions can, at compile time, greatly reduce the
occurence of unhandl ed exceptions surfacing at runtime in a given application
at the expense of requiring large throws declarat ions and encouraging use of
poorlyconstructed try/catch blocks. Checked exceptions are present in other
languages like C++, C#, and Python.
Throw a b le and its subc la s s e s Ob je ct E xceptio n Erro r T h ro w able R
untim eE xc eptio n IO E xceptio n N u llP o in te rE xc e p tio n LinkageE rro
r Runtime Exceptions (unchecked exception) A RuntimeException class represents
exceptions that occur within the Java virtua l machine (during runtime). An
example of a runtime exception is NullPointerException. The cost of checking for
the runtime exception often outweighs the benefit of catching it. Attempting to
catch or specify all of them all the time would make your code unreadable and
unmaintainable. The compiler allows runtime exceptions to go unca ught and
unspecified. If you
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book
82747038 preview-java-j2 ee-book

More Related Content

Viewers also liked

Viewers also liked (6)

P._Perehinec_3-30-16
P._Perehinec_3-30-16P._Perehinec_3-30-16
P._Perehinec_3-30-16
 
234622607 olga-tellis-case
234622607 olga-tellis-case234622607 olga-tellis-case
234622607 olga-tellis-case
 
A two stage svm-based mammographic cbir for ca dx
A two stage svm-based mammographic cbir for ca dxA two stage svm-based mammographic cbir for ca dx
A two stage svm-based mammographic cbir for ca dx
 
BALJINDER kUMAR
BALJINDER kUMARBALJINDER kUMAR
BALJINDER kUMAR
 
SOHO
SOHOSOHO
SOHO
 
desktop support
desktop supportdesktop support
desktop support
 

Similar to 82747038 preview-java-j2 ee-book

Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007Arun Kumar
 
Java j2ee interview_questions
Java j2ee interview_questionsJava j2ee interview_questions
Java j2ee interview_questionsppratik86
 
Java j2 ee job interview companion k.arulkumaran
Java j2 ee job interview companion   k.arulkumaranJava j2 ee job interview companion   k.arulkumaran
Java j2 ee job interview companion k.arulkumaranRama Krishnan L
 
Java Training Institute in Gurgaon.pptx
Java Training Institute in Gurgaon.pptxJava Training Institute in Gurgaon.pptx
Java Training Institute in Gurgaon.pptxAPTRON Gurgaon
 
Java Course for Beginners at Texceed
Java Course for Beginners at TexceedJava Course for Beginners at Texceed
Java Course for Beginners at TexceedSamidha Takle
 
Developers Nepal Meetup #4 Report
Developers Nepal Meetup #4 ReportDevelopers Nepal Meetup #4 Report
Developers Nepal Meetup #4 ReportPunit Jajodia
 
Learn Java Programming Language In Gurgaon.pptx
Learn Java Programming Language In Gurgaon.pptxLearn Java Programming Language In Gurgaon.pptx
Learn Java Programming Language In Gurgaon.pptxAPTRON Gurgaon
 
Hiring Java Developers A Comprehensive Guide for Success.pdf
Hiring Java Developers A Comprehensive Guide for Success.pdfHiring Java Developers A Comprehensive Guide for Success.pdf
Hiring Java Developers A Comprehensive Guide for Success.pdfAIS Technolabs Pvt Ltd
 
Javamagazine Mayo Junio 2013
Javamagazine Mayo Junio 2013Javamagazine Mayo Junio 2013
Javamagazine Mayo Junio 2013Erik Gur
 
7 Common Java Coding Interview Questions With Answers
7 Common Java Coding Interview Questions With Answers7 Common Java Coding Interview Questions With Answers
7 Common Java Coding Interview Questions With AnswersJAMESJOHN130
 
Java design pattern tutorial
Java design pattern tutorialJava design pattern tutorial
Java design pattern tutorialAshoka Vanjare
 
Design pattern tutorial
Design pattern tutorialDesign pattern tutorial
Design pattern tutorialRadouane23
 
On Selecting JavaScript Frameworks (Women Who Code 10/15)
On Selecting JavaScript Frameworks (Women Who Code 10/15)On Selecting JavaScript Frameworks (Women Who Code 10/15)
On Selecting JavaScript Frameworks (Women Who Code 10/15)Zoe Landon
 
Software testing career growth path explained
Software testing career growth path explainedSoftware testing career growth path explained
Software testing career growth path explainedintervietips
 
Top 10 Interview Questions for Coding Job.docx
Top 10 Interview Questions for Coding Job.docxTop 10 Interview Questions for Coding Job.docx
Top 10 Interview Questions for Coding Job.docxSurendra Gusain
 
Top 10 Interview Questions for Coding Job.docx
Top 10 Interview Questions for Coding Job.docxTop 10 Interview Questions for Coding Job.docx
Top 10 Interview Questions for Coding Job.docxSurendra Gusain
 
Greythorn Whiteboard Interview Guide
Greythorn Whiteboard Interview GuideGreythorn Whiteboard Interview Guide
Greythorn Whiteboard Interview GuideVaco Seattle
 

Similar to 82747038 preview-java-j2 ee-book (20)

Java/J2EE CV Guide
Java/J2EE CV GuideJava/J2EE CV Guide
Java/J2EE CV Guide
 
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
Lulu.com.java.j2 ee.job.interview.companion.2nd.edition.apr.2007
 
Java j2ee interview_questions
Java j2ee interview_questionsJava j2ee interview_questions
Java j2ee interview_questions
 
Imp Book
Imp BookImp Book
Imp Book
 
JavaFAQS
JavaFAQSJavaFAQS
JavaFAQS
 
Java j2 ee job interview companion k.arulkumaran
Java j2 ee job interview companion   k.arulkumaranJava j2 ee job interview companion   k.arulkumaran
Java j2 ee job interview companion k.arulkumaran
 
Java Training Institute in Gurgaon.pptx
Java Training Institute in Gurgaon.pptxJava Training Institute in Gurgaon.pptx
Java Training Institute in Gurgaon.pptx
 
Java Course for Beginners at Texceed
Java Course for Beginners at TexceedJava Course for Beginners at Texceed
Java Course for Beginners at Texceed
 
Developers Nepal Meetup #4 Report
Developers Nepal Meetup #4 ReportDevelopers Nepal Meetup #4 Report
Developers Nepal Meetup #4 Report
 
Learn Java Programming Language In Gurgaon.pptx
Learn Java Programming Language In Gurgaon.pptxLearn Java Programming Language In Gurgaon.pptx
Learn Java Programming Language In Gurgaon.pptx
 
Hiring Java Developers A Comprehensive Guide for Success.pdf
Hiring Java Developers A Comprehensive Guide for Success.pdfHiring Java Developers A Comprehensive Guide for Success.pdf
Hiring Java Developers A Comprehensive Guide for Success.pdf
 
Javamagazine Mayo Junio 2013
Javamagazine Mayo Junio 2013Javamagazine Mayo Junio 2013
Javamagazine Mayo Junio 2013
 
7 Common Java Coding Interview Questions With Answers
7 Common Java Coding Interview Questions With Answers7 Common Java Coding Interview Questions With Answers
7 Common Java Coding Interview Questions With Answers
 
Java design pattern tutorial
Java design pattern tutorialJava design pattern tutorial
Java design pattern tutorial
 
Design pattern tutorial
Design pattern tutorialDesign pattern tutorial
Design pattern tutorial
 
On Selecting JavaScript Frameworks (Women Who Code 10/15)
On Selecting JavaScript Frameworks (Women Who Code 10/15)On Selecting JavaScript Frameworks (Women Who Code 10/15)
On Selecting JavaScript Frameworks (Women Who Code 10/15)
 
Software testing career growth path explained
Software testing career growth path explainedSoftware testing career growth path explained
Software testing career growth path explained
 
Top 10 Interview Questions for Coding Job.docx
Top 10 Interview Questions for Coding Job.docxTop 10 Interview Questions for Coding Job.docx
Top 10 Interview Questions for Coding Job.docx
 
Top 10 Interview Questions for Coding Job.docx
Top 10 Interview Questions for Coding Job.docxTop 10 Interview Questions for Coding Job.docx
Top 10 Interview Questions for Coding Job.docx
 
Greythorn Whiteboard Interview Guide
Greythorn Whiteboard Interview GuideGreythorn Whiteboard Interview Guide
Greythorn Whiteboard Interview Guide
 

More from homeworkping3

238304497 case-digest
238304497 case-digest238304497 case-digest
238304497 case-digesthomeworkping3
 
238247664 crim1 cases-2
238247664 crim1 cases-2238247664 crim1 cases-2
238247664 crim1 cases-2homeworkping3
 
238234981 swamping-and-spoonfeeding
238234981 swamping-and-spoonfeeding238234981 swamping-and-spoonfeeding
238234981 swamping-and-spoonfeedinghomeworkping3
 
238218643 jit final-manual-of-power-elx
238218643 jit final-manual-of-power-elx238218643 jit final-manual-of-power-elx
238218643 jit final-manual-of-power-elxhomeworkping3
 
238103493 stat con-cases-set
238103493 stat con-cases-set238103493 stat con-cases-set
238103493 stat con-cases-sethomeworkping3
 
238097308 envi-cases-full
238097308 envi-cases-full238097308 envi-cases-full
238097308 envi-cases-fullhomeworkping3
 
238057020 envi-air-water
238057020 envi-air-water238057020 envi-air-water
238057020 envi-air-waterhomeworkping3
 
238019494 rule-06-kinds-of-pleadings
238019494 rule-06-kinds-of-pleadings238019494 rule-06-kinds-of-pleadings
238019494 rule-06-kinds-of-pleadingshomeworkping3
 
237978847 pipin-study-7
237978847 pipin-study-7237978847 pipin-study-7
237978847 pipin-study-7homeworkping3
 
237962770 arthur-lim-et-case
237962770 arthur-lim-et-case237962770 arthur-lim-et-case
237962770 arthur-lim-et-casehomeworkping3
 
237778794 ethical-issues-case-studies
237778794 ethical-issues-case-studies237778794 ethical-issues-case-studies
237778794 ethical-issues-case-studieshomeworkping3
 
237754196 case-study
237754196 case-study237754196 case-study
237754196 case-studyhomeworkping3
 
237750650 labour-turnover
237750650 labour-turnover237750650 labour-turnover
237750650 labour-turnoverhomeworkping3
 
237712710 case-study
237712710 case-study237712710 case-study
237712710 case-studyhomeworkping3
 
237654933 mathematics-t-form-6
237654933 mathematics-t-form-6237654933 mathematics-t-form-6
237654933 mathematics-t-form-6homeworkping3
 

More from homeworkping3 (20)

238304497 case-digest
238304497 case-digest238304497 case-digest
238304497 case-digest
 
238247664 crim1 cases-2
238247664 crim1 cases-2238247664 crim1 cases-2
238247664 crim1 cases-2
 
238234981 swamping-and-spoonfeeding
238234981 swamping-and-spoonfeeding238234981 swamping-and-spoonfeeding
238234981 swamping-and-spoonfeeding
 
238218643 jit final-manual-of-power-elx
238218643 jit final-manual-of-power-elx238218643 jit final-manual-of-power-elx
238218643 jit final-manual-of-power-elx
 
238103493 stat con-cases-set
238103493 stat con-cases-set238103493 stat con-cases-set
238103493 stat con-cases-set
 
238097308 envi-cases-full
238097308 envi-cases-full238097308 envi-cases-full
238097308 envi-cases-full
 
238057402 forestry
238057402 forestry238057402 forestry
238057402 forestry
 
238057020 envi-air-water
238057020 envi-air-water238057020 envi-air-water
238057020 envi-air-water
 
238056086 t6-g6
238056086 t6-g6238056086 t6-g6
238056086 t6-g6
 
238019494 rule-06-kinds-of-pleadings
238019494 rule-06-kinds-of-pleadings238019494 rule-06-kinds-of-pleadings
238019494 rule-06-kinds-of-pleadings
 
237978847 pipin-study-7
237978847 pipin-study-7237978847 pipin-study-7
237978847 pipin-study-7
 
237968686 evs-1
237968686 evs-1237968686 evs-1
237968686 evs-1
 
237962770 arthur-lim-et-case
237962770 arthur-lim-et-case237962770 arthur-lim-et-case
237962770 arthur-lim-et-case
 
237922817 city-cell
237922817 city-cell237922817 city-cell
237922817 city-cell
 
237778794 ethical-issues-case-studies
237778794 ethical-issues-case-studies237778794 ethical-issues-case-studies
237778794 ethical-issues-case-studies
 
237768769 case
237768769 case237768769 case
237768769 case
 
237754196 case-study
237754196 case-study237754196 case-study
237754196 case-study
 
237750650 labour-turnover
237750650 labour-turnover237750650 labour-turnover
237750650 labour-turnover
 
237712710 case-study
237712710 case-study237712710 case-study
237712710 case-study
 
237654933 mathematics-t-form-6
237654933 mathematics-t-form-6237654933 mathematics-t-form-6
237654933 mathematics-t-form-6
 

Recently uploaded

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxAnaBeatriceAblay2
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 

Recently uploaded (20)

“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptxENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
ENGLISH5 QUARTER4 MODULE1 WEEK1-3 How Visual and Multimedia Elements.pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 

82747038 preview-java-j2 ee-book

  • 1. Learn Java/J2EE core concepts and design/coding issues With Java/J2EE Job Interview Companion By K.Arulkumaran Technical Reviewers Craig Malone Lara D Albreo Stuart Watson Acknowledgements A. Sivayini R.Kumaraswamipillai Cover Design K. Arulkumaran A.Sivayini
  • 2. Java/J2EE Job Interview Companion Copy Right 2005 K.Arulkumaran The author has made every effort in the preparation of this book to ensure the a ccuracy of the information. However, information in this book is sold without warranty either express or imp lied. The author will not be held liable for any damages caused or alleged to be caused either directly or indirec tly by this book.
  • 3. Outline SECTION DESCRIPTION What this book will do for you? Motivation for this book Key Areas index SECTION 1 Interview questions and answers on: Java .. Language Fundamentals .. Swing .. Applet . Performance and memory Leaks. .. Personal SECTION 2 Interview questions and answers on: Enterprise Java .. J2EE .. Servlet .. JSP .. JDBC .. JNDI .. RMI .. EJB .. JMS .. XML . SQL, Database tuning and O/R mapping . RUP & UML .. Struts . Web and Application servers. . Best practices and performance considerations. . Testing and deployment. .. Personal SECTION 3 Putting it all together section. How would you go about ? 1. How would you go about documenting your Java/J2EE application? 2. How would you go about designing a Java/J2EE application? 3. How would you go about identifying performance problems and/or memory leaks i n your Java application? 4. How would you go about minimising memory leaks in your Java/J2EE application? 5. How would you 6. How would you Java/J2EE application? 7. How would you Java/J2EE application? 8. How would you our Java/J2EE go about improving performance of your Java/J2EE application? go about identifying any potential thread-safety issues in your go about identifying any potential transactional issues in your go about applying the Object Oriented (OO) design concepts in y
  • 4. application? 9. How would you go about applying the UML diagrams in your Java/J2EE project? 10. How would you go about describing the software development processes you are familiar with? 11. How would you go about applying the design patterns in your Java/J2EE applic ation? 12. How would you go about determining the enterprise security requirements for your Java/J2EE application? 13. How would you go about describing the open source projects like JUnit (unit testing), Ant (build tool), CVS (version control system) and log4J (logging tool) which are integral part of most Java/J2EE projects? 14. How would you go about describing Web services? SECTION 4 Emerging Technologies/Frameworks . Test Driven Development (TDD). . Aspect Oriented Programming (AOP). . Inversion of Control (IOC) (Also known as Dependency Injection). .. Annotations or attributes based programming (xdoclet etc). .. Spring framework. .. Hibernate framework. .. EJB 3.0. . JavaServer Faces (JSF) framework. SECTION 5 Sample interview questions . Java . Web Components . Enterprise . Design . General GLOSSARY OF TERMS RESOURCES INDEX
  • 5. Table of contents Outline ________________________________________________________________________ 3 Table of contents ______________________________________________________________ __ 5 What this book will do for you? ________________________________________________ _____ 6 Motivation for this book________________________________________________________ ___ 7 Key Areas Index ________________________________________________________________ _ 9 Java Interview questions & answers______________________________________________ _ 10 Java Language Fundamentals _____________________________________________________ __ 11 Java Personal __________________________________________________________________ ___ 37 Java Key Points ________________________________________________________________ ___ 40 GLOSSARY OF TERMS _________________________________________________________ 43 RESOURCES __________________________________________________________________ 45 INDEX _______________________________________________________________________ 47
  • 6. What this book will do for you? Have you got the time to read 10 or more books and articles to add value prior t o the interview? This book has been written mainly from the perspective of Java/J2EE job seekers and interviewers. T here are numerous books and articles on the market covering specific topics like Java, J2EE, EJB, Design Patterns, AN T, CVS, Multi-Threading, Servlets, JSP, emerging technologies like AOP (Aspect Oriented Programming), Test Driven Develo pment (TDD), Inversion of Control (IoC) etc. But from an interview perspective it is not possible to brush up on a ll these books where each book usually has from 300 pages to 600 pages. The basic purpose of this book is to cover all the core concepts and design/coding issues which, all Java/J2EE developers, designers and architects should be conversant w ith to perform well in their current jobs and to launch a successful career by doing well at interviews. The interviewer c an also use this book to make sure that they hire the right candidate depending on their requirements. This book contain s a wide range of topics relating to Java/J2EE development in a concise manner supplemented with diagrams, tables, sa mple codes and examples. This book is also appropriately categorised to enable you to choose the area of inter est to you. This book will assist all Java/J2EE practitioners to become better at what they do. Usually it takes years to understand all the core concepts and design/coding issues when you rely only on your work exper ience. The best way to fast track this is to read appropriate technical information and proactively apply these in your work environment. It worked for me and hopefully it will work for you as well. I was also at one stage undecided whethe r to name this book Java/J2EE core concepts and solving design/coding issues or Java/J2EE Job Interview Companion . The reason I chose Java/J2EE Job Interview Companion is because these core concepts and design/coding issues helped me to be successful in my interviews and also gave me thumbs up in code reviews.
  • 7. Motivation for this book I started using Java in 1999 when I was working as a junior developer. During th ose two years as a permanent employee, I pro- actively spent many hours studying the core concepts behind Java/J2EE in a ddition to my hands on practical experience. Two years later I decided to start contracting. Since I started cont racting in 2001, my career had a muchneeded boost in terms of contract rates, job satisfaction, responsibility etc. I moved from one contract to another with a view of expanding my skills and increasing my contract rates. In the last 5 years of contracting, I have worked for 5 different organisations both medium and large on 8 different projects. For each contract I held, on average I attended 6-8 interviews with di fferent companies. In most cases multiple job offers were made and consequently I was in a position to negotiate my contra ct rates and also to choose the job I liked based on the type of project, type of organisation, technology used, etc. I have also sat for around 10 technical tests and a few preliminary phone interviews. The success in the interviews did not come easily. I spent hours prior to each s et of interviews wading through various books and articles as a preparation. The motivation for this book was to collate all this information into a single book, which will save me time prior to my interviews but also can benefit others in th eir interviews. What is in this book has helped me to go from just a Java/J2EE job to a career in Java/J2EE in a short ti me. It has also given me the job security that I can find a contract/permanent job opportunity even in the difficu lt job market . I am not suggesting that every one should go contracting but by performing well at the interviews you can be in a position to pick the permanent role you like and also be able to negotiate your salary pa ckage. Those of you who are already in good jobs can impress your team leaders, solution designers and/or architects fo r a possible promotion by demonstrating your understanding of the key areas discussed in this book. You can discuss with your senior team members about perfomance issues, transactional issues, threading issues (concurrency issues) a nd memory issues. In most of my previous contracts I was in a position to impress my team leads and architect s by pinpointing some of the critical For example: performance, memory, transactional and threading issues with the code and subseq uently fixing them. Trust me it is not hard to impress someone if you understand the key areas. . Struts action classes are not thread-safe (Refer Q113 in Enterprise section). . JSP variable declaration is not thread-safe (Refer Q34 in Enterprise section). . Valuable resources like database connections should be closed properly to avoid any memory and performance issues (Refer Q45 in Enterprise section). .
  • 8. Throwing an application exception will not rollback the transaction in EJB. (Ref er Q77 in Enterprise section). The other key areas, which are vital to any software development, are a good und erstanding of some of key design concepts, design patterns, and a modelling language like UML. These key areas ar e really worthy of a mention in your resume and interviews. For example: . Know how to use inheritance, polymorphism and encapsulation (Refer Q5, Q6, Q7, a nd Q8 in Java section.). . Why use design patterns? (Refer Q5 in Enterprise section). . Why is UML important? (Refer Q106 in Enterprise section). If you happen to be in an interview with an organization facing serious issues w ith regards to their Java application relating to memory leaks, performance problems or a crashing JVM etc then you ar e likely to be asked questions on these topics. Refer Q 63 Q 65 in Java section and Q123, Q125 in Enterprise secti on. Another good reason why these key areas like transactional issues, design concep ts, design patterns etc are vital are because solution designers, architects, team leads, and/or senior developers are usually responsible for conducting the technical interviews. These areas are their favourite topics because these are e ssential to any software development. Some interviewers request you to write a small program during interview or prior to getting to the interview stage. This is to ascertain that you can code using object oriented concepts and design pattern s. So I have included a coding key area to illustrate what you need to look for while coding.
  • 9. . Apply OO concepts like inheritance, polymorphism and encapsulation: Refer Q08 in Java section. . Program to interfaces not to implementations: Refer Q08, Q15 in Java section. . Use of relevant design patterns: Refer Q11 in How would you go about section. . Use of Java collection API and exceptions correctly: Refer Q15, Q34, and Q35 in Java section. . Stay away from hard coding values: Refer Q04 in Java section. L a ngu a g e F und a m e n t a ls D es i g n C onc e p t s D es ig n P a tte r n s SE cu r it y C on c u r r e nc y Iss u e s P e r f o r m an ce Issu es M em o r y Iss u e s S ca l a b il i t y Iss u e s S p eci f i cat i o n F u nda m e nt a ls E xce p t io n H a n d lin g T r a n sac t i o n al Issu e s B est P ra c t i c e s S o ftw a r e D eve lo p m en t P r o ces s CO di n g LF DC DP SF CI PI MI SI SE EH TI BP SD CO H o w m a n y b o o k s d o I h a v e to r e a d to unde r s ta nd and pu t to geth er all th es e ke y ar e a s? H o w m a ny y e a r s o f ex per ie nc e s hou ld I hav e to un der s ta n d a ll th e s e ke y ar e a s? W ill th e s e k e y a r e a s h e lp m e pr og r e s s in m y c a r eer ? W ill th e s e k e y a r e a s h e lp m e c u t quality c ode ? This book aims to solve the above dilemma.
  • 10. My dad keeps telling me to find a permanent job (instead of contracting), which in his view provides better job security but I keep telling him that in my view in Information Technology the job security is achieved only by keeping your knowledge and skills sharp and up to date. The 8 contract positions I held over the last 5 .5 years have given me broader experience in Java/J2EE and related technologies. It also kept me motivated since there was always something new to learn in each assignment, and not all companies will appreciate your skills and expertise unti l you decide to leave. Do the following statements sound familiar to you when you hand in your resignation or decide not to extend your contract after getting another job offer? Can I tempt you to come back? What can I do to keep you here? tc. You might even think why you waited so long. The best way to make an impression in any organisations is to un derstand and proactively apply and resolve the issues relating to the Key Areas discussed in the next section. But be a team player, be tactful and don t be critical of everything, do not act in a superior way and have a sense of humo ur. Technical skills must be complemented with interpersonal skills. Quick Read guide: It is recommended that you go through all the questions in all the sections but if you are pressed for time or would like to read it just before an interview then follow the steps shown below: 1. Read/Browse 2. Read/Browse 3. Read/Browse 4. Read/Browse sed in detail. e Popular Questions in Java and Enterprise Java sections. Key Points in Java and Enterprise Java sections. through Emerging Technologies/Frameworks section. How would you go about section excluding Q11 & Q13, which are discus
  • 11. Key Areas Index I have categorised the core concepts and issues into 14 key areas as listed belo w. These key areas are vital for any good software development. This index will enable you to refer to the questions based on key areas. Also note that each question has an icon next to it to indicate which key area or areas it belongs t o. Additional reading is recommended for beginners in each of the key areas. Key Areas icon Question Numbers Java section Enterprise section How would you go about ? Emerging Technologies /Frameworks Language Fundamentals LF Q1-Q4, Q10-Q14, Q16Q20, Q22-Q27, Q30Q33, Q36-Q43, Q47-Q62 -Q10, Q15, Q17, Q19 Specification Fundamentals SF -Q1-Q19, Q26-Q33, Q35Q38, Q41, Q42, Q44, Q46Q81, Q89-Q97, Q99, 102, Q110, Q112-Q115, Q118Q119, Q121, Q126, Q127, Q128 Q14 Design Concepts DC Q5-Q9, Q10, Q13, Q22, Q49 Q2, Q3, Q19, Q20, Q21, Q31, Q45, Q98, Q106, Q107, Q108, Q109, 101, Q111 Q02, Q08, Q09 Q3-Q9, Q11, Q13, Q14, Q16, Q18, Q20 Design Patterns DP Q10, Q14, Q20, Q31, Q45, Q46, Q50, Q54, Q66 Q5, Q5, Q22, Q24, Q25, Q83, Q84, Q85, Q86, Q87, Q88, Q110, Q111, Q116 Q11 Q12 Transactional Issues TI -Q43, Q71, Q72, Q73, Q74, Q75, Q77, Q78, Q79 Q7 Concurrency Issues CI Q13, Q15, Q29, Q36,
  • 12. Q40, Q53 Q16, Q34, Q113 Q6 Performance Issues PI Q13, Q15 -Q22, Q40, Q53, Q63. Q10, Q16, Q43, Q45, Q46, Q72, Q83-Q88, Q97, Q98, Q100, Q102, Q123, Q125, Q128 Q3, Q5 Memory Issues MI Q22, Q29, Q32, Q33, Q36, Q45, Q64, Q65. Q45, Q93 Q3, Q4 Scalability Issues SI Q19, Q20 Q20, Q21, Q120, Q122 Exception Handling EH Q34,Q35 Q76, Q77 Security SE Q61 Q12, Q13, Q23, Q35, Q46, Q51, Q58, Q81 Q12 Best Practices BP Q15, Q21, Q34, Q63, Q64 Q10, Q16, Q39, Q40, Q46, Q82, Q124, Q125 Software Development Process SD -Q103-Q109, Q129, Q133, Q134, Q136 Q1, Q10, Q13 Q1, Q2 Coding1 CO Q04, Q08, Q10, Q12, Q13, Q15, Q16, Q17, Q21, Q34, Q45, Q46 Q10, Q18, Q21, Q23, Q36, Q38, Q42, Q43, Q45, Q74, Q75, Q76, Q77, Q112, Q114, Q127, Q128 Q11 1 Some interviewers request you to write a small program during interview or pri or to getting to the interview stage. This is to ascertain that you can code using object oriented concepts and design patterns. I have inc luded a coding key area to illustrate what you need to look for while coding. Unlike other key areas, the CO is not always shown agains t the question but shown above the actual section of relevance within a question.
  • 13. 10 Java SECTION ONE Java Interview questions & answers K E Y A R E A S .. Language Fundamentals LF .. Design Concepts DC .. .. .. .. .. .. Design Patterns DP Concurrency Issues CI Performance Issues PI Memory Issues MI Exception Handling EH Security SE .. Scalability Issues SI .. Coding1 CO Popular Questions: Q01, Q04, Q07, Q08, Q13, Q16, Q17, Q18, Q19, Q25, Q27, Q29, Q 32, Q34, Q40, Q45, Q46, Q50, Q51, Q53, Q54, Q55, Q63,Q64, Q66, Q67 Unlike other key areas, the CO is not always shown against the question but sho wn above the actual subsection of relevance within a question.
  • 14. Java 11 Java Language Fundamentals Q 01: Give a few reasons for using Java? LF DC A 01: Java is a fun language. Let s look at some of the reasons: . Built-in support for multi-threading, socket communication, and memory managemen t (automatic garbage collection). . Object Oriented (OO). . Better portability than other languages across operating systems. . Supports Web based applications (Applet, Servlet, and JSP), distributed applicat ions (sockets, RMI. EJB etc) and network protocols (HTTP, JRMP etc) with the help of extensive standardised A PIs (Application Program Interfaces). Q 02: What is the main difference between the Java platform and the other softwa re platforms? LF A 02: Java platform is a software-only platform, which runs on top of other hard ware-based platforms like UNIX, NT etc. The Java platform has 2 components: . Java Virtual Machine (JVM) JVM is a software that can be ported onto various hardw are platforms. Byte codes are the machine language of the JVM. . Java Application Programming Interface (Java API) Q 03: What is the difference between C++ and Java? LF A 03: Both C++ and Java use similar syntax and are Object Oriented, but: . Java does not support pointers. Pointers are inherently tricky to use and troubl esome. . Java does not support multiple inheritances because it causes more problems than it solves. Instead Java supports multiple interface inheritance, which allows an object to inherit many method signatures from different interfaces with the condition that the inheriting object must implemen t those inherited methods. The multiple interface inheritance also allows an object to behave polymorphically o n those methods. [Refer Q 8 and Q 10 in Java section.] . Java does not support destructors but rather adds a finalize() method. Finalize methods are invoked by the garbage collector prior to reclaiming the memory occupied by the object, which h as the finalize() method. This
  • 15. means you do not know when the objects are going to be finalized. Avoid using fi nalize() method to release non-memory resources like file handles, sockets, database connections et c because Java has only a finite number of these resources and you do not know when the garbage collecti on is going to kick in to release these resources through the finalize() method. . Java does not include structures or unions because the traditional data structur es are implemented as an object oriented framework (Java collection framework Refer Q14, Q15 in Java sect ion).
  • 16. 12 Java . All the code in Java program is encapsulated within classes therefore Java does not have global variables or functions. . C++ requires explicit memory management, while Java includes automatic garbage c ollection. [Refer Q32 in Java section]. Q 04: Explain Java class loaders? Explain dynamic class loading? LF A 04: Class loaders are hierarchical. Classes are introduced into the JVM as the y are referenced by name in a class that is already running in the JVM. So how is the very first class loaded? The very f irst class is specially loaded with the help of static main() method declared in your class. All the subsequently lo aded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespac e. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap ) class loader. Now let s look at non-primordial class loaders. The JVM has hooks in it to allow user defined clas s loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM. CLASS LOADER reloadable? Explanation Bootstrap (primordial) No Loads JDK internal classes, java.* packages. (as defined in the sun.boot.clas s.path system property, typically loads rt.jar and i18n.jar) Extensions No Loads jar files from JDK extensions directory (as defined in the j ava.ext.dirs system property usually lib/ext directory of the JRE) System No Loads classes from system classpath (as defined by the java.class.path property, which is set by the CLASSPATH environment variable or classpath or cp command line options) Bootstrap (primordial) (rt.jar, i18.jar) Extensions (lib/ext) System (- classpath) Sibling1 classloader Sibling2 classloader JVM class loaders Classes loaded by Bootstrap class loader have no visibility into classes loaded by its descendants (ie Extensions and Systems class loaders). The classes loaded by system class loader have visibility into classes loaded by its parents (ie Extensions and Bootstrap class loaders). If there were any sibling class loaders they cannot see classes loaded by each other. They can only see the classes loaded by their parent class loader. For example Sibling1 class loader cannot see classes loaded by
  • 17. Sibling2 class loader Both Sibling1 and Sibling2 class loaders have visibilty into classes loaded by their parent class loaders (eg: System, Extensions, and Bootstrap) Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a c lass loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniquene ss is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up th e hierarchy but the reverse is not true as explained in the above diagram. Important: Two objects loaded by different class loaders are never equal even if they carry the same values, which mean a class is uniquely identified in the context of the associated class loader. This applies to singletons too, where each class loader will have its own singleton. [Refer Q45 in Java section for singleton des ign pattern] Explain static vs dynamic class loading? Static class loading Classes are statically loaded with Java s new operator. class MyClass { public static void main(String args[]) { Car c = new Car(); } } Dynamic class loading Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. Let us look at how to load classes dynamically. Class.forName (String className); //static method which returns a Class The above static method returns the class object associated with the class name. The string className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will decide whether to load the class Car or the class Jeep at runtime based on a properties file and/or other runtime
  • 18. Java 13 conditions. Once the class is dynamically loaded the following method returns an instance of the loaded class. It s just like creating a class object with no arguments. class.newInstance (); //A non-static method, which creates an instance of a class (ie creates an object). Jeep myJeep = null ; //myClassName should be read from a properties file or Constants interface. //stay away from hard coding values in your program. CO String myClassName = "au.com.Jeep" ; Class vehicleClass = Class.forName(myClassName) ; myJeep = (Jeep) vehicleClass.newInstance(); myJeep.setFuelCapacity(50); A NoClassDefFoundException is A ClassNotFoundException is thrown when an applica tion tries to load in a thrown if a class is referenced with class through its string name using the fol lowing methods but no definition for the Java s new operator (i.e. static loading) class with the specified name could be fou nd: but the runtime system cannot find the referenced class. . The forName(..) method in class - Class. . The findSystemClass(..) method in class - ClassLoader. . The loadClass(..) method in class - ClassLoader. What are static initializers or static blocks with no function names ? When a class i s loaded, all blocks that are declared static and don t have function name (ie static initializers) are executed even before the constructors are executed. As the name suggests they are typically used to initi alize static fields. CO public class StaticInitilaizer { public static final int A = 5; public static final int B; //Static initializer block, which is executed only once when the class is loade d. static { if(A == 5) B = 10; else B = 5; } public StaticInitilaizer() {} // constructor is called only after static initial izer block } The following code gives an Output of A=5, B=10. public class Test {
  • 19. System.out.println("A =" + StaticInitilaizer.A + ", B =" + StaticInitilaizer.B); } Q 05: What are the advantages of Object Oriented Programming Languages (OOPL)? D C A 05: The Object Oriented Programming Languages directly represent the real life objects like Car, Jeep, Account, Customer etc. The features of the OO programming languages like polymorphism, in heritance and encapsulation make it powerful. [Tip: remember pie which, stands for Polymorphis m, Inheritance and Encapsulation are the 3 pillars of OOPL] Q 06: How does the Object Oriented approach improve software development? DC A 06: The key benefits are: . Re-use of previous work: using implementation inheritance and object composition . . Real mapping to the problem domain: Objects map to real world and represent vehi cles, customers, products etc: with encapsulation. . Modular Architecture: Objects, systems, frameworks etc are the building blocks o f larger systems.
  • 20. 14 Java The increased quality and reduced development time are the by-products of the ke y benefits discussed above. If 90% of the new application consists of proven existing components then only t he remaining 10% of the code have to be tested from scratch. Q 07: How do you express an is a relationship and a has a heritance and composition? What is the difference between composition and aggregation? relationship or explain in DC A 07: The is a relationship is expressed with inheritance and has a relationship is expressed with composition. Both inheritance and composition allow you to place sub-objects inside your new class . Two of the main techniques for code reuse are class inheritance and object composition. Inheritance [ is a ] Vs Composition [ has a ] Building Bathroom House class Building{ ....... } class House extends Building{ ......... } is a [House is a Building] class House { Bathroom room = new Bathroom() ; .... public void getTotMirrors(){ room.getNoMirrors(); .... } } has a [House has a Bathroom] is a has a Inheritance is uni-directional. For example House is a Building. But Building is not a House. Inheritance uses extends key word. Composition: is used when House has a Bathroom. It is incorrec t to say House is a Bathroom. Composition simply means using instance variables that refer to other objects. The class House will have an instance variable, which refers to a Bathroom object. Which one to use? The guide is that inheritance should be only used when subclas s is a superclass. . Don t use inheritance just to get code reuse. If there is no is a relationship then use composition for code reuse. Overuse of implementation inheritance (uses the extends key word) can break all the subclasses, if the superclass is modified.
  • 21. . Do not use inheritance just to get polymorphism. If there is no is a relationship and all you want is polymorphism then use interface inheritance with composition, which gives you co de reuse (Refer Q8 in Java section for interface inheritance). What is the difference between aggregation and composition? Aggregation Aggregation is an association in which one class belongs to a collection. This is a part of a whole relationship where a part can exist without a whole. For example a line item is a whole and product is a part. If a line item is deleted then corresponding product need not be deleted. So aggregation has a weaker relationship. Composition Composition is an association in which one class belongs to a collection. This is a part of a whole relationship where a part cannot exist without a whole. If a whole is deleted then all parts are deleted. For example An order is a whole and line items are parts. If an order deleted then all corresponding line items for that order should be deleted. So composition has a stronger relationship. Q 08: What do you mean by polymorphism, inheritance, encapsulation, and dynamic binding? DC A 08: Polymorphism means the ability of a single variable of a given type to be used to reference objects of different types, and automatically call the method that is specific to the type of object the variable references. In a nutshell, polymorphism is a bottom-up method call. The benefit of polymorphism is that it is very easy to add new classes of derived objects without breaking the calling code (i.e. getTotArea() in the s ample code shown below) that uses the polymorphic classes or interfaces. When you send a message to an object even though you don t know what specific type it is, and the right thing happens, that s called polymorphism. The process used by objectoriented programming languages to implement polymorphism is called dynamic bindi ng. Let us look at some sample code to demonstrate polymorphism: CO
  • 22. Java 15 Sample code: //client or calling code double dim = 5.0; //ie 5 meters radius or width List listShapes = new ArrayList(20); Shape s = new Circle(); listShapes.add(s); //add circle s = new Square(); listShapes.add(s); //add square getTotArea (listShapes,dim); //returns 78.5+25.0=103.5 //Later on, if you decide to add a half circle then define //a HalfCircle class, which extends Circle and then provide an //area(). method but your called method getTotArea(...) remains //same. s = new HalfCircle(); listShapes.add(s); //add HalfCircle getTotArea (listShapes,dim); //returns 78.5+25.0+39.25=142.75 /** called method: method which adds up areas of various ** shapes supplied to it. **/ public double getTotArea(List listShapes, double dim){ Iterator it = listShapes.iterator(); double totalArea = 0.0; //loop through different shapes while(it.hasNext()) { Shape s = (Shape) it.next(); totalArea += s.area(dim); //polymorphic method call } return totalArea ; } For example: given a base class/interface Shape, polymorphism allows the programmer to define different area(double dim1) methods for any number of derived classes such as Circle, Square etc. No matter what shape an object is, applying the area method to it will return the right results. Later on HalfCicle can be added without breaking your called code i.e. method getTotalArea(...) Depending on what the shape is, appropriate area(double dim) method gets called and calculated. Circle .. area is 78.5sqm Square .. area is 25sqm HalfCircle .. area is 39.25 sqm +area() : double <<abstract>>
  • 23. Shape +area() : double Circle +area() : double HalfCircle +area() : double Square +area() : double Circle +area() : double HalfCircle +area() : double Square +area() : double «interface» Shape Inheritance is the inclusion of behaviour (i.e. methods) and state (i.e. variabl es) of a base class in a derived class so that they are accessible in that derived class. The key benefit of Inhe ritance is that it provides the formal mechanism for code reuse. Any shared piece of business logic can be moved from t he derived class into the base class as part of refactoring process to improve maintainability of your cod e by avoiding code duplication. The existing class is called the superclass and the derived class is called the subc lass. Inheritance can also be defined as the process whereby one object acquires characteristics from one or m ore other objects the same way children acquire characteristics from their parents. There are two types of inheritances: 1. Implementation inheritance (aka class inheritance): You can extend an applica tions functionality by reusing functionality in the parent class by inheriting all or some of the operations al ready implemented. In Java, you can only inherit from one superclass. Implementation inheritance promotes reusabilit y but improper use of class inheritance can cause programming nightmares by breaking encapsulation and makin g future changes a problem. With implementation inheritance, the subclass becomes tightly coupled with the s uperclass. This will make the design fragile because if you want to change the superclass, you must know all t he details of the subclasses to avoid breaking them. So when using implementation inheritance, make sure that th e subclasses depend only on the behaviour of the superclass, not on the actual implementation. For exampl e in the above diagram the subclasses should only be concerned about the behaviour known as area() but not how it is implemented. 2. Interface inheritance (aka type inheritance): This is also known as subtyping . Interfaces provide a mechanism for specifying a relationship between otherwise unrelated classes, typically by specifying a set of common methods each implementing class must contain. Interface inheritance promotes the design concept of program to interfaces not to implementations. This also reduces the coupling or implementat ion dependencies between systems. In Java, you can implement any number of interfaces. This is more flexi
  • 24. ble than implementation inheritance because it won t lock you into specific implementations which make sub classes difficult to maintain. So care should be taken not to break the implementing classes by modifying the inte rfaces. Which one to use? Prefer interface inheritance to implementation inheritance bec ause it promotes the design concept of coding to an interface and reduces coupling. Interface inheritance ca n achieve code reuse with the help of object composition. If you look at Gang of Four (GoF) design patterns, y ou can see that it favours interface inheritance to implementation inheritance. CO
  • 25. 16 Java Implementation inheritance Interface inheritance Let s assume that savings account and term deposit account have a similar behaviour in terms of depositing and withdrawing money, so we will get the super class to implement this behaviour and get the subclasses to reuse this behaviour. But saving account and term deposit account have specific behaviour in calculating the interest. public abstract class Account { public void deposit(double amount) { //deposit logic } public void withdraw(double amount) { //withdraw logic } public abstract double calculateInterest(double amount); } public class SavingsAccount extends Account { public double calculateInterest(double amount) { //calculate interest for SavingsAccount } } public class TermDepositAccount extends Account { public double calculateInterest(double amount) { //calculate interest for TermDeposit } } The calling code can be defined as follows for illustration purpose only: public class Test { public static void main(String[] args) { Account acc1 = new SavingsAccount(); acc1.deposit(5.0); acc1.withdraw(2.0); Account acc2 = new TermDepositAccount(); acc2.deposit(10.0); acc2.withdraw(3.0); acc1.calculateInterest(500.00); acc2.calculateInterest(500.00); } } Let s look at an interface inheritance code sample, which makes use of composition for reusability. In the following example the methods deposit( ) and withdraw( ) share the same piece of code in AccountHelper class. The method calculateInterest( ) has its specific implementation in its own class. public interface Account { public abstract void deposit(double amount); public abstract void withdraw(double amount); public abstract int getAccountType(); } public interface SavingsAccount extends Account{ public abstract double calculateInterest(double amount); } public interface TermDepositAccount extends Account{ public abstract double calculateInterest(double amount); } The classes SavingsAccountImpl, TermDepositAccountImpl
  • 26. should implement the methods declared in its interfaces. The class AccountHelper implements the methods deposit( ) and withdraw( ) public class SavingsAccountImpl implements SavingsAccount{ private int accountType = 1; //helper class which promotes code reuse through composition AccountHelper helper = new AccountHelper(); public void deposit(double amount) { helper.deposit(amount, getAccountType()); } public void withdraw(double amount) { helper.withdraw(amount, getAccountType()); } public double calculateInterest(double amount) { //calculate interest for SavingsAccount } public int getAccountType(){ return accountType; } } public class TermDepositAccountImpl implements TermDepositAccount { private int accountType = 2; //helper class which promotes code reuse through composition AccountHelper helper = new AccountHelper(); public void deposit(double amount) { helper.deposit(amount, getAccountType()); } public void withdraw(double amount) { helper.withdraw(amount, getAccountType()); } public double calculateInterest(double amount) { //calculate interest for TermDeposit } public int getAccountType() { return accountType; } } The calling code can be defined as follows for illustration purpose only: public class Test { public static void main(String[] args) {
  • 27. Java 17 } } Account acc1 = new SavingsAccountImpl(); acc1.deposit(5.0); Account acc2 = new TermDepositAccountImpl(); acc2.deposit(10.0); if (acc1.getAccountType() == 1) { ((SavingsAccount) acc1).calculateInterest(500.00); } if (acc2.getAccountType() == 2) { ((TermDepositAccount) acc2).calculateInterest(500.00); } Encapsulation refers to keeping all the related members (variables and methods) together in an object. Specifying members as private can hide the variables and methods. Objects should hide their inner workings from the outside view. Good encapsulation improves code modularity by preventing obje cts interacting with each other in an unexpected way, which in turn makes future development and refa ctoring efforts easy. Being able to encapsulate members of a class is important for security and integ rity. We can protect variables from unacceptable values. The sample code below describes how encapsulation can be used to protect the MyMarks object from having negative values. Any modification to member variable v marks can only be carried out through the setter method setMarks(int mark). This prevents the object MyMark s from having any negative values by throwing an exception. CO Sample code setName(Stringname) StringgetName() intgetMarks() setMarks(intmark) private int vmarks; private String name; Class MyMarks { private int vmarks = 0; private String name; public void setMarks(int mark) throws MarkException { if(mark > 0) this.vmarks = mark; else { throw new MarkException("No negative Values"); } } public int getMarks(){ return vmarks; } //getters and setters for attribute name goes here.
  • 28. } Member variables are encapsulated, so that they can only be accessed via encapsulating methods. Q 09: What is design by contract? Explain the assertion construct? DC A 09: Design by contract specifies the obligations of a calling- method and calle d-method to each other. Design by contract is a valuable technique, which should be used to build well-defined int erfaces. The strength of this programming methodology is that it gets the programmer to think clearly about wh at a function does, what pre and post conditions it must adhere to and also it provides documentation for the caller. Java uses the assert statement to implement pre- and post-conditions. Java s exceptions handling also s upport design by contract especially checked exceptions (Refer Q34 in Java section for checked exceptions) . In design by contract in addition to specifying programming code to carrying out intended operations of a method the programmer also specifies: 1. Preconditions This is the part of the contract the calling- method must agree to. Preconditions specify the conditions that must be true before a called method can execute. Preconditions i nvolve the system state and the arguments passed into the method at the time of its invocation. If a preconditio n fails then there is a bug in the calling-method or calling software component.
  • 29. 18 Java On public methods On non-public methods Preconditions on public methods are enforced by explicit checks that throw particular, specified exceptions. You should not use assertion to check the parameters of the public methods but can use for the non-public methods. Assert is inappropriate because the method guarantees that it will always enforce the argument checks. It must check its arguments whether or not assertions are enabled. Further, assert construct does not throw an exception of a specified type. It can throw only an AssertionError. public void setRate(int rate) { if(rate <= 0 rate > MAX_RATE){ throw new IllegalArgumentException( Invalid rate .. + rate); } setCalculatedRate(rate); } You can use assertion to check the parameters of the non-public methods. private void setCalculatedRate(int rate) { assert (rate > 0 && rate < MAX_RATE) : rate; //calculate the rate and set it. } Assertions can be disabled, so programs must not assume that assert construct will be always executed: //Wrong: if assertion is disabled, CarpenterJob never //Get removed assert jobsAd.remove(PilotJob); //Correct: boolean pilotJobRemoved = jobsAd.remove(PilotJob); assert pilotJobRemoved; 2. Postconditions This is the part of the contract the called-method agrees to. What must be true after a method completes successfully. Postconditions can be used with assertions in bot h public and non-public methods. The postconditions involve the old system state, the new system state, the method arguments and the method s return value. If a postcondition fails then there is a bug in the calledmethod or called software component. public double calcRate(int rate) { if(rate <= 0 rate > MAX_RATE){ throw new IllegalArgumentException( Invalid rate !!! ); } //logic to calculate the rate and set it goes here assert this.evaluate(result) < 0 : this; //this .. message sent to AssertionErro r on failure return result; } 3. Class invariants - what must be true about each instance of a class? A class invariant as an internal invariant that can specify the relationships among multiple attributes, and should be true before and after any method
  • 30. completes. If an invariant fails then there could be a hod or called-method. There is no particular mechanism for checking invariants but ne all the expressions required for checking invariants into a single internal method that ns. For example if you have a class, which deals with negative integers then you define the nternal method: class NegativeInteger { Integer value = new Integer (-1); //invariant //constructor public NegativeInteger(Integer int) { //constructor logic goes here assert isNegative(); } bug in either calling-met it is convenient to combi can be called by assertio isNegative() convenient i //rest of the public and non-public methods goes here. public methods should ca ll assert isNegative(); prior to its return //convenient internal method for checking invariants. Returns true if the integ er value is negative private boolean isNegative(){ return value.intValue() < 0 ; } } The isNegative() method should be true before and after any method completes, ea ch public method and constructor should contain the following assert statement immediately prior to i ts return. assert isNegative(); Explain the assertion construct? The assertion statements have two forms as show n below: assert Expression1;
  • 31. Java 19 assert Expression1 : Expression2; Where: . Expression1 Æ is a boolean expression. If the Expression1 evaluates to false, it throws an Ass ertionError without any detailed message. . Expression2 .. if the Expression1 evaluates to false throws an AssertionError wi th using the value of the Expression2 as the errors detailed message. Note: If you are using assertions (available from JDK1.4 onwards), you should su pply the JVM argument to enable it by package name or class name. Java -ea[:packagename... :classname] or Java -enableassertions[:packagename... : classname] Java ea:Account Q 10: What is the difference between an abstract class and an interface and when should you use them? LF DP DC A 10: In design, you want the base class to present only an interface for its de rived classes. This means, you don t want anyone to actually instantiate an object of the base class. You only want to upc ast to it (implicit upcasting, which gives you polymorphic behaviour), so that its interface can be used. This is acc omplished by making that class abstract using the abstract keyword. If anyone tries to make an object of an abs tract class, the compiler prevents it. The interface keyword takes this concept of an abstract class a step further by preventing any method or function implementation at all. You can only declare a method or function but not provide the implementation. The class, which is implementing the interface, should provide the actual implementation. T he interface is a very useful and commonly used aspect in OO design, as it provides the separation of interface an d implementation and enables you to: ..Capture similarities among unrelated classes without artificially forcing a cl ass relationship. ..Declare methods that one or more classes are expected to implement. ..Reveal an object's programming interface without revealing its actual implemen tation. ..Model multiple interface inheritance in Java, which provides some of the benef its of full on multiple inheritances, a feature that some object-oriented languages support that allow a class to have more than one superclass. Shape Circle Square CircleOnSquare
  • 32. Diamond problem & use of interface No multiple inheritance in JAVA Circle Square CircleOnSquare <<Interface>> ShapeIF <<Interface>> CircleIF <<Interface>> SquareIF Multiple interface inheritance in JAVA Abstract class Interface Have executable methods and abstract methods. Have no implementation code. All m ethods are abstract. Can only subclass one abstract class. A class can implement any number of interf aces. Can have instance variables, constructors and any visibility: public, private, protected, none (aka package). Cannot have instance variables, constructors and can have only public and none (aka package) visibility. When to use an abstract class?: In case where you want to use implementation inh eritance then it is usually provided by an abstract base class. Abstract classes are excellent candidates in side of application frameworks. Abstract classes let you define some default behaviour and force subclasses to p rovide any specific behaviour. Care should be taken not to overuse implementation inheritance as discussed in Q 8 in Java section.
  • 33. 20 Java When to use an interface?: For polymorphic interface inheritance, where the clie nt wants to only deal with a type and does not care about the actual implementation use interfaces. If you need to change your design frequently, you should prefer using interface to abstract. CO Coding to an interface reduces coupling and interface inheritance can achieve code reuse with the help of object composition. Another justification for using interfaces is that they solve the diamond problem of traditional multiple inheritance as show n in the figure. Java does not support multiple inheritances. Java only supports multiple interface inheritance . Interface will solve all the ambiguities caused by this diamond problem . Design pattern: Strategy design pattern lets you swap new algorithms and process es into your program without altering the objects that use them. Strategy design pattern: Refer Q11 in How wo uld you go about section. Q 11: Why there are some interfaces with no defined methods (i.e. marker interfa ces) in Java? LF A 11: The interfaces with no defined methods act like markers. They just tell th e compiler that the objects of the classes implementing the interfaces with no defined methods need to be treated different ly. Example Serializable (Refer Q19 in Java section), Cloneable etc Q 12: When is a method said to be overloaded and when is a method said to be ove rridden? LF CO A 12: Method Overloading Method Overriding Overloading deals with multiple methods in the same class with the same name but different method signatures. class MyClass { public void getInvestAmount(int rate) { } public void getInvestAmount(int rate, long principal) { } } Both the above methods have the same method names but different method signatures, which mean the methods are overloaded. Overriding deals with two methods, one in the parent class and the other one in the child class and has the same name and signatures. class BaseClass{ public void getInvestAmount(int rate) { } } class MyClass extends BaseClass { public void getInvestAmount(int rate) { } } Both the above methods have the same method names and the signatures but the method in the subclass MyClass overrides the method in the superclass BaseClass. Overloading lets you define the same operation in
  • 34. different ways for different data. Overriding lets you define the same operation in different ways for different object types. Q 13: What is the main difference between an ArrayList and a Vector? What is the main difference between Hashmap and Hashtable? LF DC PI CI A 13: Vector / Hashtable ArrayList / Hashmap Original classes before the introduction of Collections API. Vector & Hashtable are synchronized. Any method that touches their contents is thread-safe. So if you don t need a thread safe collection, use the ArrayList or Hashmap. Why pay the price of synchronization unnecessarily at the expense of performance degradation. So which is better? As a general rule, prefer ArrayList/Hashmap to Vector/Hashta ble. If your application is a multithreaded application and at least one of the threads either adds or deletes an entry into the collection then use new Java collection API s external synchronization facility as shown belo w to temporarily synchronize your collections as needed: CO Map myMap = Collections.synchronizedMap (myMap); List myList = Collections.synchronizedList (myList); Java arrays are even faster than using an ArrayList/Vector and perhaps therefore may be preferable. ArrayList/Vector internally uses an array with some convenient methods like add( ..), remove( ) etc. Q 14: Explain the Java Collection framework? LF DP
  • 35. Java 21 A 14: The key interfaces used by the collection framework are List, Set and Map. The List and Set extends the Collection interface. Should not confuse the Collection interface with the Colle ctions class which is a utility class. A Set is a collection with unique elements and prevents duplication within the c ollection. HashSet and TreeSet are implementations of a Set interface. A List is a collection with an ordered s equence of elements and may contain duplicates. ArrayList, LinkedList and Vector are implementations of a Li st interface. The Collection API also supports maps, but within a hierarchy distinct from the Collection interface. A Map is an object that maps keys to values, where the list of keys is itself a collection o bject. A map can contain duplicate values, but the keys in a map must be distinct. HashMap, TreeMap and Hashtable a re implementations of a Map interface. How to implement collection ordering? SortedSet and SortedMap interfaces maintai n sorted order. The classes, which implement the Comparable interface, impose natural order. For cla sses that don t implement comparable interface, or when one needs even more control over ordering based on multiple attributes, a Comparator interface should be used. Design pattern: What is an Iterator? An Iterator is a use once object to access the objects stored in a collection. Iterator design pattern (aka Cursor) is used, which is a behavioural design patt ern that provides a way to access elements of a collection sequentially without exposing its internal representati on. JAVA collection framework ex tends ArrayList AbstractCollection AbstractL ist AbstractS et AbstractMap Ab stract Sequ en tial List LinkedList V ector TreeS et HashS et TreeMap HashMap Weak HashMap Linked HashMap Id entity
  • 36. HashMap < interface> So rted Map < in terface> So rted Set Linked HashS et < interface> Collectio n < interface> List <interface> Set < interface> Map < in terface> Random Acess < interface> Com p arato r Arrays implements Stack asList java.util.Collections (Diagram sourced from: http://www.wilsonmar.com/1arrays.htm) What are the benefits of the Java collection framework? Collection framework pro vides flexibility, performance, and robustness. . Polymorphic algorithms sorting, shuffling, reversing, binary search etc. . Set algebra - such as finding subsets, intersections, and unions between objects . . Performance - collections have much better performance compared to the older Vec tor and Hashtable classes with the elimination of synchronization overheads. . Thread-safety -when synchronization is required, wrapper implementations are pro vided for temporarily synchronizing existing collection objects. . Immutability -when immutability is required wrapper implementations are provided for making a collection immutable. . Extensibility - interfaces and abstract classes provide an excellent starting po int for adding functionality and features to create specialized object collections. Q 15: What are some of the best practices relating to Java collection? BP PI CI A 15: .
  • 37. Use ArrayLists, HashMap etc as opposed to Vector, Hashtable etc, where possible to avoid any synchronization overhead. Even better is to use just arrays where possible. If m ultiple threads concurrently access a collection and at least one of the threads either adds or deletes an en try into the collection, then the collection must be externally synchronized. This is achieved by: Map myMap = Collections.synchronizedMap (myMap);
  • 38. 22 Java List myList = Collections.synchronizedList (myList); . Set the initial capacity of a collection appropriately (e.g. ArrayList, HashMap etc). This is because collection classes like ArrayList, HashMap etc must grow periodically to accommodate new el ements. But if you have a very large array, and you know the size in advance then you can speed things up by setting the initial size appropriately. For example: HashMaps/Hashtables need to be created with sufficiently large capacity to minim ise rehashing (which happens every time the table grows). HashMap has two parameters initial capacity and load factor that affect its performance and space requirements. Higher load fact or values (default load factor of 0.75 provides a good trade off between performance and space) will reduce the space cost but will increase the lookup cost of myMap.get( ) and myMap.put( ) methods. When the number o f entries in the HashMap exceeds the current capacity * loadfactor then the capacity of the HasMa p is roughly doubled by calling the rehash function. It is also very important not to set the initial ca pacity too high or load factor too low if iteration performance or reduction in space is important. . Program in terms of interface not implementation: For example you might decide a LinkedList is the best choice for some application, but then later decide ArrayList might be a better c hoice for performance reason. CO Use: List list = new ArrayList(100); //program in terms of interface & set the initia l capacity. Instead of: ArrayList list = new ArrayList(); ..Avoid storing unrelated or different types of objects into same collection: Th is is analogous to storing items in pigeonholes without any labelling. To store items use value objects or data objects (as oppose to storing every attribute in an ArrayList or HashMap). Provide wrapper classes aro und your collection API classes like ArrayList, Hashmap etc as shown in better approach column. Also whe re applicable consider using composite design pattern, where an object may represent a single object or a collection of objects. Refer Q52 in Java section for UML diagram of a composite design pattern. CO Avoid where possible Better approach The code below is hard to maintain and understand by others. Also gets more complicated as the requirements
  • 39. grow in the future because we are throwing different types of objects like Integer, String etc into a list just based on the indices and it is easy to make mistakes while casting the objects back during retrieval. When storing items into a collection define value objects as shown below: (VO is an acronym for Value Object). public class LineItemVO { private int itemId; private String productName; List myOrder = new ArrayList() ResultSet rs = While (rs.hasNext()) { List lineItem = new ArrayList(); lineItem.add (new Integer(rs.getInt( itemId ))); lineItem.add (rs.getString( description )); . myOrder.add( lineItem); } public int getLineItemId(){return accountId ;} public int getAccountName(){return accountName;} public void setLineItemId(int accountId ){ this.accountId = accountId } //implement other getter & setter methods } Now let s define our base wrapper class, which represents an order: public abstract class Order { int orderId; return myOrder; Example 2: List myOrder = new ArrayList(10); //create an order OrderVO header = new OrderVO(); header.setOrderId(1001); //add all the line items LineItemVO line1 = new LineItemVO(); line1.setLineItemId(1); LineItemVO line2 = new LineItemVO(); Line2.setLineItemId(2); List lineItems = null; public abstract int countLineItems(); public abstract boolean add(LineItemVO itemToAdd); public abstract boolean remove(LineItemVO itemToAdd); public abstract Iterator getIterator(); public int getOrderId(){return this.orderId; } } Now a specific implementation of our wrapper class: public class OverseasOrder extends Order { public OverseasOrder(int inOrderId) { this.lineItems = new ArrayList(10); this.orderId = inOrderId; }
  • 40. Java 23 List lineItems = new ArrayList(); lineItems.add(line1); lineItems.add(line2); //to store objects myOrder.add(order);// index 0 is an OrderVO object myOrder.add(lineItems);//index 1 is a List of line items //to retrieve objects myOrder.get(0); myOrder.get(1); Above approaches are bad because disparate objects are stored in the lineItem collection in example-1 and example-2 relies on indices to store disparate objects. The indices based approach and storing disparate objects are hard to maintain and understand because indices are hardcoded and get scattered across the code. If an index position changes for some reason, then you will have to change every occurence, otherwise it breaks your application. The above coding approaches are analogous to storing disparate items in a storage system without proper labelling and just relying on its grid position. public int countLineItems() { //logic to count } public boolean add(LineItemVO itemToAdd){ //additional logic or checks return lineItems.add(itemToAdd); } public boolean remove(LineItemVO itemToAdd){ return lineItems.remove(itemToAdd); } public ListIterator getIterator(){ return lineItems.Iterator();} } Now to use: Order myOrder = new OverseasOrder(1234) ; LineItemVO item1 = new LineItemVO(); Item1.setItemId(1); Item1.setProductName( BBQ ); LineItemVO item2 = new LineItemVO(); Item1.setItemId(2); Item1.setProductName( Outdoor chair ); //to add line items to order myOrder.add(item1); myOrder.add(item2); Q 16: When providing a user defined key class for storing objects in the Hashmap s or Hashtables, what methods do you have to provide or override (ie method overriding)? LF PI CO A 16: You should override the equals() and hashCode() methods from the Object cl ass. The default implementation of the equals() and hashcode(), which are inherited from the java.lang.Object uses an object instance s memory location (e.g. MyObject@6c60f2ea). This can cause problems when two instances of the car objects have the same color but the inherited equals() will return false because it uses the memo ry location, which is different for the two instances. Also the toString() method can be overridden to provide a pro per string representation of your
  • 41. object. Points to consider: If a class overrides equals(), it must override hashCode(). If 2 objects are equal, then their hashCode values must be equal as well. If a field is not used in equals(), then it must not be used in hashCode(). If it is accessed often, hashCode() is a candidate for caching to enhance perfor mance. Note: Java 1.5 introdces enumerated constants, which improves readability and ma intainability of your code. Java programming language enums are more powerful than their counterparts in other la nguages. E.g. A class like Weather can be built on top of simple enum type Season and the class Weather can be made immutable, and only one instance of each Weather can be created, so that your Weather class does not have to override equals() and hashCode() methods. public class Weather { public enum Season {WINTER, SPRING, SUMMER, FALL} private final Season season; private static final List<Weather> listWeather = new ArrayList<Weather> (); private Weather (Season season) { this.season = season;} public Season getSeason () { return season;} static { for (Season season : Season.values()) { listWeather.add(new Weather(season)); } } public static ArrayList<Weather> getWeatherList () { return listWeather; } public String toString(){ return season;} // takes advantage of toString() metho d of Season. }
  • 42. 24 Java Q 17: What is the main difference between a String and a StringBuffer class? LF PI CI CO A 17: String StringBuffer / StringBuilder String is immutable: you can t modify a string StringBuffer is mutable: use String Buffer or StringBuilder when you want to object but can replace it by creating a new modify the contents. StringBuilder w as added in Java 5 and it is identical in instance. Creating a new instance is rather all respects to StringBuffer except that it is not synchronised, which makes expensive. it slightly faster at the cost of not being thread-safe. //Inefficient version using immutable String //More efficient version using muta ble StringBuffer String output = Some text StringBuffer output = new StringBuffer(110); Int count = 100; Output.append( Some text ); for(int I =0; i<count; i++) { for(int I =0; i<count; i++) { output += i; output.append(i); } } return output; return output.toString(); The above code would build 99 new String objects, of which 98 would be thrown away The above code creates only two new ob jects, the StringBuffer and the final immediately. Creating new objects is not String that is returned. StringBuffer e xpands as needed, which is costly efficient. however, so it would be better to initilise the StringBuffer with the correct size from the start as shown. Another important point is that creation of extra strings is not limited to overl oaded mathematical operators ( + ) but there are several methods like conact(), trim(), substring(), and replace() in S tring classes that generate new string instances. So use StringBuffer or StringBuilder for computation intensive operations, which offer better performance. Q 18: What is the main difference between pass-by-reference and pass-by-value? L F PI A 18: Other languages use pass-by-reference or pass-by-pointer. But in Java no m atter what type of argument you pass the corresponding parameter (primitive variable or object reference) will g et a copy of that data, which is exactly how pass- by-value (ie copy-by-value) works. In Java, if a calling method passes a reference of an object as an argument to t he called method then the passedin reference gets copied first and then passed to the called method. Both the or iginal reference that was passed-in and the copied reference will be pointing to the same object. So no ma tter which reference you use, you will be always modifying the same original object, which is how the pass-by-refe rence works as well. ref d Pass-by-value for primitive variables vs Object references public void first(){
  • 43. int i= 10; int x = second(i); //A t this point //value of i is still 10 //value of x is 11 } public int second(int k) { k++; return k ; } i = 10 k = 10 k = 11 Copy of i stores i copiesi acts on k ref public void first(){ Car c = new Car("red") //A t this point //color is Red second(c); //A t this point //color is Blu e } public void second(C ar d) { d.setC olor(blue); //color is blue } C ar object S tring colo r = red ref c copyofc Primitive variables Object references m odifies th e orig in al object through c opied referen ce m odifies th e c opy k but no t th e orig inal. C hanges color = blue If your method call involves inter-process (e.g. between two JVMs) communication , then the reference of the calling method has a different address space to the called method sitting in a s eparate processs (i.e separate JVM). Hence inter-process communication involves calling method passing objects as arguments to called method by-value in a serialized form, which can adversely affect performance due to mar shalling and unmarshalling cost. Note: As discussed in Q69 in Enterprise section, EJB 2.x introduced local interf aces, where enterprise beans that can be used locally within the same JVM using Java s form of pass-by-reference, hence improvin g performance.
  • 44. to code but will have performance implications (Refer Q22 in Java section). to c ode but will have performance implications (Refer Q22 in Java section). Java 25 Q 19: What is serialization? How would you exclude a field of a class from seria lization or what is a transient variable? What is the common use? LF SI PI A 19: Serialization is a process of reading or writing an object. It is a proces s of saving an object s state to a sequence of bytes, as well as a process of rebuilding those bytes back into a live object at some future time. An object is marked serializable by implementing the java.io.Serializable interface, which is only a marker interface -- it simply allows the serialization mechanism to verify that the class can be persisted, ty pically to a file. byte stream writeto Serialization File class Car implements Serializable { String color = null; transient File fh = null; } Car Object1 Class Car implements Serializable { String color = null; } Car Object 2 deserialize serialize deserialize Transient variables cannot be serialized. The fields marked transient in a seria lizable object will not be transmitted in the byte stream. An example would be a file handle or a database connection. Such objects are only meaningful locally. So they should be marked as transient in a serializable clas s. Serialization can adversely affect performance since it: .. Depends on reflection. . Has an incredibly verbose data format. . Is very easy to send surplus data. When to use serialization? Do not use serialization if you do not have to. A com mon use of serialization is to use it to send an object over the network or if the state of an object needs to be p ersisted to a flat file or a database. (Refer Q57 on Enterprise section). Deep cloning or copy can be achieved through serialization. This may be fast The objects stored in an HTTP session should be serializable to support in-memor y replication of sessions to achieve scalability (Refer Q20 in Enterprise section). Objects are passed in RMI (Remote Method Invocation)
  • 45. across network using serialization (Refer Q57 in Enterprise section). Q 20: Explain the Java I/O streaming concept and the use of the decorator design pattern in Java I/O? LF DP A 20: tream There PI SI Java input and output is defined in terms of an abstract concept called a , which is a sequence of data. are 2 kinds of streams. s . Byte streams (8 bit bytes) .. Abstract classes are: InputStream and OutputStream . Character streams (16 bit UNICODE) .. Abstract classes are: Reader and Writer Design pattern: java.io.* classes use the decorator design pattern. The decorato r design pattern attaches responsibilities to objects at runtime. Decorators are more flexible than inheri tance because the inheritance attaches responsibility to classes at compile time. The java.io.* classes use th e decorator pattern to construct different combinations of behaviour at runtime based on some basic classes. Attaching responsibilities to classes at compile time using subclassing. Attaching responsibilities to objects at runtime using a decorator design pattern. Inheritance (aka subclassing) attaches responsibilities to classes at compile time. When you extend a class, each individual changes you make to child class will affect all instances of the child classes. Defining many classes using inheritance to have all possible combinations is problematic and inflexible. By attaching responsibilities to objects at runtime, you can apply changes to each individual object you want to change. File file = new File( c:/temp ); FileInputStream fis = new FileInputStream(file); BufferedInputStream bis = new BufferedInputStream(fis); Decorators decorate an object by enhancing or restricting functionality of an object it decorates. The decorators add or restrict functionality to decorated
  • 46. 26 Java objects either before or after forwarding the request. At runtime the BufferedInputStream (bis), which is a decorator (aka a wrapper around decorated object), forwards the method call to its decorated object FileInputStream (fis). The bis will apply the additional functionality of buffering around the lower level file (i.e. fis) I/O. java.lang.Object java.io.InputStream java.io.Reader java.io.OutputStream java.io.Writer java.io.BefferedReader java.io.InputStreamReader java.io.FileReader java.io.OutputStreamWriterr java.io.FileWriter java.io.FileInputStream java.io.FileoutputStream java.lang.System java.io.* class hierachy Note: Only a few sub classes of abstract classes like InputStream are shown for clarity. The New I/O (NIO): more scalabe and better performance Java has long been not suited for developing programs that perform a lot of I/O operations. Furthermore, commonly needed tasks such as file locking, non-blocking and asynchronous I/O op erations and ability to map file to memory were not available. Non-blocking I/O operations were achieved through work arounds such as multithreading or using JNI. The New I/O API (aka NIO) in J2SE 1.4 has changed t his situation. A server s ability to handle several client requests effectively depends on how it uses I/O streams. When a server has to handle hundreds of clients simultaneously, it must be able to use I/O ser vices concurrently. One way to cater for this scenario in Java is to use threads but having almost one-to-one r atio of threads (100 clients will have 100 threads) is prone to enormous thread overhead and can result in performance and scalability problems due to consumption of memory stacks and CPU context switching. To overcome this problem, a new set of non-blocking I/O classes have been introduced to the Java platform in java.nio p ackage. The non- blocking I/O mechanism is built around Selectors and Channels. Channels, Buffers and Selector s are the core of the NIO. A Channel class represents a bi- directional communication channel (similar to In putStrean and OutputStream) between datasources such as a socket, a file, or an application component, which is capable of performing one or more I/O operations such as reading or writing. Channels can be non-blocking, wh ich means, no I/O operation will wait for data to be read or written to the network. The good thing about NIO cha nnels is that they can be asynchronously interrupted and closed. So if a thread is blocked in an I/O opera tion on a channel, another thread can interrupt that blocked thread. Buffers hold data. Channels can fill and drain Buffers. Buffers replace the need for you to do your own buffer management using byte arrays. There are different types of Buffers like ByteBuff
  • 47. er, CharBuffer, DoubleBuffer, etc. A Selector class is responsible for multiplexing (combining multiple streams int o a single stream) by allowing a single thread to service multiple channels. Each Channel registers events with a Selector. When events arrive from clients, the Selector demultiplexes (separating a single stream into multip le streams) them and dispatches the events to corresponding Channels. To achieve non-blocking I/O a Channel clas s must work in conjunction with a Selector class. Design pattern: NIO uses a reactor design pattern, which demultiplexes events (s eparating single stream into multiple streams) and dispatches them to registered object handlers. The reactor pattern is similar to an observer pattern (aka publisher and subscriber design pattern), but an observer pattern h andles only a single source of events (i.e a single publisher with multiple subscribers) where a reactor patter n handles multiple event sources (i.e. multiple publishers with multiple subscribers). The intent of an observer pattern is to define a one-to-many depndency so that when one object (i.e the publisher) changes its state, all its dependents (i.e all its subscribers) are notfied and updated correspondingly. Another sought after functionality of NIO is its ability to map a file to memory . There is a specialized form of a Buffer known as MappedByteBuffer, which represents a buffer of bytes mapped to a file. To map a file to
  • 48. Java 27 MappedByteBuffer, you must first get a channel for a file. Once you get a channe l then you map it to a buffer and subsequently you can access it like any other ByteBuffer. Once you map an input file to a CharBuffer, you can do pattern matching on the file contents. This is similar to running grep on a UNIX f ile system. Another feature of NIO is its ability to lock and unlock files. Locks can be exc lusive or shared and can be held on a contiguous portion of a file. But file locks are subject to the control of the u nderlying operating system. Q 21: How can you improve Java I/O performance? PI BP A 21: Java applications that utilise Input/Output are excellent candidates for p erformance tuning. Profiling of Java applications that handle significant volumes of data will show significant time spent in I/O operations. This means substantial gains can be had from I/O performance tuning. Therefore, I/O efficie ncy should be a high priority for developers looking to optimally increase performance. The basic rules for speeding up I/O performance are . Minimise accessing the hard disk. . Minimise accessing the underlying operating system. . Minimise processing bytes and characters individually. Let us look at some of the techniques to improve I/O performance. CO .. Use buffering to minimise disk access and underlying operating system. As sho wn below, with buffering large chunks of a file are read from a disk and then accessed a byte or characte r at a time. W ithout buffering : inefficient code try{ File f = new File("m yFile.txt"); FileInputStream fis = new FileInputStream (f); int count = 0; int b = ; while((b = fis.read()) != -1){ if(b== 'n') { count++; } } // fis should be closed in a finally block. fis.close() ; } catch(IO Exception io){} Note: fis.read() is a native m ethod call to the underlying system . W ith B uffering: yields better perform ance try{
  • 49. File f = new File("myFile.txt"); FileInputStream fis = new FileInputStream (f); BufferedInputStream bis = new BufferedInputStream (fis); int count = 0; int b = ; while((b = bis.read()) != -1){ if(b== 'n') { count++; } } //bis should be closed in a finally block. bis.close() ; } catch(IO Exception io){} Note: bis.read() takes the next byte from the input buffer and only rarely access the underlying operating system . Instead of reading a character or a byte at a time, the above code with bufferin g can be improved further by reading one line at a time as shown below: FileReader fr = new FileReader(f); BufferedReader br = new BufferedReader(fr); While (br.readLine() != null) count++; By default the System.out is line buffered, which means that the output buffer i s flushed when a new line character is encountered. This is required for any interactivity between an inpu t prompt and display of output. The line buffering can be disabled for faster I/O operation as follows: FileOutputStream fos = new FileOutputStream(file); BufferedOutputStream bos = new BufferedOutputStream(fos, 1024); PrintStream ps = new PrintStream(bos,false); System.setOut(ps); while (someConditionIsTrue) System.out.println( blah blah ); } It is recommended to use logging frameworks like Log4J or apache commons logging , which uses buffering instead of using default behaviour of System.out.println( ..) for better performance. Frameworks like Log4J are configurable, flexible, extensible and easy to use.
  • 50. 28 Java . Use the NIO package, if you are using JDK 1.4 or later, which uses performance-e nhancing features like buffers to hold data, memory mapping of files, non-blocking I/O operations etc. . I/O performance can be improved by minimising the calls to the underlying operat ing systems. The Java runtime itself cannot know the length of a file, querying the file system for is Directory(), isFile(), exists() etc must query the underlying operating system. . Where applicable caching can be used to improve performance by reading in all th e lines of a file into a Java collection class like an ArrayList or a HashMap and subsequently access the data from an in-memory collection instead of the disk. Q 22: What is the main difference between shallow cloning and deep cloning of ob jects? DC LF MI PI A 22: The default behaviour of an object s clone() method automatically yields a s hallow copy. So to achieve a deep copy the classes must be edited or adjusted. Shallow copy: If a shallow copy is performed on obj-1 as shown in fig-2 then it is copied but its contained objects are not. The contained objects Obj-1 and Obj-2 are affected by changes to cloned Obj-2. Java supports shallow cloning of objects by default when a class implements the java.lang.Cloneable in terface. Deep copy: If a deep copy is performed on obj-1 as shown in fig-3 then not only obj-1 has been copied but the objects contained within it have been copied as well. Serialization can be used to achieve deep cloning. Deep cloning through serialization is faster to develop and easier to maintain but ca rries a performance overhead. Fig-2:Shallow cloning Fig-3:Deep cloning Shallow Vs Deep cloning Obj-1 c ontaine d Obj-1 contained Obj-2 Fig-1:O riginal O bject contains contains Obj-1 C loned Obj-2 c ontaine d Obj-1 contained Obj-2 Obj-1 c ontained Obj-1 c ontained
  • 51. Obj-2 C loned Obj-2 contain ed Obj-1 contained Obj-2 For example, invoking clone() method on a HashMap returns a shallow copy of Hash Map instance, which means the keys and values themselves are not cloned. If you want a deep copy then a si mple method is to serialize the HashMap to a ByteArrayOutputSream and then deserialize it. This creates a de ep copy but does require that all keys and values in the HashMap are Serializable. Its primary advantage is th at it will deep copy any arbitrary object graph. List some of the methods supported by Java object class? clone(), toString(), eq uals(Object obj), hashCode() .. refer Q16 in Java section, wait(), notify() .. refer Q42 in Java section, fin alize() etc. Q 23: What is the difference between an instance variable and a static variable? Give an example where you might use a static variable? LF A 23: Static variable Instance variable Class variables are called static variables. There is only one occurrence of a class variable per JVM per class loader. When a class is loaded the class variables (aka static variables) are initialised. Instance variables are non-static and there is one occurrence of an instance variable in each class instance (ie each object). A static variable is used in the singleton pattern. (Refer Q45 in Java section). A static variable is used with a final modifier to define constants. Q 24: Give an example where you might use a static method? LF
  • 52. Java 29 A 24: Static methods prove useful for creating utility classes, singleton classe s and factory methods (Refer Q45, Q46 in Java section). Utility classes are not meant to be instantiated. Improper coding of utility classes can lead to procedural coding. java.lang.Math, java.util.Collections etc are examples of uti lity classes in Java. Q 25: What are access modifiers? LF A 25: Modifier Used with Description public Outer classes, interfaces, constructors, Inner classes, methods and field variables A class or interface may be accessed from outside the package. Constructors, inner classes, methods and field variables may be accessed wherever their class is accessed. protected Constructors, inner classes, methods, and field variables. Accessed by other classes in the same package or any subclasses of the class in which they are referred (ie same package or different package). private Constructors, inner classes, methods and field variables, Accessed only within the class in which they are declared No modifier: (Package by default). Outer classes, inner classes, interfaces, constructors, methods, and field variables Accessed only from within the package in which they are declared. Q 26: Where and how can you use a private constructor? LF A 26: Private constructor is used if you do not want other classes to instantiat e the object. The instantiation is done by a public static method within the same class. . Used in the singleton pattern. (Refer Q45 in Java section). . Used in the factory method pattern (Refer Q46 in Java section). . Used in utility classes e.g. StringUtils etc. Q 27: What is a final modifier? Explain other Java modifiers? LF A 27: A final class can t be extended i.e. A final class may not be subclassed. A final method can t be overridden when its class is inherited. You can t change value of a final variable (i.e. it is a c onstant). Modifier Class Method Property static A static inner class is just an inner class associated with
  • 53. the class, rather than with an instance. cannot be instantiated, are called by classname.method, can only access static variables Only one instance of the variable exists. abstract Cannot be instantiated, must be a superclass, used whenever one or more methods are abstract. Method is defined but contains no implementation code (implementation code is included in the subclass). If a method is abstract then the entire class must be abstract. N/A synchronized N/A Acquires a lock on the class for static methods. Acquires a lock on the instance for non-static methods. N/A transient N/A N/A Field should not be serialized. final Class cannot be inherited Method cannot be overridden Makes the variable a constant. native N/A Platform dependent. No body, only signature. N/A Note: Be prepared for tricky questions on modifiers like, what is a volatile ? Or w hat is a const ? Etc. The reason it is tricky is that Java does have these keywords const and volatile as reserved, which means you c an t name your variables with these names but modifier const is not yet added in the language and the modifier volatile is very rarely used. The volatile modifier is used on member variables that may be modified simultaneou sly by other threads. Since other threads cannot see local variables, there is no need to mark local varibles as volatile. E.g. volatile int number; volatile private List listItems = null; etc. The modifier volatile only synchronizes the variable mark ed as volatile whereas synchronized modifier synchronizes all variables. Java uses the final modifier to declare constants. A final variable or constant declared as final has a value that is immutable and cannot be modified to refer to any other objects other than one it was initi alized to refer to. So the final modifier applies only to the value of the variable itself, and not to the object referenced by the var iable. This is where the const modifier can come in very useful if added to the Java language. A reference variable or a constant ma rked as const refers to an immutable object that cannot be modified. The reference variable itself can be modified, if it is not marked as final . The const modifier will be applicable only to non-primitive types. The primitive types should continue to u se the modifier final .
  • 54. 30 Java Q 28: What is the difference between final, finally and finalize() in Java? LF A 28: . final - constant declaration. Refer Q27 in Java section. . finally - handles exception. The finally block is optional and provides a mechan ism to clean up regardless of what happens within the try block (except System.exit(0) call). Use the finally block to close files or to release other system resources like database connections, statements etc. (Refer Q45 in Enterprise section) . finalize() - method helps in garbage collection. A method that is invoked before an object is discarded by the garbage collector, allowing it to clean up its state. Should not be used to rele ase non-memory resources like file handles, sockets, database connections etc because Java has only a finite n umber of these resources and you do not know when the garbage collection is going to kick in to release these non-memory resources through the finalize() method. Q 29: How does Java allocate stack and heap memory? Explain re-entrant, recursiv e and idempotent methods/functions? MI CI A 29: Each time an object is created in Java it goes into the area of memory kno wn as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables an d in the heap if they are member variables (i.e. fields of a class). In Java methods local variables are pushed i nto stack when a method is invoked and stack pointer is decremented when a method call is completed. In a multi-thr eaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space. The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronisation through your code. A method in stack is reentrant allowing multiple concurrent invocations that do not interfere with each other. A function is recursive if it calls itself. Given enough stack space, recursive me thod calls are perfectly valid in Java though it is tough to debug. Recursive functions are useful in removing iteratio ns from many sorts of algorithms. All recursive functions are re-entrant but not all re-entrant functions are recursiv e. Idempotent methods are methods, which are written in such a way that repeated calls to the same method with the same arguments yield same results. For example clustered EJBs, which are written with idempotent methods, can automatically recover from a
  • 55. server failure as long as it can reach another server. Jav a st ack & h e a p m e m o r y a l l o ca t i o n St a c k He a p p ubl i c c las s S t ac kR ef { p u b lic v o id f i r s t ( ) { s e c o n d ( ) ; //a f t e r } p u b lic v o id s e c o n d ( ) { C a r c = n e w C a r ( ) ; } } s e c ond( ) fi r s t( ) s e c ond( ) r e f c fi r s t( ) Ca r 1 2 3 4 Re f p ubl i c c las s H eapR ef { C a r c = n e w C a r( ); p u b lic v o id f i r s t ( ) { c = N e w C a r(); } } Ca r c Re f Ca r c Ca r 2 1 fi r s t( ) Q 30: Explain Outer and Inner classes (or Nested classes) in Java? When will you use an Inner Class? LF
  • 56. Java 31 A 30: In Java not all classes have to be defined separate from each other. You c an put the definition of one class inside the definition of another class. The inside class is called an inner class and t he enclosing class is called an outer class. So when you define an inner class, it is a member of the outer class in m uch the same way as other members like attributes, methods and constructors. Where should you use inner classes? Code without inner classes is more maintaina ble and readable. When you access private data members of the outer class, the JDK compiler creates pac kage-access member functions in the outer class for the inner class to access the private members. This leave s a security hole. In general we should avoid using inner classes. Use inner class only when an inner class is on ly relevant in the context of the outer class and/or inner class can be made private so that only outer class can access it. Inner classes are used primarily to implement helper classes like Iterators, Comparators etc which are used in the context of an outer class. CO Member inner class Anonymous inner class public class MyStack { private Object[] items = null; public Iterator iterator() { return new StackIterator(); } //inner class class StackIterator implements Iterator{ public boolean hasNext(){ } } } public class MyStack { private Object[] items = null; public Iterator iterator() { return new Iterator { public boolean hasNext() { } } } } Explain outer and inner classes? Class Type Description Example + Class name Outer Package Top level class. Only type JVM //package scope class member class or interface can recognize. class Outside{} Outside.class Inner static nested Defined within the context of the //package scope class class or
  • 57. interface top-level class. Must be static & can access static members of its containing class. No relationship between the instances of outside and Inside classes. class Outside { static class Inside{ } } Outside.class ,Outside$Inside.class Inner Member class Defined within the context of class Outside{ class outer class, but non-static. Until an object of Outside class has been created you can t create Inside. class Inside(){} } Outside.class , Outside$Inside.class Inner class Local class Defined within a block of code. Can use final local variables and final method parameters. Only visible within the block of code that defines it. class Outside { void first() { final int i = 5; class Inside{} } } Outside.class , Outside$1$Inside.class Inner class Anonymous class Just like local class, but no name is used. Useful when only one instance is used in a method. Most commonly used in AWT event model. class Outside{ void first() { button.addActionListener ( new ActionListener() { public void actionPerformed(ActionEvent e) { System.out.println( The button was pressed! ); } }); } } Outside.class , Outside$1.class
  • 58. 32 Java Q 31: What is type casting? Explain up casting vs down casting? When do you get ClassCastException? LF DP A 31: Type casting means treating a variable of one type as though it is another type. When up casting primitives as shown below from left to right, automatic conversi on occurs. But if you go from right to left, down casting or explicit casting is required. Casting in Java is safer than in C or other languages that allow arbitrary casting. Java only lets casts occur when they make sense, such a s a cast between a float and an int. However you can't cast between an int and a String (is an object in Java). byte .. short .. int .. long .. float .. double int i = 5; long j = i; //Right. Up casting or implicit casting byte b1 = i; //Wrong. Compile time error Type Mismatch . byte b2 = (byte) i ; //Right. Down casting or explicit casting is required. When it comes to object references you can always cast from a subclass to a supe rclass because a subclass object is also a superclass object. You can cast an object implicitly to a super class type (ie upcasting). If this were not the case polymorphism wouldn t be possible. Ob je c t Ve h ic le Ca r Bu s BM W Vehicle v1 = new Car(); //Right.upcasting or implicit casting Vehicle v2 = new V ehicle(); Car c0 = v1; //W rong. com pile tim e error "Type M ism atch". //Explicit or down casting is required Car c1 = (Car)v1; // Right. down casting or explicit casting. // v1 has knowledge of Car due to line1 Car c2 = (Car)v2; //W rong. R untim e exception ClassCastE xception //v2 has no knowledge of Car. Bus b1 = new BM W (); //W rong. com pile tim e error "Type M ism atch" Car c3 = new BMW (); //Right.upcasting or implicit casting Car c4 = (BMW ) v1; //W rong. Runtime exception ClassC astException Object o = v1; //v1 can only be upcast to its parent or Car c5 = (Car)v1; //v1 can be down cast to Car due to line 1. U p ca st in g vs D o w n ca st in g O b je c ts You can cast down the hierarchy as well but you must explicitly write the cast a nd the object must be a legitimate instance of the class you are casting to. The ClassCastException is t hrown to indicate that code has attempted to cast an object to a subclass of which it is not an instance. We can deal with the problem of incorrect casting in two ways: . Use the exception handling mechanism to catch ClassCastException. try{ Object o = new Integer(1);
  • 59. System.out.println((String) o); } catch(ClassCastException cce) { logger.log( Invalid casting, String is expected Not an Integer ); System.out.println(((Integer) o).toString()); } .. Use the instanceof statement to guard against incorrect casting. If(v2 instanceof Car) { Car c2 = (Car) v2; } Design pattern: The instanceof and typecast constructs are shown for the illustration purpose only. Using these constructs can be unmaintainable due to large if and elseif statemen ts and can affect performance if used in frequently accessed methods or loops. Look at using visit or design pattern to avoid these constructs. (Refer Q11 in How would you go about section ).
  • 60. Java 33 Points-to-ponder: We can also get a ClassCastException when two different class loaders load the same class because they are treated as two different classes. Q 32: What do you know about the Java garbage collector? When does the garbage c ollection occur? Explain different types of references in Java? LF MI A 32: Each time an object is created in Java, it goes into the area of memory kn own as heap. The Java heap is called the garbage collectable heap. The garbage collection cannot be forced. The garba ge collector runs in low memory situations. When it runs, it releases the memory allocated by an unreacha ble object. The garbage collector runs on a low priority daemon (background) thread. You can nicely ask the garbage collector to collect garbage by calling System.gc() but you can t force it. What is an unreachable object? An object s life has no meaning unless something ha s reference to it. If you can t reach it then you can t ask it to do anything. Then the object becomes unreach able and the garbage collector will figure it out. Java automatically collects all the unreachable objects peri odically and releases the memory consumed by those unreachable objects to be used by the future reachable objects . G a r b a g e C o l l e c t i on & U n r e a c ha bl e O b j e c t s re a c h a b l e re a c h a b l e C ase 1 C a r a = n e w C a r(); Ca r b = n e w Ca r ( ) 1r e f a C a r obj ec t 2r e f b C a r obj ec t C ase 2 a = n e w Ca r ( ) re a c h a b l e re a c h a b l e unr e a c h a b l e 2r e f b Ca r o b j e c t 3r e f a Ca r o b j e c t 1 Ca r o b j e c t C ase 3 a = b un r e a c h a bl e re a c h a b l e u n r ea c h ab l e refa Ca r o b j e c t r e f b Ca r o b j e c t 1
  • 61. C a r obj ec t 2 3 C ase 4 a = n u l l ; b = n u l l ; unr e a c h a bl e un r e a c h a bl e u n r ea ch ab l e Ca r o b j e c t Ca r o b j e c t 1 C a r obj ec t 2 3 He a p We can use the following options with the Java command to enable tracing for gar bage collection events. -verbose:gc reports on each garbage collection event. Explain types of references in Java? java.lang.ref package can be used to declar e soft, weak and phantom references. . Garbage Collector won t remove a strong reference. .. A soft reference will only get removed if memory is low. So it is useful for implementing caches while avoiding memory leaks. .. A weak reference will get removed on the next garbage collection cycle. Can b e used for implementing canonical maps. The java.util.WeakHashMap implements a HashMap with keys held by weak references. .. A phantom reference will be finalized but the memory will not be reclaimed. C an be useful when you want to be notified that an object is about to be collected. Q 33: If you have a circular reference of objects, but you no longer reference i t from an execution thread, will this object be a potential candidate for garbage collection? LF MI
  • 62. 34 Java A 33: Yes. Refer diagram below. Garbage Collecting Circular References sample code public void buildCar() { Car c = new Car(); Engine e = new Engine(); //lets create a circular reference c.engine = e; e.car = c; } buildCar() Stack Heap Car Engine Before buildCar() returns After buildCar() returns Stack Heap Car Engine Both the Car & Engine are not reachable and potential candidate for Garbage Collection. Q 34: Discuss the Java error handling mechanism? What is the difference between Runtime (unchecked) exceptions and checked exceptions? What is the implication of catching all the exceptions w ith the type Exception ? EH BP A 34: Errors: When a dynamic linking failure or some other hard failure in the virtual m achine occurs, the virtual machine throws an Error. Typical Java programs should not catch Errors. In addit ion, it s unlikely that typical Java programs will ever throw Errors either. Exceptions: Most programs throw and catch objects that derive from the Exception class. Exceptions indicate that a problem occurred but that the problem is not a serious JVM problem. An Ex ception class has many various types ofsubclasses. These descendants indicateexceptions that can occur. For example, NegativeArraySizeException indicates that a program attempted to create an array with a negative size. One exception subclass has special meaning in the Java language: RuntimeException. A ll the exceptions except RuntimeException are compiler checked exceptions. If a method is capable of thro wing a checked exception it must declare it in its method header or handle it in a try/catch block. Failure to do so raises a compiler error. So checked exceptions can, at compile time, greatly reduce the occurence of unhandl ed exceptions surfacing at runtime in a given application at the expense of requiring large throws declarat ions and encouraging use of poorlyconstructed try/catch blocks. Checked exceptions are present in other languages like C++, C#, and Python.
  • 63. Throw a b le and its subc la s s e s Ob je ct E xceptio n Erro r T h ro w able R untim eE xc eptio n IO E xceptio n N u llP o in te rE xc e p tio n LinkageE rro r Runtime Exceptions (unchecked exception) A RuntimeException class represents exceptions that occur within the Java virtua l machine (during runtime). An example of a runtime exception is NullPointerException. The cost of checking for the runtime exception often outweighs the benefit of catching it. Attempting to catch or specify all of them all the time would make your code unreadable and unmaintainable. The compiler allows runtime exceptions to go unca ught and unspecified. If you