You are on page 1of 107

Java concepts

Ramachandra Kamath A
12/9/2011




This documents covers all important concepts of core java and basic concept of JSP
2

1. Introduction to Java 12
What are different types of access modifiers in Java? 12
What is the use of final keyword? 12
What is use of synchronized keyword? 13
What is volatile keyword? 13
What is a transient variable? 13
What is a strictfp modifier? 14
What is a static variable? 14
What is a static method? 15
Why static methods cannot access non static variables or methods? 16
What is static class ? 16
What is throw keyword? 16
What is use of throws keyword? 17
2. Key Concepts in Java 17
Why is main() method static? 17
What is the difference between static methods and instance methods? 17
Can static block throw exception? 17
What is difference between abstract class and interface? 18
Explain with example to describe when to use abstract class and interface? 18
Does java support multiple interitance? Why? 19
Can this keyword be assigned null value? 20
What are the different types of references in java? 20
How to change the heap size of a JVM? 20
What is difference between instanceof and isInstance(Object obj)? 21
Java supports pass by value or pass by reference? 21
What is memory leak? 22
What is the difference between equals() and ==? 22
How to make sure that Childclass method actually overrides the method of the superclass? 23
How to find the size of an object? 23
Can an abstract class have a static method? 23
Can an abstract class have a constructor? 24
Why static methods cannot access non static variables or methods? 24
3

What is difference between stringbuffer and stringbuilder? 24
Consider a scenario in which the admin want to sure that if some one has written System.exit() at some part of
application then before system shutdown all the resources should be released. How is it possible? 24
What is the difference between final, finally and finalize() in Java? 25
How does Java allocate stack and heap memory? 25
Explain re-entrant, recursive and idempotent methods/functions? 25
Can a private variable or method of a class can be accessed? 26
What is difference between static block and the init block? Or Difference between Static {} and {} 26
Why inner class can access only final variable? 26
What is fully abstract class? 27
What is dynamic binding and static binding? 27
What is Java Reflection? 27
When an obj is passed through a function , one can set the properties but cannot set a new memory location?
28
3. OOPS Concept 28
What is polymorphism? 28
What is inheritance? 29
What is multiple inheritance and does java support? 30
What is abstraction? 30
What is encapsulation? 30
What is Association? 30
What is Aggregation? 31
What is Composition? 31
4. Collections Questions 31
What is difference between ArrayList and vector? 31
How can Arraylist be synchronized without using Vector? 31
If an Employee class is present and its objects are added in an arrayList. Now I want the list to be sorted on the
basis of the employeeID of Employee class. What are the steps? 32
What is difference between HashMap and HashTable? 32
What are the classes implementing List interface? 32
Which all classes implement Set interface? 33
What is difference between List and a Set? 33
What is difference between Arrays and ArrayList ? 33
4

When to use ArrayList or LinkedList ? 34
Consider a scenario. If an ArrayList has to be iterate to read data only, what are the possible ways and which
is the fastest? 34
Now another question with respect to above question is if accessing through iterator is slow then why do we
need it and when to use it. 34
Which design pattern Iterator follows? 34
Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of ArrayList<String> = new
ArrayList<String>(); 35
What is difference between iterator access and index access? 35
How to sort list in reverse order? 36
Can a null element added to a Treeset or HashSet? 36
How to sort list of strings - case insensitive? 36
How to make a List (ArrayList,Vector,LinkedList) read only? 36
What is ConcurrentHashMap? 36
Which is faster to iterate LinkedHashSet or LinkedList? 36
Which data structure HashSet implements 36
Arrange in the order of speed - HashMap,HashTable, Collections.synchronizedMap,concurrentHashmap 37
What is identityHashMap? 37
What is WeakHashMap? 37
5. Exceptions Questions 37
What is an Exception? 37
Exceptions are defined in which java package? 37
How are the exceptions handled in java? 37
Explain the exception hierarchy in java. 37
What is Runtime Exception or unchecked exception? 38
What is checked exception? 38
What is difference between Error and Exception? 38
What is difference between ClassNotFoundException and NoClassDefFoundError? 38
What is throw keyword? 39
What is use of throws keyword? 39
What are the possible combination to write try, catch finally block? 40
How to create custom Exception? 40
When to make a custom checked Exception or custom unchecked Exception? 41
5

What is StackOverflowError? 41
Why did the designers decide to force a method to specify all uncaught checked exceptions that can be thrown
within its scope? 41
Once the control switches to the catch block does it return back to the try block to execute the balance code?41
Where is the clean up code like release of resources is put in try-catch-finally block and why? 41
Is it valid to have a try block without catch or finally? 42
Is it valid to place some code in between try the catch/finally block that follows it? 42
What happens if the exception is never caught and throws down the method stack? 42
How do you get the descriptive information about the Exception occurred during the program execution? 42
Can you catch more than one exceptions in a single catch block? 42
Why is not considered as a good practice to write a single catchall handler to catch all the exceptions? 43
What is exception matching? 43
What happens if the handlers for the most specific exceptions is placed above the more general exceptions
handler? 43
Does the order of the catch blocks matter if the Exceptions caught by them are not subtype or supertype of
each other? 44
What happens if a method does not throw an checked Exception directly but calls a method that does? What
does 'Ducking' the exception mean? 44
Is an empty catch block legal? 45
Can a catch block throw the exception caught by itself? 46
6. Threads Questions 46
What is a Thread? 46
What is difference between thread and process? 46
What are the advantages or usage of threads? 47
What are the two ways of creating thread? 48
What are the different states of a thread's lifecycle? 48
What is use of synchronized keyword? 49
What is the difference when the synchronized keyword is applied to a static method or to a non static method?
49
What is a volatile keyword? 49
What is the difference between yield() and sleep()? 50
What is the difference between wait() and sleep()? 50
What is difference between notify() and notfiyAll()? 50
What happens if a start method is not invoked and the run method is directly invoked? 50
6

What happens when start() is called? 50
If code running is a thread creates a new thread what will be the initial priority of the newly created thread?
51
When jvm starts up, which thread will be started up first? 51
What are the daemon threads? 51
What all constructors are present in the Thread class? 51
Can the variables or classes be Synchronized? 51
How many locks does an object have? 51
Can a class have both Synchronized and non-synchronized methods? 51
If a class has a synchronised method and non-synchronised method, can multiple threads execute the non-
synchronised methods? 52
If a thread goes to sleep does it hold the lock? 52
Can a thread hold multiple locks at the same time? 52
Can a thread call multiple synchronized methods on the object of which it hold the lock? 52
Can static methods be synchronized? 52
Can two threads call two different static synchronized methods of the same class? 52
Does a static synchronized method block a non-static synchronized method? 52
Once a thread has been started can it be started again? 52
When does deadlock occur and how to avoid it? 53
What is a better way of creating multithreaded application? Extending Thread class or implementing
Runnable? 53
Can the start() method of the Thread class be overridden? If yes should it be overridden? 53
What are the methods of the thread class used to schedule the threads? 53
Which thread related methods are available in Object class? 53
Which thread related methods are available in Thread class? 53
List the methods which when called the thread does not release the locks held? 54
List the methods which when called on the object the thread releases the locks held on that object? 54
Does each thread has its own thread stack? 54
What is thread starvation? 54
What is threadLocal variable? 54
7. Inner Class Questions 55
What is an inner class? 55
What are the different types of inner classes? 55
7

What is static member class? 55
What are non static inner classes? 56
Does a static nested class have access to the enclosing class' non-static methods or instance variables? 58
What are the advantages of Inner classes? 58
What are disadvantages of using inner classes? 59
What are different types of anonymous classes? 59
If you compile a file containing inner class how many .class files are created and what are all of them
accessible in usual way? 60
How to access the inner class from code within the outer class? 60
How to create an inner class instance from outside the outer class instance code? 61
How to refer to the outer this i.e. outer classs current instance from inside the inner class? 61
Which modifiers can be applied to the inner class? 61
Can the method local inner class object access methods local variables? 62
Can a method local inner class access the local final variables?Why? 62
Which modifiers can be applied to the method local inner class? 62
Can a local class declared inside a static method have access to the instance members of the outer class? 62
Can a method which is not in the definition of the superclass of an anonymous class be invoked on that
anonymous class reference? 62
Can an anonymous class define method of its own? 63
Can an anonymous class implement multiple interfaces directly? 63
Can an anonymous class implement an interface and also extend a class at the same time? 63
8. Serialization Questions 63
What is Serialization? 63
What is use of serialVersionUID? 64
What is the need of Serialization? 64
Other than Serialization what are the different approach to make object Serializable? 65
Do we need to implement any method of Serializable interface to make an object serializable? 65
What happens if the object to be serialized includes the references to other serializable objects? 65
What happens if an object is serializable but it includes a reference to a non-serializable object? 65
Are the static variables saved as the part of serialization? 66
What is a transient variable? 66
What will be the value of transient variable after de-serialization? 67
8

Does the order in which the value of the transient variables and the state of the object using the
defaultWriteObject() method are saved during serialization matter? 68
How can one customize the Serialization process? or What is the purpose of implementing the writeObject()
and readObject() method? 68
If a class is serializable but its superclass in not , what will be the state of the instance variables inherited from
super class after deserialization? 69
To serialize an array or a collection all the members of it must be serializable. True /False? 70
9. Immutable Class Questions 70
What is an immutable class? 70
How to create an immutable class? 71
Immutable objects are automatically thread-safe true/false? 71
Which classes in java are immutable? 71
What are the advantages of immutability? 72
10. Cloning questions 72
What are different types of cloning in Java? 72
What is Shallow copy? 72
What is deep copy and how it can be acheived? 72
What is difference between deep and shallow cloning? 74
What are the characteristics of a shallow clone? 74
What are the disadvantages of deep cloning? 74
11. Garbage Collections Questions 74
Which part of the memory is involved in Garbage Collection? Stack or Heap? 74
What is responsiblity of Garbage Collector? 74
Is garbage collector a dameon thread? 75
Garbage Collector is controlled by whom? 75
When does an object become eligible for garbage collection? 75
What are the different ways to make an object eligible for Garbage Collection when it is no longer needed? 75
Can the Garbage Collection be forced by any means? 77
How can the Garbage Collection be requested? 77
What is the purpose of overriding finalize() method? 77
If an object becomes eligible for Garbage Collection and its finalize() method has been called and inside this
method the object becomes accessible by a live thread of execution and is not garbage collected. Later at some
point the same object becomes eligible for Garbage collection, will the finalize() method be called again? 77
9

How many times does the garbage collector calls the finalize() method for an object? 77
What 77
What are different ways to call garbage collector? 77
How to enable/disable call of finalize() method of exit of the application 77
12. JSP questions 78
What is a JSP? What is it used for? What do you understand by the term JSP translation phase or compilation
phase? 78
Explain the life cycle methods of a JSP? 78
What are different type of scripting elements? 78
What are the different scope values or what are the different scope values for "jsp:usebean"? 79
What are the differences between static and a dynamic include? 79
Is JSP variable declaration thread safe? 80
Explain JSP URL mapping? What is URL hiding or protecting the JSP page? 80
What are custom tags? Explain how to build custom tags? 80
What is the difference between custom JSP tags and JavaBeans? 82
What is a Expression? 82
Difference between forward and sendRedirect? 82
What are implicit objects? List them? 82
How do I prevent the output of my JSP or Servlet pages from being cached by the browser? 83
How to implement a thread-safe JSP page? What are the advantages and Disadvantages of using it? 83
Why to use the HttpServlet Init method to perform expensive operations that need only be done once? 84
Why is it not a good practice to create HttpSessions in JSPs by default? 84
What are the standard actions available in JSP? 84
13. JDBC questions and answers 84
What are the steps involved in establishing a JDBC connection? 84
How can you load the drivers? 84
What will Class.forName do while loading drivers? 85
How can you make the connection? 85
How can you create JDBC statements and what are they? 85
How can you retrieve data from the ResultSet? 85
What are the different types of Statements? 86
How can you use PreparedStatement? 86
10

What does setAutoCommit do? 86
How do you call a stored procedure from JDBC? 87
How do I retrieve warnings? 87
How can you move the cursor in scrollable result sets? 88
Whats the difference between TYPE_SCROLL_INSENSITIVE,and TYPE_SCROLL_SENSITIVE? 88
How to Make Updates to Updatable Result Sets? 89
14. Reading XML in JAVA 90
15. Reading properties file in JAVA 91
16. DataSource in JAVA 92
17. StringTokenizer in JAVA 92
18. Collection in details 92
19. Collection Subtypes 93
20. Adding and Removing Elements 94
21. Checking if a Collection Contains a Certain Element 96
22. Collection Size 96
23. Iterating a Collection 96
24. List Implementations 97
25. Adding and Accessing Elements 97
26. Removing Elements 99
27. Generic Lists 99
28. Set Implementations 99
29. Adding and Accessing Elements 100
30. Removing Elements 101
31. Generic Sets 101
32. Map Implementations 102
33. Adding and Accessing Elements 102
11

34. Removing Elements 103
35. Generic Maps 103
36. Array list 104
37. Hash Map 105


















12

1. Introduction to Java
What are different types of access modifiers in Java?
Ans) There are four different types of modifiers:
Modifer Accessible in the same package Accessible in different package
Private No No
Protected Yes Yes, only if the class extends
the main class
Default Yes No
Public Yes Yes
What is the use of final keyword?
Ans) The final keyword can be assigned to
1. Class level variable
2. method
3. class
4. Objects
If a final is assigned to a variable, the variable behaves as a constant. It means that the value
of variable once set cannot be changed.
final int i=1;
i =5; // error
If a final is assigned to a method then it cannot be overridden in its child class.
class Parent {
final void print(){
System.out.println(Inside);
}
}
class Child extends Parent{
public final void print(){ // error cannot override final method
13

System.out.println(Inside);
}
}
If a class is made as final, then no other class can extend it and make it as parent class. E.g.
String Class.
Final objects are instantiated only once. i.e
final Map map = new HashMap();
map.put(key,value);
map = new HashMap(); // error
What is use of synchronized keyword?
Ans) This keyword is used to prevent concurrency. Synchronized keyword can be applied
to static/non-static methods or a block of code. Only one thread at a time can access
synchronized methods and if there are multiple threads trying to access the same method
then other threads have to wait for the execution of method by one thread. Synchronized
keyword provides a lock on the object and thus prevents race condition. E.g.
public void synchronized method(){}
public void synchronized staticmethod(){}
public void myMethod(){
synchronized (this){ // synchronized keyword on block of code
}
}
What is volatile keyword?
Ans) In general each thread has its own copy of variable, such that one thread is not
concerned with the value of same variable in the other thread. But sometime this may not
be the case. Consider a scenario in which the count variable is holding the number of times
a method is called for a given class irrespective of any thread calling, in this case
irrespective of thread access the count has to be increased. In this case the count variable is
declared as volatile. The copy of volatile variable is stored in the main memory, so every
time a thread access the variable even for reading purpose the local copy is updated each
time from the main memory. The volatile variable also have performance issues.
What is a transient variable?
14

Ans) If some of the properties of a class are not required to be serialized then the varaibles
are marked as transient. When an object is deserialized the transient variables retains the
default value depending on the type of variable declared and hence lost its original value.
What is a strictfp modifier?
Ans) Strictfp is used with variable only . It is used to restrict floating point calculations ( fp )
to ensure portability ( platform Independent ). When this modifier is specified, the JVM
adheres to the Java specifications ( IEEE-754 floating-point specification ) and returns the
consistent value independent of the platform. That is, if you want the answers from your
code (which uses floating point values) to be consistent in all platforms, then you need to
specify the strictfp modifier.
What is a static variable?
Ans) Static keyword can be used with the variables and methods but not with the class but
there are static class. Anything declared as static is related to class and not objects.
Static variable : Multiples objects of a class shares the same instance of a static
variable.Consider the example:
public class Counter{
private static int count=0;
private int nonStaticcount=0;
public void incrementCounter(){
count++;
nonStaticcount++;
}
public int getCount(){
return count;
}
public int getNonStaticcount(){
return nonStaticcount;
}
15

public static void main(String args[]){
Counter countObj1 = new Counter();
Counter countObj2 = new Counter();
countObj1.incrementCounter();
countObj1.incrementCounter();
System.out.println("Static count for Obj1: "+countObj1.getCount());
System.out.println("NonStatic count for Obj1: "+countObj1.getNonStaticcount());
System.out.println("Static count for Obj2: "+countObj2.getCount())
System.out.println("NonStatic count for Obj2: "+countObj2.getNonStaticcount())
}
Output
Static count for Obj1: 2
NonStatic count for Obj1: 2
Static count for Obj2: 2
NonStatic count for Obj2: 0
In the above program obj1 and obj2 share the same instance of static variable count hence
if the value is incremented by one object , the incremented value will be reflected across
the other objects.
What is a static method?
Ans)A method defined as static is called static method. A static method can be accessed
without creating the objects. Just by using the Class name the method can be accessed.
Static method can only access static variables and not local or global non-static variables.
For eg:
public class Test{
public static void printMe(){
System.out.println("Hello World");
}
16

}
public class MainClass{
public static void main(String args[]){
Test.printMe()

}
}
OutPut:
Hello World
Also static method can call only static methods and not non static methods. But non-static
methods can call static mehtods.
Why static methods cannot access non static variables or methods?
Ans) A static method cannot access non static variables or methods because static methods
doesnt need the object to be accessed. So if a static method has non static variables or non
static methods which has instantiated variables they will no be intialized since the object is
not created and this could result in an error.
What is static class ?
Ans) A class cannot be declared static. But a class can be said a static class if all the
variables and methods of the class are static and the constructor is private. Making the
constructor private will prevent the class to be instantiated. So the only possibility to
access is using Class name only
What is throw keyword?
Ans) Throw keyword is used to throw the exception manually. It is mainly used when the
program fails to satisfy the given condition and it wants to warn the application.The
exception thrown should be subclass of Throwable.
public void parent(){
try{
child();
}catch(MyCustomException e){ }
}


public void child{
String iAmMandatory=null;
if(iAmMandatory == null){
throw (new MyCustomException("Throwing exception using throw keyword");
}
}
17

What is use of throws keyword?
Ans) If the function is not capable of handling the exception then it can ask the calling
method to handle it by simply putting the throws clause at the function declaration.
public void parent(){
try{
child();
}catch(MyCustomException e){ }
}


public void child throws MyCustomException{
//put some logic so that the exception occurs.
}
2. Key Concepts in Java
Why is main() method static?
Ans) To access the static method the object of the class is not needed. The method can be
access directly with the help of ClassName. So when a program is started the jvm search for
the class with main method and calls it without creating an object of the class.
What is the difference between static methods and instance methods?
Ans) instance method belongs to the instance of a class therefore it requires an instance
before it can be invoked, whereas static method belongs to the class itself and not to any
class instance so it doesnt need an instance to be invoked.
Instance methods use dynamic (late) binding, whereas static methods use static (early)
binding.
When the JVM invokes a class instance method, it selects the method to invoke based on the
type of the object reference, which is always known at run-time. On the other hand, when
the JVM invokes a static method, it selects the method to invoke based on the actual class of
the object, which may only be known at compile time.
Can static block throw exception?
Ans) Yes, static block can throw only Runtime exception or can use a try-catch block to
catch checked exception.
Typically scenario will be if JDBC connection is created in static block and it fails then
exception can be caught, logged and application can exit. If System.exit() is not done, then
application may continue and next time if the class is referred JVM will throw
NoClassDefFounderror since the class was not loaded by the Classloader.
18

What is difference between abstract class and interface?
Ans) 1) A class is called abstract when it contains at least one abstract method. It can also
contain n numbers of concrete method.Interface can contain only abstract( non
implemented) methods.
2) The abstract class can have public,private,protect or default variables and also
constants. In interface the variable is by default public final. In nutshell the interface
doesnt have any variables it only has constants.
3) A class can extend only one abstract class but a class can implement multiple
interfaces.
4) If an interface is implemented its compulsory to implement all of its methods but if an
abstract class is extended its not compulsory to implement all methods. 5) The problem
with an interface is, if you want to add a new feature (method) in its contract, then you
MUST implement those method in all of the classes which implement that interface.
However, in the case of an abstract class, the method can be simply implemented in the
abstract class and the same can be called by its subclass.
Explain with example to describe when to use abstract class and interface?
Ans) Consider a scenario where all Cars will have 4 tyres and other features can be
different.
In this case any subclass of Car has to have 4 tyres. This is a case where abstract class will
be used and a default implementaion for tyres will be provided.

public abstract class Car{

public abstract String getCarName();

public final int getNoOfTyres(){
return 4;
}

}
Consider a scenario where Cars can have any number of tyres and other features can also
be different. In this case interface will be created.

public interface Car{

public abstract String getCarName();
public abstract int getNoOfTyres();
}
19

Does java support multiple interitance? Why?
Ans) Java doesnt support multiple inheritance but it provide a way through which it can
enact it.
Consider the scenario is C++
Class A{

public void add(){
// some text
}
}

Class B{

public void add(){
// some text
}
}

Class C extends A,B{

public static void main(String arg[]){

C objC = new C();
objC.add(); // problem, compiler gets confused and cant
decide to call Class A or B method.
}
This problem is called Diamond problem.

This problem in java is taken care with the use of interfaces
In Java similar problem would look like:
interface A{
add();
}

interface B{
add();
}

class C implements A,B{

20

add(){
// doesnt matter which interface it belong to
}
}
Can this keyword be assigned null value?
Ans) No
What are the different types of references in java?
Ans) Java has a more expressive system of reference than most other garbage-collected
programming languages, which allows for special behavior for garbage collection. A normal
reference in Java is known as a strong reference. The java.lang.ref package defines three
other types of referencessoft, weak, and phantom references. Each type of reference is
designed for a specific use.
A SoftReference can be used to implement a cache. An object that is not reachable by a
strong reference (that is, not strongly reachable), but is referenced by a soft reference is
called softly reachable. A softly reachable object may be garbage collected at the discretion
of the garbage collector. This generally means that softly reachable objects will only be
garbage collected when free memory is low, but again, it is at the discretion of the garbage
collector. Semantically, a soft reference means "keep this object unless the memory is
needed."
A WeakReference is used to implement weak maps. An object that is not strongly or softly
reachable, but is referenced by a weak reference is called weakly reachable. A weakly
reachable object will be garbage collected during the next collection cycle. This behavior is
used in the class java.util.WeakHashMap. A weak map allows the programmer to put
key/value pairs in the map and not worry about the objects taking up memory when the
key is no longer reachable anywhere else. Another possible application of weak references
is the string intern pool. Semantically, a weak reference means "get rid of this object when
nothing else references it."

A PhantomReference is used to reference objects that have been marked for garbage
collection and have been finalized, but have not yet been reclaimed. An object that is not
strongly, softly or weakly reachable, but is referenced by a phantom reference is called
phantom reachable. This allows for more flexible cleanup than is possible with the
finalization mechanism alone. Semantically, a phantom reference means "this object is no
longer needed and has been finalized in preparation for being collected."
How to change the heap size of a JVM?
21

Ans) The old generation's default heap size can be overridden by using the -Xms and -Xmx
switches to specify the initial and maximum sizes respectively:
java -Xms <initial size> -Xmx <maximum size> program
For example:
java -Xms64m -Xmx128m program
What is difference between instanceof and isInstance(Object obj)?
Ans) Differences are as follows:
1) instanceof is a reserved word of Java, but isInstance(Object obj) is a method of
java.lang.Class.
if (obj instanceof MyType) {
...
}else if (MyType.class.isInstance(obj)) {
...
}
2) instanceof is used of identify whether the object is type of a particular class or its
subclass but isInstance(obj) is used to identify object of a particular class.
Java supports pass by value or pass by reference?
Ans) Java supports only pass by value. The arguments passed as a parameter to a method is
mainly primitive data types or objects. For the data type the actual value is passed.
Java passes the references by value just like any other parameter. This means the
references passed to the method are actually copies of the original references.Java copies
and passes the reference by value, not the object. Thus, method manipulation will alter the
objects, since the references point to the original objects.Consider the example:
public void tricky(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
22

System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}
OutPut:
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0
The method successfully alters the value of pnt1, even though it is passed by value;
however, a swap of pnt1 and pnt2 fails! This is the major source of confusion. In the main()
method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and
pnt2 to the tricky() method, Java passes the references by value just like any other
parameter. This means the references passed to the method are actually copies of the
original references.
What is memory leak?
Ans) A memory leak is where an unreferenced object that will never be used again still
hangs around in memory and doesnt get garbage collected.
What is the difference between equals() and ==?
Ans) == operator is used to compare the references of the objects.
public bollean equals(Object o) is the method provided by the Object class. The default
implementation uses == operator to compare two objects.
But since the method can be overriden like for String class. equals() method can be used to
compare the values of two objects.
String str1 = "MyName";
String str2 = "MyName";
String str3 = str2;

if(str1 == str2){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}

if(str1.equals(str2)){
System.out.println("Objects are equal")
}else{
23

System.out.println("Objects are not equal")
}

Output:

Objects are not equal
Objects are equal

String str2 = "MyName";
String str3 = str2;

if(str2 == str3){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}

if(str3.equals(str2)){
System.out.println("Objects are equal")
}else{
System.out.println("Objects are not equal")
}

OutPut:
Objects are equal
Objects are equal
How to make sure that Childclass method actually overrides the method of the
superclass?
Ans) The @Override annotation can be added to the javadoc for the new method. If you
accidently miss an argument or capitalize the method name wrong, the compiler will
generate a compile-time error.
How to find the size of an object?
Ans)The heap size of an object can be found using -
Runtime.totalMemory()-Runtime.freeMemory() .
Can an abstract class have a static method?
24

Ans) Yes an abstract class have a static method and it can be accessed by any other
class(even not a concrete class).
Can an abstract class have a constructor?
Ans) Yes an abstract class have a default and parameterized constructors.
Why static methods cannot access non static variables or methods?
Ans) A static method cannot access non static variables or methods because static methods
doesnt need the object to be accessed. So if a static method has non static variables or non
static methods which has instantiated variables they will no be intialized since the object is
not created and this could result in an error.
What is difference between stringbuffer and stringbuilder?
Ans) The only difference between StringBuffer and StringBuilder is that StringBuilder is
unsynchronized whereas StringBuffer is synchronized. So when the application needs to be
run only in a single thread then it is better to use StringBuilder. StringBuilder is more
efficient than StringBuffer.

Criteria to choose among StringBuffer and StringBuilder

1)If your text can change and will only be accessed from a single thread, use a StringBuilder
2)because StringBuilder is unsynchronized.

If your text can changes, and will be accessed from multiple threads, use a StringBuffer
because StringBuffer is synchronous.
Consider a scenario in which the admin want to sure that if some one has written
System.exit() at some part of application then before system shutdown all the
resources should be released. How is it possible?
Ans) This is possible using Runtime.getRuntime().addShutdownHook(Thread hook).

Straight from Java Spec:
This method registers a new virtual-machine shutdown hook.

The Java virtual machine shuts down in response to two kinds of events:
1. The program exits normally, when the last non-daemon thread exits or when the
exit (equivalently, System.exit) method is invoked, or
2. The virtual machine is terminated in response to a user interrupt, such as typing
^C, or a system-wide event, such as user logoff or system shutdown.
25

A shutdown hook is simply an initialized but unstarted thread. When the virtual machine
begins its shutdown sequence it will start all registered shutdown hooks in some
unspecified order and let them run concurrently. When all the hooks have finished it will
then run all uninvoked finalizers if finalization-on-exit has been enabled. Finally, the virtual
machine will halt. Note that daemon threads will continue to run during the shutdown
sequence, as will non-daemon threads if shutdown was initiated by invoking the exit
method.
Once the shutdown sequence has begun it can be stopped only by invoking the halt method,
which forcibly terminates the virtual machine.
What is the difference between final, finally and finalize() in Java?
Ans)
final - constant declaration. A final variable act as constant, a final class is immutable
and a final method cannot be ovrriden.
finally - handles exception. The finally block is optional and provides a mechanism 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.
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 release non-memory resources like file handles, sockets, database
connections etc because Java has only a finite number 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.
How does Java allocate stack and heap memory?
Ans) Each time an object is created in Java it goes into the area of memory known as
heap. The primitive variables like int and double are allocated in the stack, if they are
local method variables and in the heap if they are member variables (i.e. fields of a
class). In Java methods local variables are pushed into stack when a method is invoked
and stack pointer is decremented when a method call is completed.
In a multi-threaded 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.
Explain re-entrant, recursive and idempotent methods/functions?
Ans) A method in stack is re-entrant allowing multiple concurrent invocations that do
not interfere with each other.
A function is recursive if it calls itself. Given enough stack space, recursive method calls
are perfectly valid in Java though it is tough to debug. Recursive functions are useful in
removing iterations from many sorts of algorithms. Allrecursive functions are re-entrant
26

but not all re-entrant functions are recursive. 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.
Can a private variable or method of a class can be accessed?
Ans) Yes its possible using reflection.
What is difference between static block and the init block?
Or
Difference between
Static {} and {}
Ans) The static block is loaded when the class is loaded by the JVM for the 1st time only
whereas init {} block is loaded every time class is loaded. Also first the static block is loaded
then the init block.
public class LoadingBlocks {

static{
System.out.println("Inside static");
}

{
System.out.println("Inside init");
}
public static void main(String args[]){
new LoadingBlocks();
new LoadingBlocks();
new LoadingBlocks();
}
}

Output:

Inside static
Inside init
Inside init
Inside init
Why inner class can access only final variable?
Ans) Local classes can most definitely reference instance variables. The reason they cannot
reference non final local variables is because the local class instance can remain in memory
27

after the method returns. When the method returns the local variables go out of scope, so a
copy of them is needed. If the variables weren't final then the copy of the variable in the
method could change, while the copy in the local class didn't, so they'd be out of synch.
Anonymous inner classes require final variables because of the way they are implemented
in Java. An anonymous inner class (AIC) uses local variables by creating a private instance
field which holds a copy of the value of the local variable. The inner class isn't actually
using the local variable, but a copy. It should be fairly obvious at this point that a "Bad
Thing" can happen if either the original value or the copied value changes; there will be
some unexpected data synchronization problems. In order to prevent this kind of problem,
Java requires you to mark local variables that will be used by the AIC as final (i.e.,
unchangeable). This guarantees that the inner class' copies of local variables will always
match the actual values.
What is fully abstract class?
Ans) An abstract class which has all methods as abstract and all fields are public static final.
What is dynamic binding and static binding?
Ans) Method invocation
The Java programming language provides two basic kinds of methods: instance
methods and class (or static) methods. The difference are:
1. Instance methods require an instance before they can be invoked, whereas class
methods do not.
2. Instance methods use dynamic (late) binding, whereas class methods use static (early)
binding.
When the Java virtual machine invokes a class method, it selects the method to invoke
based on the type of the object reference, which is always known at compile-time. On
the other hand, when the virtual machine invokes an instance method, it selects the
method to invoke based on the actual class of the object, which may only be known at
run time.
What is Java Reflection?
Ans)Reflection is commonly used by programs which require the ability to examine or
modify the runtime behavior of applications running in the Java virtual machine.
Drawbacks of Reflection: Reflection is powerful, but should not be used indiscriminately.
If it is possible to perform an operation without using reflection, then it is preferable to
avoid using it. The following concerns should be kept in mind when accessing code via
reflection.
Performance Overhead: Because reflection involves types that are dynamically resolved,
certain Java virtual machine optimizations can not be performed. Consequently,
reflective operations have slower performance than their non-reflective counterparts,
and should be avoided in sections of code which are called frequently in performance-
sensitive applications.
Security Restrictions: Reflection requires a runtime permission which may not be
28

present when running under a security manager. This is in an important consideration
for code which has to run in a restricted security context, such as in an Applet.
Exposure of Internals: Since reflection allows code to perform operations that would be
illegal in non-reflective code, such as accessing private fields and methods, the use of
reflection can result in unexpected side-effects, which may render code dysfunctional
and may destroy portability. Reflective code breaks abstractions and therefore may
change behavior with upgrades of the platform.
When an obj is passed through a function , one can set the properties but cannot set a
new memory location?
Ans) It is because when u pass an object the address value is passed and stored in some
new address . like if address 1234 is passed , it is stored in 4567 location. So if u change in
the value of an object it will take the address from 4567 and do 1234.setXXX(). If u set the
object to null it will set 4567=null.
3. OOPS Concept
What is polymorphism?
Ans) Polymorphism gives us the ultimate flexibility in extensibility. The abiltiy to define
more than one function with the same name is called Polymorphism. In java,c++ there are
two type of polymorphism: compile time polymorphism (overloading) and runtime
polymorphism (overriding).

When you override methods, JVM determines the proper methods to call at the programs
run time, not at the compile time. Overriding occurs when a class method has the same
name and signature as a method in parent class.
Overloading occurs when several methods have same names with
Overloading is determined at the compile time.
Different method signature and different number or type of parameters.
Same method signature but different number of parameters.
Same method signature and same number of parameters but of different type
Example of Overloading
int add(int a,int b)
float add(float a,int b)
float add(int a ,float b)
void add(float a)
int add(int a)
void add(int a) //error conflict with the method int add(int a)
Example: Overloading
29

Class BookDetails{
String title;
String publisher;
float price;
setBook(String title){
}
setBook(String title, String publisher){
}
setBook(String title, String publisher,float price){
}

}
Example: Overriding
class BookDetails{
String title;
setBook(String title){ }
}
class ScienceBook extends BookDetails{
setBook(String title){} //overriding
setBook(String title, String publisher,float price){ } //overloading
}
What is inheritance?
Ans) Inheritance is the property which allows a Child class to inherit some properties from
its parent class. In Java this is achieved by using extends keyword. Only properties with
access modifier public and protected can be accessed in child class.
public class Parent{
public String parentName;
public int parentage;
public String familyName;
}
public class Child extends Parent{
30

public String childName;
public int childAge;
public void printMyName(){
System.out.println( My name is + chidName+ +familyName)
}
}
In above example the child has inherit its family name from the parent class just by
inheriting the class.
What is multiple inheritance and does java support?
Ans) If a child class inherits the property from multiple classes is known as multiple
inheritance.
Java does not allow to extend multiple classes but to overcome this problem it allows to
implement multiple Interfaces.
What is abstraction?
Ans) Abstraction is way of converting real world objects in terms of class. For example
creating a class Vehicle and injecting properties into it. E.g
public class Vehicle {
public String colour;
public String model;
}
What is encapsulation?
Ans) The encapsulation is achieved by combining the methods and attribute into a class.
The class acts like a container encapsulating the properties. The users are exposed mainly
public methods.The idea behind is to hide how thinigs work and just exposing the requests
a user can do.
What is Association?
Ans) Association is a relationship between two classes. In this relationship the object of
one instance perform an action on behalf of the other class. The typical behaviour can be
invoking the method of other class and using the member of the other class.
public class MyMainClass{
public void init(){
31

new OtherClass.init();
}
}
What is Aggregation?
Ans) Aggregation has a relationship between two classes. In this relationship the object of
one class is a member of the other class. Aggregation always insists for a direction.
public class MyMainClass{
OtherClass otherClassObj = new OtherClass();
}
What is Composition?
Ans) Composition is a special type of aggregation relationship with a difference that its the
compulsion for the OtherClass object (in previous example) to exist for the existence of
MyMainClass.
4. Collections Questions
What is difference between ArrayList and vector?
Ans: )
1) Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe. In Vector
class each method like add(), get(int i) is surrounded with a synchronized block and thus
making Vector class thread-safe.
2) Data growth - Internally, both the ArrayList and Vector hold onto their contents using an
Array. When an element is inserted into an ArrayList or a Vector, the object will need to
expand its internal array if it runs out of room. A Vector defaults to doubling the size of its
array, while the ArrayList increases its array size by 50 percent.
How can Arraylist be synchronized without using Vector?
Ans) Arraylist can be synchronized using:
Collection.synchronizedList(List list)
Other collections can be synchronized:
32

Collection.synchronizedMap(Map map)
Collection.synchronizedCollection(Collection c)
If an Employee class is present and its objects are added in an arrayList. Now I want
the list to be sorted on the basis of the employeeID of Employee class. What are the
steps?
Ans) 1) Implement Comparable interface for the Employee class and override the
compareTo(Object obj) method in which compare the employeeID
2) Now call Collections.sort() method and pass list as an argument.
Now consider that Employee class is a jar file.
1) Since Comparable interface cannot be implemented, create Comparator and override the
compare(Object obj, Object obj1) method .
2) Call Collections.sort() on the list and pass comparator as an argument.
What is difference between HashMap and HashTable?
Ans) Both collections implements Map. Both collections store value as key-value pairs. The
key differences between the two are
1. Hashmap is not synchronized in nature but hshtable is.
2. Another difference is that iterator in the HashMap is fail-safe while the enumerator for
the Hashtable isn't.
Fail-safe - if the Hashtable is structurally modified at any time after the iterator is
created, in any way except through the iterator's own remove method, the iterator will
throw a ConcurrentModificationException?
3. HashMap permits null values and only one null key, while Hashtable doesn't allow key or
value as null.
What are the classes implementing List interface?
Ans)
There are three classes that implement List interface:
1) ArrayList : It is a resizable array implementation. The size of the ArrayList can be
increased dynamically also operations like add,remove and get can be formed once the
object is created. It also ensures that the data is retrieved in the manner it was stored. The
ArrayList is not thread-safe.

2) Vector: It is thread-safe implementation of ArrayList. The methods are wrapped around
33

a synchronized block.

3) LinkedList: the LinkedList also implements Queue interface and provide FIFO(First In
First Out) operation for add operation. It is faster if than ArrayList if it performs insertion
and deletion of elements from the middle of a list.
Which all classes implement Set interface?
Ans) A Set is a collection that contains no duplicate elements. More formally, sets contain
no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element.
HashSet,SortedSet and TreeSet are the commnly used class which implements Set
interface.
SortedSet - It is an interface which extends Set. A the name suggest , the interface allows
the data to be iterated in the ascending order or sorted on the basis of Comparator or
Comparable interface. All elements inserted into the interface must implement Comparable
or Comparator interface.
TreeSet - It is the implementation of SortedSet interface.This implementation provides
guaranteed log(n) time cost for the basic operations (add, remove and contains). The class
is not synchronized.
HashSet: This class implements the Set interface, backed by a hash table (actually a
HashMap instance). It makes no guarantees as to the iteration order of the set; in
particular, it does not guarantee that the order will remain constant over time. This class
permits the null element. This class offers constant time performance for the basic
operations (add, remove, contains and size), assuming the hash function disperses the
elements properly among the buckets
What is difference between List and a Set?
Ans)
1) List can contain duplicate values but Set doesnt allow. Set allows only to unique
elements.
2) List allows retrieval of data to be in same order in the way it is inserted but Set doesnt
ensures the sequence in which data can be retrieved.(Except HashSet)
What is difference between Arrays and ArrayList ?
Ans) Arrays are created of fix size whereas ArrayList is of not fix size. It means that once
array is declared as :
1. int [] intArray= new int[6];
2. intArray[7] // will give ArraysOutOfBoundException.
Also the size of array cannot be incremented or decremented. But with arrayList the size is variable.
34

2. Once the array is created elements cannot be added or deleted from it. But with ArrayList
the elements can be added and deleted at runtime.
List list = new ArrayList();
list.add(1);
list.add(3);
list.remove(0) // will remove the element from the 1st location.
3. ArrayList is one dimensional but array can be multidimensional.
int[][][] intArray= new int[3][2][1]; // 3 dimensional array
4. To create an array the size should be known or initalized to some value. If not initialized
carefully there could me memory wastage. But arrayList is all about dynamic creation and
there is no wastage of memory.
When to use ArrayList or LinkedList ?
Ans) Adding new elements is pretty fast for either type of list. For the ArrayList, doing
random lookup using "get" is fast, but for LinkedList, it's slow. It's slow because there's no
efficient way to index into the middle of a linked list. When removing elements, using
ArrayList is slow. This is because all remaining elements in the underlying array of Object
instances must be shifted down for each remove operation. But here LinkedList is fast,
because deletion can be done simply by changing a couple of links. So an ArrayList works
best for cases where you're doing random access on the list, and a LinkedList works better
if you're doing a lot of editing in the middle of the list.
Source : Read More - from java.sun
Consider a scenario. If an ArrayList has to be iterate to read data only, what are the
possible ways and which is the fastest?
Ans) It can be done in two ways, using for loop or using iterator of ArrayList. The first
option is faster than using iterator. Because value stored in arraylist is indexed access. So
while accessing the value is accessed directly as per the index.
Now another question with respect to above question is if accessing through iterator
is slow then why do we need it and when to use it.
Ans) For loop does not allow the updation in the array(add or remove operation) inside the
loop whereas Iterator does. Also Iterator can be used where there is no clue what type of
collections will be used because all collections have iterator.
Which design pattern Iterator follows?
35

Ans) It follows Iterator design pattern. Iterator Pattern is a type of behavioral pattern. The
Iterator pattern is one, which allows you to navigate through a collection of data using a
common interface without knowing about the underlying implementation. Iterator should
be implemented as an interface. This allows the user to implement it anyway its easier for
him/her to return data. The benefits of Iterator are about their strength to provide a
common interface for iterating through collections without bothering about underlying
implementation.
Example of Iteration design pattern - Enumeration The class java.util.Enumeration is an
example of the Iterator pattern. It represents and abstract means of iterating over a
collection of elements in some sequential order without the client having to know the
representation of the collection being iterated over. It can be used to provide a uniform
interface for traversing collections of all kinds.
Why is it preferred to declare: List<String> list = new ArrayList<String>(); instead of
ArrayList<String> = new ArrayList<String>();
Ans) It is preferred because:
1. If later on code needs to be changed from ArrayList to Vector then only at the
declaration place we can do that.
2. The most important one If a function is declared such that it takes list. E.g void
showDetails(List list);
When the parameter is declared as List to the function it can be called by passing
any subclass of List like ArrayList,Vector,LinkedList making the function more
flexible
What is difference between iterator access and index access?
Ans) Index based access allow access of the element directly on the basis of index. The
cursor of the datastructure can directly goto the 'n' location and get the element. It doesnot
traverse through n-1 elements.
In Iterator based access, the cursor has to traverse through each element to get the desired
element.So to reach the 'n'th element it need to traverse through n-1 elements.
Insertion,updation or deletion will be faster for iterator based access if the operations are
performed on elements present in between the datastructure.
Insertion,updation or deletion will be faster for index based access if the operations are
performed on elements present at last of the datastructure.
Traversal or search in index based datastructure is faster.
ArrayList is index access and LinkedList is iterator access.
36

How to sort list in reverse order?
Ans) To sort the elements of the List in the reverse natural order of the strings, get a
reverse Comparator from the Collections class with reverseOrder(). Then, pass the reverse
Comparator to the sort() method.
List list = new ArrayList();
Comparator comp = Collections.reverseOrder();
Collections.sort(list, comp)
Can a null element added to a Treeset or HashSet?
Ans) A null element can be added only if the set contains one element because when a
second element is added then as per set defination a check is made to check duplicate value
and comparison with null element will throw NullPointerException.
HashSet is based on hashMap and can contain null element.
How to sort list of strings - case insensitive?
Ans) using Collections.sort(list, String.CASE_INSENSITIVE_ORDER);
How to make a List (ArrayList,Vector,LinkedList) read only?
Ans) A list implemenation can be made read only using
Collections.unmodifiableList(list). This method returns a new list. If a user tries to
perform add operation on the new list; UnSupportedOperationException is thrown.
What is ConcurrentHashMap?
Ans) A concurrentHashMap is thread-safe implementation of Map interface. In this class
put and remove method are synchronized but not get method. This class is different from
Hashtable in terms of locking; it means that hashtable use object level lock but this class
uses bucket level lock thus having better performance.
Which is faster to iterate LinkedHashSet or LinkedList?
Ans) LinkedList.
Which data structure HashSet implements
Ans) HashSet implements hashmap internally to store the data. The data passed to hashset
is stored as key in hashmap with null as value.
37

Arrange in the order of speed - HashMap,HashTable,
Collections.synchronizedMap,concurrentHashmap
Ans) HashMap is fastest, ConcurrentHashMap,Collections.synchronizedMap,HashTable.
What is identityHashMap?
Ans) The IdentityHashMap uses == for equality checking instead of equals(). This can be
used for both performance reasons, if you know that two different elements will never be
equals and for preventing spoofing, where an object tries to imitate another.
What is WeakHashMap?
Ans) A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap
will automatically be removed when its key is no longer in ordinary use. More precisely,
the presence of a mapping for a given key will not prevent the key from being discarded by
the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key
has been discarded its entry is effectively removed from the map, so this class behaves
somewhat differently than other Map implementations.
5. Exceptions Questions
What is an Exception?
Ans) The exception is said to be thrown whenever an exceptional event occurs in java
which signals that something is not correct with the code written and may give unexpected
result. An exceptional event is a occurrence of condition which alters the normal program
flow. Exceptional handler is the code that does something about the exception.
Exceptions are defined in which java package?
Ans)All the exceptions are subclasses of java.lang.Exception
How are the exceptions handled in java?
Ans)When an exception occurs the execution of the program is transferred to an
appropriate exception handler.The try-catch-finally block is used to handle the exception.
The code in which the exception may occur is enclosed in a try block, also called as a
guarded region.
The catch clause matches a specific exception to a block of code which handles that
exception.
And the clean up code which needs to be executed no matter the exception occurs or not is
put inside the finally block
Explain the exception hierarchy in java.
38

Ans) The hierarchy is as follows:

Throwable is a parent class off all Exception classes. They are two types of Exceptions:
Checked exceptions and UncheckedExceptions. Both type of exceptions extends Exception
class.
What is Runtime Exception or unchecked exception?
Ans) Runtime exceptions represent problems that are the result of a programming
problem. Such problems include arithmetic exceptions, such as dividing by zero; pointer
exceptions, such as trying to access an object through a null reference; and indexing
exceptions, such as attempting to access an array element through an index that is too large
or too small. Runtime exceptions need not be explicitly caught in try catch block as it can
occur anywhere in a program, and in a typical one they can be very numerous. Having to
add runtime exceptions in every method declaration would reduce a program's clarity.
Thus, the compiler does not require that you catch or specify runtime exceptions (although
you can). The solution to rectify is to correct the programming logic where the exception
has occurred or provide a check.
What is checked exception?
Ans) Checked exception are the exceptions which forces the programmer to catch them
explicitly in try-catch block. It is a subClass of Exception. Example: IOException.
What is difference between Error and Exception?
Ans) An error is an irrecoverable condition occurring at runtime. Such as OutOfMemory
error. These JVM errors and you can not repair them at runtime.Though error can be
caught in catch block but the execution of application will come to a halt and is not
recoverable.
While exceptions are conditions that occur because of bad input etc. e.g.
FileNotFoundException will be thrown if the specified file does not exist. Or a
NullPointerException will take place if you try using a null reference. In most of the cases it
is possible to recover from an exception (probably by giving user a feedback for entering
proper values etc.)
What is difference between ClassNotFoundException and NoClassDefFoundError?
Ans) A ClassNotFoundException is thrown when the reported class is not found by the
ClassLoader in the CLASSPATH. It could also mean that the class in question is trying to be
loaded from another class which was loaded in a parent classloader and hence the class
from the child classloader is not visible.
39

Consider if NoClassDefFoundError occurs which is something like
java.lang.NoClassDefFoundError
src/com/TestClass
does not mean that the TestClass class is not in the CLASSPATH. It means that the class
TestClass was found by the ClassLoader however when trying to load the class, it ran into
an error reading the class definition. This typically happens when the class in question has
static blocks or members which use a Class that's not found by the ClassLoader. So to find
the culprit, view the source of the class in question (TestClass in this case) and look for
code using static blocks or static members.
What is throw keyword?
Ans) Throw keyword is used to throw the exception manually. It is mainly used when the
program fails to satisfy the given condition and it wants to warn the application.The
exception thrown should be subclass of Throwable.
public void parent(){
try{
child();
}catch(MyCustomException e){ }
}


public void child{
String iAmMandatory=null;
if(iAmMandatory == null){
throw (new MyCustomException("Throwing exception using throw keyword");
}
}
What is use of throws keyword?
Ans) If the function is not capable of handling the exception then it can ask the calling
method to handle it by simply putting the throws clause at the function declaration.
public void parent(){
try{
child();
}catch(MyCustomException e){ }
}


40

public void child throws MyCustomException{
//put some logic so that the exception occurs.
}
What are the possible combination to write try, catch finally block?
Ans)
1) try{
//lines of code that may throw an exception
}catch(Exception e){
//lines of code to handle the exception thrown in try block
}finally{
//the clean code which is executed always no matter the exception occurs or not.
}
2 try{
}finally{}
3 try{
}catch(Exception e){
//lines of code to handle the exception thrown in try block
}
The catch blocks must always follow the try block. If there are more than one catch blocks
they all must follow each other without any block in between. The finally block must follow
the catch block if one is present or if the catch block is absent the finally block must follow
the try block.
How to create custom Exception?
Ans) To create you own exception extend the Exception class or any of its subclasses.
e.g.
41

1 class New1Exception extends Exception { } // this will create Checked Exception
2 class NewException extends IOExcpetion { } // this will create Checked exception
3 class NewException extends NullPonterExcpetion { } // this will create UnChecked
exception
When to make a custom checked Exception or custom unchecked Exception?
Ans) If an application can reasonably be expected to recover from an exception, make it a
checked exception. If an application cannot do anything to recover from the exception,
make it an unchecked exception.
What is StackOverflowError?
Ans) The StackOverFlowError is an Error Object thorwn by the Runtime System when it
Encounters that your application/code has ran out of the memory. It may occur in case of
recursive methods or a large amount of data is fetched from the server and stored in some
object. This error is generated by JVM.
e.g. void swap(){
swap();
}
Why did the designers decide to force a method to specify all uncaught checked
exceptions that can be thrown within its scope?
Ans) Any Exception that can be thrown by a method is part of the method's public
programming interface. Those who call a method must know about the exceptions that a
method can throw so that they can decide what to do about them. These exceptions are as
much a part of that method's programming interface as its parameters and return value.
Once the control switches to the catch block does it return back to the try block to
execute the balance code?
Ans) No. Once the control jumps to the catch block it never returns to the try block but it
goes to finally block(if present).
Where is the clean up code like release of resources is put in try-catch-finally block
and why?
Ans) The code is put in a finally block because irrespective of try or catch block execution
the control will flow to finally block. Typically finally block contains release of connections,
closing of result set etc.
42

Is it valid to have a try block without catch or finally?
Ans) NO. This will result in a compilation error. The try block must be followed by a catch
or a finally block. It is legal to omit the either catch or the finally block but not both.
e.g. The following code is illegal.
try{
int i =0;
}
int a = 2;
System.out.println(a = +a);
Is it valid to place some code in between try the catch/finally block that follows it?
Ans) No. There should not be any line of code present between the try and the catch/finally
block. e.g. The following code is wrong.
try{}
String str = ABC;
System.out.println(str = +str);
catch(Exception e){}
What happens if the exception is never caught and throws down the method stack?
Ans) If the exception is not caught by any of the method in the methods stack till you get to
the main() method, the main method throws that exception and the JVM halts its execution.
How do you get the descriptive information about the Exception occurred during the
program execution?
Ans) All the exceptions inherit a method printStackTrace() from the Throwable class. This
method prints the stack trace from where the exception occurred. It prints the most
recently entered method first and continues down, printing the name of each method as it
works its way down the call stack from the top.
Can you catch more than one exceptions in a single catch block?
Ans)Yes. If the exception class specified in the catch clause has subclasses, any exception
object that is a subclass of the specified Exception class will be caught by that single catch
block.
E.g..
try {
43

// Some code here that can throw an IOException
}
catch (IOException e) {
e.printStackTrace();
}
The catch block above will catch IOException and all its subclasses e.g.
FileNotFoundException etc.
Why is not considered as a good practice to write a single catchall handler to catch all
the exceptions?
Ans) You can write a single catch block to handle all the exceptions thrown during the
program execution as follows :
try {
// code that can throw exception of any possible type
}catch (Exception e) {
e.printStackTrace();
}
If you use the Superclass Exception in the catch block then you will not get the valuable
information about each of the exception thrown during the execution, though you can find
out the class of the exception occurred. Also it will reduce the readability of the code as the
programmer will not understand what is the exact reason for putting the try-catch block.
What is exception matching?
Ans) Exception matching is the process by which the the jvm finds out the matching catch
block for the exception thrown from the list of catch blocks. When an exception is thrown,
Java will try to find by looking at the available catch clauses in the top down manner. If it
doesn't find one, it will search for a handler for a supertype of the exception. If it does not
find a catch clause that matches a supertype for the exception, then the exception is
propagated down the call stack. This process is called exception matching.
What happens if the handlers for the most specific exceptions is placed above the
more general exceptions handler?
44

Ans) Compilation fails. The catch block for handling the most specific exceptions must
always be placed above the catch block written to handle the more general exceptions.
e.g. The code below will not compile.
1 try {
// code that can throw IOException or its subtypes
} catch (IOException e) {
// handles IOExceptions and its subtypes
} catch (FileNotFoundException ex) {
// handle FileNotFoundException only
}
The code below will compile successfully :-
try {
// code that can throw IOException or its subtypes
} catch (FileNotFoundException ex) {
// handles IOExceptions and its subtypes
} catch (IOException e){
// handle FileNotFoundException only
}
Does the order of the catch blocks matter if the Exceptions caught by them are not
subtype or supertype of each other?
Ans) No. If the exceptions are siblings in the Exception classs hierarchy i.e. If one Exception
class is not a subtype or supertype of the other, then the order in which their
handlers(catch clauses) are placed does not matter.
What happens if a method does not throw an checked Exception directly but calls a
method that does? What does 'Ducking' the exception mean?
Ans) If a method does not throw an checked Exception directly but calls a method that
throws an exception then the calling method must handle the throw exception or declare
the exception in its throws clause. If the calling method does not handle and declares the
exception, the exceptions is passed to the next method in the method stack. This is called as
ducking the exception down the method stack.
45

e.g. The code below will not compile as the getCar() method has not declared the
CarNotFoundException which is thrown by the getColor () method.
void getCar() {
getColor();
}
void getColor () {
throw new CarNotFoundException();
}
Fix for the above code is
void getCar() throws CarNotFoundException {
getColor();
}
void getColor () {
throw new CarNotFoundException();
}
Is an empty catch block legal?
Ans) Yes you can leave the catch block without writing any actual code to handle the
exception caught.
e.g. The code below is legal but not appropriate, as in this case you will nt get any
information about the exception thrown.
try{
//code that may throw the FileNotFoundException
}catch(FileNotFound eFnf){
//no code to handle the FileNotFound exception
}
46


Can a catch block throw the exception caught by itself?
Ans) Yes. This is called rethrowing of the exception by catch block.
e.g. the catch block below catches the FileNotFound exception and rethrows it again.
void checkEx() throws FileNotFoundException {
try{
//code that may throw the FileNotFoundException
}catch(FileNotFound eFnf){
throw FileNotFound();
}
}
6. Threads Questions
What is a Thread?
Ans) In Java, "thread" means two different things:
An instance of class java.lang.Thread.
A thread of execution.
An instance of Thread is justan object. Like any other object in Java, it has variables and
methods, and lives and dies on the heap. But a thread of execution is an individual process
(a "lightweight" process) that has its own call stack. In Java, there is one thread per call
stackor, to think of it in reverse, one call stack per thread. Even if you don't create any
new threads in your program, threads are back there running.
The main() method, that starts the whole ball rolling, runs in one thread, called
(surprisingly) the main thread. If you looked at the main call stack (and you can, any time
you get a stack trace from something that happens after main begins, but not within
another thread), you'd see that main() is the first method on the stack the method at the
bottom. But as soon as you create a new thread, a new stack materializes and methods
called from that thread run in a call stack that's separate from the main() call stack.
What is difference between thread and process?
47

Ans) Differences between threads and processes are:-
1. Threads share the address space of the process that created it; processes have their own
address.
2. Threads have direct access to the data segment of its process; processes have their own
copy of the data segment of the parent process.
3. Threads can directly communicate with other threads of its process; processes must use
interprocess communication to communicate with sibling processes.
4. Threads have almost no overhead; processes have considerable overhead.
5. New threads are easily created; new processes require duplication of the parent process.
6. Threads can exercise considerable control over threads of the same process; processes
can only exercise control over child processes.
7. Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of
the other threads of the process; changes to the parent process do not affect child
processes.
What are the advantages or usage of threads?
Ans)
Threads support concurrent operations. For example,
Multiple requests by a client on a server can be handled as an individual client thread.
Long computations or high-latency disk and network operations can be handled in the
background without disturbing foreground computations or screen updates.

Threads often result in simpler programs.
In sequential programming, updating multiple displays normally requires a big while-
loop that performs small parts of each display update. Unfortunately, this loop basically
simulates an operating system scheduler. In Java, each view can be assigned a thread to
provide continuous updates.
Programs that need to respond to user-initiated events can set up service routines to
handle the events without having to insert code in the main routine to look for these
events.

Threads provide a high degree of control.
Imagine launching a complex computation that occasionally takes longer than is
satisfactory. A "watchdog" thread can be activated that will "kill" the computation if it
becomes costly, perhaps in favor of an alternate, approximate solution. Note that sequential
programs must muddy the computation with termination code, whereas, a Java program
can use thread control to non-intrusively supervise any operation.

Threaded applications exploit parallelism.
48

A computer with multiple CPUs can literally execute multiple threads on different
functional units without having to simulating multi-tasking ("time sharing").
On some computers, one CPU handles the display while another handles computations or
database accesses, thus, providing extremely fast user interface response times.
What are the two ways of creating thread?
Ans) There are two ways to create a new thread.
1)Extend the Thread class and override the run() method in your class. Create an
instance of the subclass and invoke the start() method on it, which will create a new thread
of execution. e.g.
public class NewThread extends Thread{
public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
c.start();
}
}
2)Implements the Runnable interface.The class will have to implement the run() method
in the Runnable interface. Create an instance of this class. Pass the reference of this
instance to the Thread constructor a new thread of execution will be created. e.g. class
public class NewThread implements Runnable{
public void run(){
// the code that has to be executed in a separate new thread goes here
}
public static void main(String [] args){
NewThread c = new NewThread();
Thread t = new Thread(c);
t.start();
}
}
What are the different states of a thread's lifecycle?
Ans) The different states of threads are as follows:
49

1) New When a thread is instantiated it is in New state until the start() method is called
on the thread instance. In this state the thread is not considered to be alive.
2) Runnable The thread enters into this state after the start method is called in the
thread instance. The thread may enter into the Runnable state from Running state. In this
state the thread is considered to be alive.
3) Running When the thread scheduler picks up the thread from the Runnable threads
pool, the thread starts running and the thread is said to be in Running state.
4) Waiting/Blocked/Sleeping In these states the thread is said to be alive but not
runnable. The thread switches to this state because of reasons like wait method called or
sleep method has been called on the running thread or thread might be waiting for some
i/o resource so blocked. 5) Dead When the thread finishes its execution i.e. the run()
method execution completes, it is said to be in dead state. A dead state can not be started
again. If a start() method is invoked on a dead thread a runtime exception will occur.
What is use of synchronized keyword?
Ans) synchronized keyword can be applied to static/non-static methods or a block of code.
Only one thread at a time can access synchronized methods and if there are multiple
threads trying to access the same method then other threads have to wait for the execution
of method by one thread. Synchronized keyword provides a lock on the object and thus
prevents race condition. E.g.
public void synchronized method(){}
public void synchronized staticmethod(){}
public void myMethod(){
synchronized (this){ // synchronized keyword on block of code
}
}
What is the difference when the synchronized keyword is applied to a static method
or to a non static method?
Ans) When a synch non static method is called a lock is obtained on the object. When a
synch static method is called a lock is obtained on the class and not on the object. The lock
on the object and the lock on the class dont interfere with each other. It means, a
thread accessing a synch non static method, then the other thread can access the synch
static method at the same time but cant access the synch non static method.
What is a volatile keyword?
Ans) In general each thread has its own copy of variable, such that one thread is not
concerned with the value of same variable in the other thread. But sometime this may not
be the case. Consider a scenario in which the count variable is holding the number of times
a method is called for a given class irrespective of any thread calling, in this case
50

irrespective of thread access the count has to be increased so the count variable is declared
as volatile. The copy of volatile variable is stored in the main memory, so every time a
thread access the variable even for reading purpose the local copy is updated each time
from the main memory. The volatile variable also have performance issues.
What is the difference between yield() and sleep()?
Ans) yield() allows the current the thread to release its lock from the object and scheduler
gives the lock of the object to the other thread with same priority.
sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into
sleep state it doesnt release the lock.
What is the difference between wait() and sleep()?
Ans)
1) wait() is a method of Object class. sleep() is a method of Object class.
2) sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into
sleep state it doesnt release the lock. wait() allows thread to release the lock and goes to
suspended state. The thread is only active when a notify() or notifAll() method is called for
the same object.
What is difference between notify() and notfiyAll()?
Ans) notify( ) wakes up the first thread that called wait( ) on the same object.
notifyAll( ) wakes up all the threads that called wait( ) on the same object. The
highest priority thread will run first.
What happens if a start method is not invoked and the run method is directly
invoked?
Ans) If a thread has been instantiated but not started its is said to be in new state. Unless
until a start() method is invoked on the instance of the thread, it will not said to be alive. If
you do not call a start() method on the newly created thread instance thread is not
considered to be alive. If the start() method is not invoked and the run() method is directly
called on the Thread instance, the code inside the run() method will not run in a separate
new thread but it will start running in the existing thread.
What happens when start() is called?
Ans) A new thread of execution with a new call stack starts. The state of thread changes
from new to runnable. When the thread gets chance to execute its target run() method
starts to run.
51

If code running is a thread creates a new thread what will be the initial priority of the
newly created thread?
Ans) When a code running in a thread creates a new thread object , the priority of the new
thread is set equal to the priority of the thread which has created it.
When jvm starts up, which thread will be started up first?
Ans) When jvm starts up the thread executing main method is started.
What are the daemon threads?
Ans) Daemon thread are service provider threads run in the background,these not used to
run the application code generally.When all user threads(non-daemon threads) complete
their execution the jvm exit the application whatever may be the state of the daemon
threads. Jvm does not wait for the daemon threads to complete their execution if all user
threads have completed their execution.
To create Daemon thread set the daemon value of Thread using setDaemon(boolean value)
method. By default all the threads created by user are user thread. To check whether a
thread is a Daemon thread or a user thread use isDaemon() method.
Example of the Daemon thread is the Garbage Collector run by jvm to reclaim the unused
memory by the application. The Garbage collector code runs in a Daemon thread which
terminates as all the user threads are done with their execution.
What all constructors are present in the Thread class?
Ans) Thread()
Thread(Runnable target)
Thread(Runnable target, String name)
Thread(String name)
Can the variables or classes be Synchronized?
Ans) No. Only methods can be synchronized.
How many locks does an object have?
Ans) Each object has only one lock.
Can a class have both Synchronized and non-synchronized methods?
Ans) Yes a class can have both synchronized and non-synchronized methods.
52

If a class has a synchronised method and non-synchronised method, can multiple
threads execute the non-synchronised methods?
Ans) Yes. If a class has a synchronised and non-synchronised methods, multiple threads
can access the non-synchronised methods.
If a thread goes to sleep does it hold the lock?
Ans) Yes when a thread goes to sleep it does not release the lock.
Can a thread hold multiple locks at the same time?
Ans) Yes. A thread can hold multiple locks at the same time. Once a thread acquires a lock
and enters into the synchronized method / block, it may call another synchronized method
and acquire a lock on another object.
Can a thread call multiple synchronized methods on the object of which it hold the
lock?
Ans) Yes. Once a thread acquires a lock in some object, it may call any other synchronized
method of that same object using the lock that it already holds.
Can static methods be synchronized?
Ans) Yes. As static methods are class methods and have only one copy of static data for the
class, only one lock for the entire class is required. Every class in java is represented by
java.lang.Class instance. The lock on this instance is used to synchronize the static methods.
Can two threads call two different static synchronized methods of the same class?
Ans) No. The static synchronized methods of the same class always block each other as only
one lock per class exists. So no two static synchronized methods can execute at the same
time.
Does a static synchronized method block a non-static synchronized method?
Ans)No As the thread executing the static synchronized method holds a lock on the class
and the thread executing the non-satic synchronized method holds the lock on the object
on which the method has been called, these two locks are different and these threads do
not block each other.
Once a thread has been started can it be started again?
Ans) No. Only a thread can be started only once in its lifetime. If you try starting a thread
which has been already started once an IllegalThreadStateException is thrown, which is a
runtime exception. A thread in runnable state or a dead thread can not be restarted.
53

When does deadlock occur and how to avoid it?
Ans) When a locked object tries to access a locked object which is trying to access the first
locked object. When the threads are waiting for each other to release the lock on a
particular object, deadlock occurs .
What is a better way of creating multithreaded application? Extending Thread class
or implementing Runnable?
Ans) If a class is made to extend the thread class to have a multithreaded application then
this subclass of Thread can not extend any other class and the required application will
have to be added to this class as it can not be inherited from any other class. If a class is
made to implement Runnable interface, then the class can extend other class or implement
other interface.
Can the start() method of the Thread class be overridden? If yes should it be
overridden?
Ans) Yes the start() method can be overridden. But it should not be overridden as its
implementation in thread class has the code to create a new executable thread and is
specialised.
What are the methods of the thread class used to schedule the threads?
Ans) The methods are as follows:
public static void sleep(long millis) throws InterruptedException
public static void yield()
public final void join() throws InterruptedException
public final void setPriority(int priority)
public final void wait() throws InterruptedException
public final void notify()
public final void notifyAll()
Which thread related methods are available in Object class?
Ans) The methods are:
public final void wait() throws Interrupted exception
public final void notify()
public final void notifyAll()
Which thread related methods are available in Thread class?
Ans) Methods which are mainly used :
54

public static void sleep(long millis) throws Interrupted exception
public static void yield() public final void join() throws Interrupted exception
public final void setPriority(int priority)
public void start()
public void interrupt()
public final void join()
public void run()
public void resume()
List the methods which when called the thread does not release the locks held?
Ans) Following are the methods.
notify()
join()
sleep()
yield()
List the methods which when called on the object the thread releases the locks held
on that object?
Ans) wait()
Does each thread has its own thread stack?
Ans) Yes each thread has its own call stack. For eg
Thread t1 = new Thread();
Thread t2 = new Thread();
Thread t3 = t1;
In the above example t1 and t3 will have the same stack and t2 will have its own
independent stack.
What is thread starvation?
Ans) In a multi-threaded environment thread starvation occurs if a low priority thread is
not able to run or get a lock on the resoruce because of presence of many high priority
threads. This is mainly possible by setting thread priorities inappropriately.
What is threadLocal variable?
Ans) ThreadLocal is a class. If a variable is declared as threadLocal then each thread will
have a its own copy of variable and would not interfere with the other's thread copy.
Typical scenario to use this would be giving JDBc connection to each thread so that there is
no conflict.
55

ThreadLocal class by JAVA API
public class ThreadLocal {
public Object get();
public void set(Object newValue);
public Object initialValue();
}
Implementation of ThreadLocal
public class ConnectionDispenser {
private static class ThreadLocalConnection extends ThreadLocal {
public Object initialValue() {
return DriverManager.getConnection(ConfigurationSingleton.getDbUrl());
}
}

private static ThreadLocalConnection conn = new ThreadLocalConnection();

public static Connection getConnection() {
return (Connection) conn.get();
}
}
7. Inner Class Questions
What is an inner class?
Ans) Inner class is a class defined inside other class and act like a member of the enclosing
class.
What are the different types of inner classes?
Ans) There are two main types of inner classes
Static member class
Inner class
o Member class
o Anonymous class
o Local class
What is static member class?
Ans) A static member class behaves much like an ordinary top-level class, except that it can
access the static members of the class that contains it. The static nested class can be
accessed as the other static members of the enclosing class without having an instance of
the outer class. The static class can contain non-static and static members and methods.
56

public class InnerClass {
static class StaticInner {
static int i = 9;
int no = 6;
private void method() {}
public void method1() {}
static void method2() {}
final void method3() {}
}
}
The static inner class can be accessed from Outer Class in the following manner:
InnerClass.StaticInner staticObj= new InnerClass. StaticInner ();
No outer class instance is required to instantiate the nested static class because the static
class is a static member of the enclosing class.
What are non static inner classes?
Ans) The different type of static inner classes are: Non - static inner classes classes
associated with the object of the enclosing class. Member class - Classes declared outside a
function (hence a "member") and not declared "static".
The member class can be declared as public, private, protected, final and abstract. E.g.
public class InnerClass {
class MemberClass {
public void method1() { }
}
}
Method local class The inner class declared inside the method is called method local
inner class. Method local inner class can only be declared as final or abstract. Method local
class can only access global variables or method local variables if declared as final
public class InnerClass {
57

int i = 9;
public void method1() {
final int k = 6;
class MethodLocal {
MethodLocal() {
System.out.println(k + i);
}
}
}
}
Anonymous inner class - These are local classes which are automatically declared and
instantiated in the middle of an expression. Also, like local classes, anonymous classes
cannot be public, private, protected, or static. They can specify arguments to the
constructor of the superclass, but cannot otherwise have a constructor. They can
implement only one interface or extend a class.
Anonymous class cannot define any static fields, methods, or classes, except for static final
constants.
Also, like local classes, anonymous classes cannot be public, private, protected, or static
Some examples:
public class MyFrame extends JFrame {
JButton btn = new JButton();
MyFrame() {
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
}
});
}
}
Anonymous class used with comparator
List<Parent> l = new ArrayList<Parent>();
l.add(new Parent(2));
l.add(new Parent(3));
Collections.sort(l, new Comparator() {
public int compare(Object o1, Object o2) {
Parent prt1 = (Parent) o1;
Parent prt2 = (Parent) o2;
if (prt1.getAge() > prt2.getAge()) {
58

return -1;
}else if(prt1.getAge()<prt2.getAge()) {
return 1;
} else {
return 0;
}
}
});
Does a static nested class have access to the enclosing class' non-static methods or
instance variables?
Ans) No .
What are the advantages of Inner classes?
Ans) The embedding of inner class into the outer class in the case when the inner class is to
be used only by one class i.e. the outer class makes the package more streamlined. Nesting
the inner class code where it is used (inside the outer class) makes the code more readable
and maintainable.
The inner class shares a special relationship with the outer class i.e. the inner class has
access to all members of the outer class and still have its own type is the main advantages
of Inner class. Advantage of inner class is that they can be hidden from the other classes in
the same package and still have the access to all the members (private also) of the
enclosing class. So the outer class members which are going to be used by the inner class
can be made private and the inner class members can be hidden from the classes in the
same package. This increases the level of encapsulation.
If a class A is written requires another class B for its own use, there are two ways to do this.
One way is to write a separate class B or to write an inner class B inside class A. Advantage
of writing the inner class B in the class A is you can avoid having a separate class. Inner
classes are best used in the event handling mechanism and to implement the helper classes.
The advantage of using inner class for event handling mechanism is that the use of if/else
to select the component to be handled can be avoided. If inner classes are used each
component gets its own event handler and each event handler implicitly knows the
component it is working for. e.g.

Button btn1 = new Button("Submit");
Btn.addActionListener(new ActionListener(){/br>
Public void actionPerformed(ActionEvent ae){ submitClicked(); }
59

} );
The advantage of using static nested class is that to instantiate a static nested class you
need not create an instance of the enclosing class which reduces the number of objects the
application creates at runtime.
What are disadvantages of using inner classes?
Ans) 1. Using inner class increases the total number of classes being used by the
application. For all the classes created by JVM and loaded in the memory, jvm has to
perform some tasks like creating the object of type class. Jvm may have to perform some
routine tasks for these extra classes created which may result slower performance if the
application is using more number of inner classes. 2. Inner classes get limited support of
ide/tools as compared to the top level classes, so working with the inner classes is
sometimes annoying for the developer.
What are different types of anonymous classes?
Ans 1) Plain old anonymous class type one
e.g.
class superClass{
void doSomething() {
System.out.println(Doing something in the Super class);
}
}

class hasAnonymous{
superClass anon = new superClass(){
void doSomething() {
System.out.println(Doing something in the Anonymous class);
}
};
Here anon is the reference which is of type superClass which is the class extended by the
anonymous class i.e. superclass of the anonymous class. The method doSomething() is the
super class method overridden by the anonymous class.
2) Plain old anonymous class type two

interface Eatable{
public void prepareSweets();
}
class serveMeal{
Eatable food = new Eatable(){
public void prepareSweets(){ //come implementation code goes here }
};
}
food is reference variable of type Eatable interface which refers to the anonymous class
60

which is the implementer of the interface Eatable. The anonymous implementer class of the
interface Eatable implements its method prepareSweets() inside it.
3) Argument defined anonymous class e.g.

interface Vehicle {
void getNoOfWheels();
}
class Car {
void getType(Vehical v) { }
}
class BeautifulCars {
void getTheBeautifilCar() {
Car c = new Car ();
c.getType (new Vehicle () {
public void getNoOfWheels () {
System.out.println("It has four wheels");
}
});
}
}
Anonymous class is defined as the argument of the method getTheBeautifilCar(), this
anonymous class is the implementer of the interface Vehicle. The method of class Car
getTheBeautifilCar() expects the argument as an object of type Vehicle. So first we create
an object of Car referenced by the variable c. On this object of Car we call the method
getTheBeautifilCar() and in the argument we create an anonymous class in place which is
the implementer of interface Vehicle hence of type Vehicle.
If you compile a file containing inner class how many .class files are created and what
are all of them accessible in usual way?
Ans) If a inner class enclosed with an outer class is compiled then one .class file for each
inner class an a .class file for the outer class is created. e.g.
class EnclosingOuter {
class Inner{ }
}
If you compile the above code with command
% javac EnclosingOuter.java
Two files
EnclosingOuter.class
EnclosingOuter$Inner.class
will be created. Though a separate inner class file is generated, the inner class file is not
accessible in the usual way like,
% java EnclosingOuter$Inner
How to access the inner class from code within the outer class?
61

Ans) The inner class is instantiated only through the outer class instance.
class EnclosingOuter {
private int noInnerClass = 1;
public void getNoOfInnerClasses(){
Inner in = new Inner();
System.out.println(No Of Inner classes is : + in.getNoOfClassesFromOuter());
}
class Inner{

public int getNoOfClassesFromOuter(){ return noInnerClass; }

}
Here the method getNoOfInnerClasses() is called on the outer classs instance through this
outer class instance the inner class instance in is created.
How to create an inner class instance from outside the outer class instance code?
Ans) To create an instance of the inner class you must have the instance of its
enclosing class.
e.g. class EnclosingOuter {
class Inner{ }
}
To create the instance of inner class from class other than the enclosing class.
1) class OtherThanOuter{
EnclosingOuter out = new EnclosingOuter();
EnclosingOuter.Inner in = out.new Inner();
}

2) class OtherThanOuter{
EnclosingOuter.Inner out = new EnclosingOuter.Inner (); }
How to refer to the outer this i.e. outer classs current instance from inside the inner
class?
Ans) The outer this reference i.e. the outer class current instance reference can be refered
using OuterClassName.this. E.g
class EnclosingOuter {
class Inner{
System.out.println(Inner class reference is + this); // inner class instance
System.out.println(Outer class reference is + EnclosingOuter.this); //outer class instance
}
}
To refer the inner class reference from within the inner class use this.
Which modifiers can be applied to the inner class?
62

Ans) Following are modifiers that can be applied to the inner:
public
private
abstract
final
protected
strictfp
static turns the inner class into static nested class.
Can the method local inner class object access methods local variables?
Ans) No, a method local inner class object can not access the method local variable.
Reason: The local variables are not guaranteed to live as long as the local inner class
object. The method local variable live on stack and exist only till the method lives, their
scope is limited only code inside the method they are declared in. But the local inner class
object created within the method lives on heap and it may exist even after the method ends
if in case the reference of this local inner class is passed into some other code and is stored
in an instance variable. So we can not be sure that the local variables will live till the
method local inner class object lives, therefore the method local inner class object can not
access the method local variable. To access the method local variables, the variable has to
be declared as final.
Can a method local inner class access the local final variables?Why?
Ans) Yes. Because the final variables are stored on heap and they live as long as the method
local inner class object may live.
Which modifiers can be applied to the method local inner class?
Ans) Only abstract or final keyword isallowed.
Can a local class declared inside a static method have access to the instance members of the
outer class?
Ans) No. There is no this reference available in the static method .The static method class
can not have access to any members of the outer class other than static members.
Can a method which is not in the definition of the superclass of an anonymous class be
invoked on that anonymous class reference?
Ans) No. Compilation will fail.As the reference variable type of the anonymous class will be
of superclass which will not know of any method defined inside the anonymous class the
compilation will fail.
e.g. class SuperClass{
void doSomething() {
System.out.println("In the Super class");
63

}
}
class hasAnonymous{
SuperClass anon = new SuperClass(){
void doSomething() {
System.out.println("In the Anonymous class");
}
void doStuff() {
System.out.println("An Anonymous class method not present in superClass");
}
};

public void doIt(){
anon.doSomething(); // legal superClass has this method
anon.doStuff(); // Not legal }
}
The above code does not compile as the superClass does not know about the anonymous
class method doStuff().
Can an anonymous class define method of its own?
Ans) Yes. But there will be no way by which the methods defined in the anonymous class
which are not present in its superclass be invoked. As only those methods which are
defined in the suprclass which the anonymous class extends be invoked defining the
methods in the anonymous class will be of no use.
Can an anonymous class implement multiple interfaces directly?
Ans) No. An anonymous class can implement only one interface. If the anonymous class is
extending a class then it becomes the implementer of all the interfaces implemented by its
superclass automatically.
Can an anonymous class implement an interface and also extend a class at the same time?
Ans) No. An anonymous class can either extend a class or implement a single interface. If
the anonymous class is extending a class then it becomes the implementer of all the
interfaces implemented by its superclass automatically.
8. Serialization Questions
What is Serialization?
Ans) Serializable is a marker interface. When an object has to be transferred over a
network ( typically through rmi or EJB) or persist the state of an object to a file, the object
64

Class needs to implement Serializable interface. Implementing this interface will allow the
object converted into bytestream and transfer over a network.
What is use of serialVersionUID?
Ans) During object serialization, the default Java serialization mechanism writes the
metadata about the object, which includes the class name, field names and types, and
superclass. This class definition is stored as a part of the serialized object. This stored
metadata enables the deserialization process to reconstitute the objects and map the
stream data into the class attributes with the appropriate type
Everytime an object is serialized the java serialization mechanism automatically computes
a hash value. ObjectStreamClass's computeSerialVersionUID() method passes the class
name, sorted member names, modifiers, and interfaces to the secure hash algorithm (SHA),
which returns a hash value.The serialVersionUID is also called suid.
So when the serilaize object is retrieved , the JVM first evaluates the suid of the serialized
class and compares the suid value with the one of the object. If the suid values match then
the object is said to be compatible with the class and hence it is de-serialized. If not
InvalidClassException exception is thrown.

Changes to a serializable class can be compatible or incompatible. Following is the list of
changes which are compatible:
Add fields
Change a field from static to non-static
Change a field from transient to non-transient
Add classes to the object tree
List of incompatible changes:
Delete fields
Change class hierarchy
Change non-static to static
Change non-transient to transient
Change type of a primitive field
So, if no suid is present , inspite of making compatible changes, jvm generates new suid thus
resulting in an exception if prior release version object is used .
The only way to get rid of the exception is to recompile and deploy the application again.

If we explicitly metion the suid using the statement:

private final static long serialVersionUID = <integer value>

then if any of the metioned compatible changes are made the class need not to be
recompiled. But for incompatible changes there is no other way than to compile again.
What is the need of Serialization?
65

Ans) The serialization is used :-
To send state of one or more objects state over the network through a socket.
To save the state of an object in a file.
An objects state needs to be manipulated as a stream of bytes.
Other than Serialization what are the different approach to make object Serializable?
Ans) Besides the Serializable interface, at least three alternate approaches can serialize
Java objects:

1)For object serialization, instead of implementing the Serializable interface, a developer
can implement the Externalizable interface, which extends Serializable. By implementing
Externalizable, a developer is responsible for implementing the writeExternal() and
readExternal() methods. As a result, a developer has sole control over reading and writing
the serialized objects.
2)XML serialization is an often-used approach for data interchange. This approach lags
runtime performance when compared with Java serialization, both in terms of the size of
the object and the processing time. With a speedier XML parser, the performance gap with
respect to the processing time narrows. Nonetheless, XML serialization provides a more
malleable solution when faced with changes in the serializable object.
3)Finally, consider a "roll-your-own" serialization approach. You can write an object's
content directly via either the ObjectOutputStream or the DataOutputStream. While this
approach is more involved in its initial implementation, it offers the greatest flexibility and
extensibility. In addition, this approach provides a performance advantage over Java
serialization.
Do we need to implement any method of Serializable interface to make an object
serializable?
Ans) No. Serializable is a Marker Interface. It does not have any methods.
What happens if the object to be serialized includes the references to other serializable
objects?
Ans) If the object to be serialized includes the references to other objects whose class
implements serializable then all those objects state also will be saved as the part of the
serialized state of the object in question. The whole object graph of the object to be
serialized will be saved during serialization automatically provided all the objects included
in the objects graph are serializable.
What happens if an object is serializable but it includes a reference to a non-serializable
object?
66

Ans- If you try to serialize an object of a class which implements serializable, but the object
includes a reference to an non-serializable class then a NotSerializableException will be
thrown at runtime.
e.g.
public class NonSerial {
//This is a non-serializable class
}
public class MyClass implements Serializable{
private static final long serialVersionUID = 1L;
private NonSerial nonSerial;
MyClass(NonSerial nonSerial){
this.nonSerial = nonSerial;
}
public static void main(String [] args) {
NonSerial nonSer = new NonSerial();
MyClass c = new MyClass(nonSer);
try {
FileOutputStream fs = new FileOutputStream("test1.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) { e.printStackTrace(); }
try {
FileInputStream fis = new FileInputStream("test1.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (MyClass) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
On execution of above code following exception will be thrown
java.io.NotSerializableException: NonSerial
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java)
Are the static variables saved as the part of serialization?
Ans) No. The static variables belong to the class and not to an object they are not the part of
the state of the object so they are not saved as the part of serialized object.
What is a transient variable?
67

Ans) These variables are not included in the process of serialization and are not the part of
the objects serialized state.
What will be the value of transient variable after de-serialization?
Ans) Its default value.
e.g. if the transient variable in question is an int, its value after deserialization will be zero.
public class TestTransientVal implements Serializable{

private static final long serialVersionUID = -22L;
private String name;
transient private int age;
TestTransientVal(int age, String name) {
this.age = age;
this.name = name;
}

public static void main(String [] args) {
TestTransientVal c = new TestTransientVal(1,"ONE");
System.out.println("Before serialization: - " + c.name + " "+ c.age);
try {
FileOutputStream fs = new FileOutputStream("testTransients.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) { e.printStackTrace(); }


try {
FileInputStream fis = new FileInputStream("testTransients.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (TestTransientVal) ois.readObject();
ois.close();
} catch (Exception e) { e.printStackTrace(); }
System.out.println("After de-serialization:- " + c.name + " "+ c.age);
}
}
Result of executing above piece of code
Before serialization: - Value of non-transient variable ONE Value of transient variable 1
After de-serialization:- Value of non-transient variable ONE Value of transient variable 0
68

Explanation
The transient variable is not saved as the part of the state of the serailized variable, its
value after de-serialization is its default value.
Does the order in which the value of the transient variables and the state of the object using
the defaultWriteObject() method are saved during serialization matter?
Ans) Yes. As while restoring the objects state the transient variables and the serializable
variables that are stored must be restored in the same order in which they were saved.
How can one customize the Serialization process? or What is the purpose of implementing
the writeObject() and readObject() method?
Ans) When you want to store the transient variables state as a part of the serialized object
at the time of serialization the class must implement the following methods
private void wrtiteObject(ObjectOutputStream outStream)
{
//code to save the transient variables state as a part of serialized object
}
private void readObject(ObjectInputStream inStream)
{
//code to read the transient variables state and assign it to the de-serialized object
}
e.g.
public class TestCustomizedSerialization implements Serializable{

private static final long serialVersionUID =-22L;
private String noOfSerVar;
transient private int noOfTranVar;

TestCustomizedSerialization(int noOfTranVar, String noOfSerVar) {
this.noOfTranVar = noOfTranVar;
this.noOfSerVar = noOfSerVar;
}

private void writeObject(ObjectOutputStream os) {

try {
os.defaultWriteObject();
os.writeInt(noOfTranVar);
} catch (Exception e) { e.printStackTrace(); }
69

}

private void readObject(ObjectInputStream is) {
try {
is.defaultReadObject();
int noOfTransients = (is.readInt());
} catch (Exception e) {
e.printStackTrace(); }
}

public int getNoOfTranVar() {
return noOfTranVar;
}

}
The value of transient variable noOfTranVar is saved as part of the serialized object
manually by implementing writeObject() and restored by implementing readObject().
The normal serializable variables are saved and restored by calling defaultWriteObject()
and defaultReadObject()respectively. These methods perform the normal serialization and
de-sirialization process for the object to be saved or restored respectively.
If a class is serializable but its superclass in not , what will be the state of the instance
variables inherited from super class after deserialization?
Ans) The values of the instance variables inherited from superclass will be reset to the
values they were given during the original construction of the object as the non-serializable
super-class constructor will run.
E.g.
public class ParentNonSerializable {
int noOfWheels;

ParentNonSerializable(){
this.noOfWheels = 4;
}

}
public class ChildSerializable extends ParentNonSerializable implements Serializable {

private static final long serialVersionUID = 1L;
String color;
70

ChildSerializable() {
this.noOfWheels = 8;
this.color = "blue";
}
}
public class SubSerialSuperNotSerial {

public static void main(String [] args) {

ChildSerializable c = new ChildSerializable();
System.out.println("Before : - " + c.noOfWheels + " "+ c.color);
try {
FileOutputStream fs = new FileOutputStream("superNotSerail.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) { e.printStackTrace(); }

try {
FileInputStream fis = new FileInputStream("superNotSerail.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (ChildSerializable) ois.readObject();
ois.close();
} catch (Exception e) { e.printStackTrace(); }
System.out.println("After :- " + c.noOfWheels + " "+ c.color);
}
}
Result on executing above code
Before : - 8 blue
After :- 4 blue
The instance variable noOfWheels is inherited from superclass which is not serializable.
Therefore while restoring it the non-serializable superclass constructor runs and its value
is set to 8 and is not same as the value saved during serialization which is 4.
To serialize an array or a collection all the members of it must be serializable. True /False?
Ans) true.
9. Immutable Class Questions
What is an immutable class?
71

Ans) Immutable class is a class which once created, its contents can not be changed.
Immutable objects are the objects whose state can not be changed once constructed. e.g.
String class
How to create an immutable class?
Ans) To create an immutable class following steps should be followed:
1. Create a final class.
2. Set the values of properties using constructor only.
3. Make the properties of the class final and private
4. Do not provide any setters for these properties.
5. If the instance fields include references to mutable objects, don't allow those objects to be
changed:
1. Don't provide methods that modify the mutable objects.
2. Don't share references to the mutable objects. Never store references to external,
mutable objects passed to the constructor; if necessary, create copies, and store
references to the copies. Similarly, create copies of your internal mutable objects
when necessary to avoid returning the originals in your methods.
E.g.
public final class FinalPersonClass {
private final String name;
private final int age;

public FinalPersonClass(final String name, final int age) {
super();
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}

}
Immutable objects are automatically thread-safe true/false?
Ans) True. Since the state of the immutable objects can not be changed once they are
created they are automatically synchronized/thread-safe.
Which classes in java are immutable?
72

Ans) All wrapper classes in java.lang are immutable
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger
What are the advantages of immutability?
Ans) The advantages are:
1) Immutable objects are automatically thread-safe, the overhead caused due to use of
synchronisation is avoided.
2) Once created the state of the immutable object can not be changed so there is no
possibility of them getting into an inconsistent state.
3) The references to the immutable objects can be easily shared or cached without having
to copy or clone them as there state can not be changed ever after construction.
4) The best use of the immutable objects is as the keys of a map.
10. Cloning questions
What are different types of cloning in Java?
Ans) Java supports two type of cloning: - Deep and shallow cloning. By default shallow copy
is used in Java. Object class has a method clone() which does shallow cloning.
What is Shallow copy?
Ans) In shallow copy the object is copied without its contained objects.
Shallow clone only copies the top level structure of the object not the lower levels.
It is an exact bit copy of all the attributes.

Figure 1: Original java object obj
The shallow copy is done for obj and new object obj1 is created but contained objects of obj
are not copied.

Figure 2: Shallow copy object obj1
It can be seen that no new objects are created for obj1 and it is referring to the same old
contained objects. If either of the containedObj contain any other object no new reference
is created
What is deep copy and how it can be acheived?
Ans) In deep copy the object is copied along with the objects it refers to. Deep clone copies
all the levels of the object from top to the bottom recursively.
73


Figure 3 : Original Object obj
When a deep copy of the object is done new references are created.

Figure 4: obj2 is deep copy of obj1
One solution is to simply implement your own custom method (e.g., deepCopy()) that
returns a deep copy of an instance of one of your classes. This may be the best solution if
you need a complex mixture of deep and shallow copies for different fields, but has a few
significant drawbacks:
You must be able to modify the class (i.e., have the source code) or implement a subclass. If
you have a third-party class for which you do not have the source and which is marked final,
you are out of luck.
You must be able to access all of the fields of the classs superclasses. If significant parts
of the objects state are contained in private fields of a superclass, you will not be able to
access them.
You must have a way to make copies of instances of all of the other kinds of objects that the
object references. This is particularly problematic if the exact classes of referenced objects
cannot be known until runtime.
Custom deep copy methods are tedious to implement, easy to get wrong, and difficult to
maintain. The method must be revisited any time a change is made to the class or to any of
its superclasses.
Other common solution to the deep copy problem is to use Java Object Serialization (JOS).
The idea is simple: Write the object to an array using JOSs ObjectOutputStream and
then use ObjectInputStream to reconsistute a copy of the object. The result will be a
completely distinct object, with completely distinct referenced objects. JOS takes care of all
of the details: superclass fields, following object graphs, and handling repeated references
to the same object within the graph.
It will only work when the object being copied, as well as all of the other objects references
directly or indirectly by the object, are serializable. (In other words, they must implement
java.io.Serializable.) Fortunately it is often sufficient to simply declare that a given class
implements java.io.Serializable and let Javas default serialization mechanisms do their
thing. Java Object Serialization is slow, and using it to make a deep copy requires both
serializing and deserializing.
There are ways to speed it up (e.g., by pre-computing serial version ids and defining
custom readObject() and writeObject() methods), but this will usually be the primary
bottleneck. The byte array stream implementations included in the java.io package are
designed to be general enough to perform reasonable well for data of different sizes and to
be safe to use in a multi-threaded environment. These characteristics, however, slow down
ByteArrayOutputStream and (to a lesser extent) ByteArrayInputStream .
74

What is difference between deep and shallow cloning?
Ans) The differences are as follows:
Consider the class:
public class MyData{
String id;
Map myData;
}
The shallow copying of this object will have new id object and values as but will point to
the myData of the original object. So a change in myData by either original or cloned object
will be reflected in other also. But in deep copying there will be new id object and also new
myData object and independent of original object but with same values.
Shallow copying is default cloning in Java which can be achieved using clone() method of
Object class. For deep copying some extra logic need to be provided.
What are the characteristics of a shallow clone?
Ans) If we do a = clone(b)
1) Then b.equals(a)
2) No method of a can modify the value of b.
What are the disadvantages of deep cloning?
Ans) Disadvantages of using Serialization to achieve deep cloning
Serialization is more expensive than using object.clone().
Not all objects are serializable.
Serialization is not simple to implement for deep cloned object..
11. Garbage Collections Questions
Which part of the memory is involved in Garbage Collection? Stack or Heap?
Ans) Heap
What is responsiblity of Garbage Collector?
Ans) Garbage collector frees the memory occupied by the unreachable objects during the
java program by deleting these unreachable objects.
It ensures that the available memory will be used efficiently, but does not guarantee that
there will be sufficient memory for the program to run.
75

Is garbage collector a dameon thread?
Ans) Yes GC is a dameon thread. A dameon thread runs behind the application. It is started
by JVM. The thread stops when all non-dameon threads stop.
Garbage Collector is controlled by whom?
Ans) The JVM controls the Garbage Collector; it decides when to run the Garbage Collector.
JVM runs the Garbage Collector when it realizes that the memory is running low, but this
behavior of jvm can not be guaranteed.
One can request the Garbage Collection to happen from within the java program but there
is no guarantee that this request will be taken care of by jvm.
When does an object become eligible for garbage collection?
Ans) An object becomes eligible for Garbage Collection when no live thread can access it.
What are the different ways to make an object eligible for Garbage Collection when it is no
longer needed?

Ans)
1. Set all available object references to null once the purpose of creating the
object is served :

public class GarbageCollnTest1 {

public static void main (String [] args){
String str = "Set the object ref to null";
//String object referenced by variable str is not eligible for GC yet

str = null;
/*String object referenced by variable str becomes eligible for GC */
}

}
2. Make the reference variable to refer to another object : Decouple the
reference variable from the object and set it refer to another object, so the object
which it was referring to before reassigning is eligible for Garbage Collection.
76


publc class GarbageCollnTest2 {

public static void main(String [] args){
String str1 = "Garbage collected after use";
String str2 = "Another String";
System.out.println(str1);
//String object referred by str1 is not eligible for GC yet

str1 = str2;
/* Now the str1 variable referes to the String object "Another String" and the object
"Garbage collected after use" is not referred by any variable and hence is eligible for GC */

}

}
3) Creating Islands of Isolation : If you have two instance reference variables
which are referring to the instances of the same class, and these two reference
variables refer to each other and the objects referred by these reference variables
do not have any other valid reference then these two objects are said to form an
Island of Isolation and are eligible for Garbage Collection.


public class GCTest3 {
GCTest3 g;

public static void main(String [] str){
GCTest3 gc1 = new GCTest3();
GCTest3 gc2 = new GCTest3();
gc1.g = gc2; //gc1 refers to gc2
gc2.g = gc1; //gc2 refers to gc1
gc1 = null;
gc2 = null;
//gc1 and gc2 refer to each other and have no other valid //references
//gc1 and gc2 form Island of Isolation
//gc1 and gc2 are eligible for Garbage collection here
}

}
77

Can the Garbage Collection be forced by any means?
Ans) No. The Garbage Collection can not be forced, though there are few ways by which it
can be requested there is no guarantee that these requests will be taken care of by JVM.
How can the Garbage Collection be requested?
Ans) There are two ways in which we can request the jvm to execute the Garbage
Collection.
1) The methods to perform the garbage collections are present in the Runtime class
provided by java. The Runtime class is a Singleton for each java main program.
The method getRuntime() returns a singleton instance of the Runtime class. The method
gc() can be invoked using this instance of Runtime to request the garbage collection.
2) Call the System class System.gc() method which will request the jvm to perform GC.
What is the purpose of overriding finalize() method?
Ans) The finalize() method should be overridden for an object to include the clean up code
or to dispose of the system resources that should to be done before the object is garbage
collected.
If an object becomes eligible for Garbage Collection and its finalize() method has been
called and inside this method the object becomes accessible by a live thread of execution
and is not garbage collected. Later at some point the same object becomes eligible for
Garbage collection, will the finalize() method be called again?
Ans) No
How many times does the garbage collector calls the finalize() method for an object?
Ans) Only once.
What happens if an uncaught exception is thrown from during the execution of the
finalize() method of an object?
Ans) The exception will be ignored and the garbage collection (finalization) of that object
terminates.
What are different ways to call garbage collector?
Ans) Garbage collection can be invoked using System.gc() or Runtime.getRuntime().gc().
How to enable/disable call of finalize() method of exit of the application
Ans) Runtime.getRuntime().runFinalizersOnExit(boolean value) . Passing the boolean
value will either disable or enable the finalize() call.
78

12. JSP questions
What is a JSP? What is it used for? What do you understand by the term JSP translation
phase or compilation phase?
Ans) JSP (Java ServerPages) is an extension of the Java Servlet technology. JSP is commonly used
as the presentation layer for combining HTML and Java code. While Java Servlet technology is
capable of generating HTML with out.println(.. ?) statements, where out is a PrintWriter.
This process of embedding HTML code with escape characters is cumbersome and hard to
maintain. The JSP technology solves this by providing a level of abstraction so that the developer
can use custom tags and action elements, which can speed up Web development and are easier to
maintain.

The JSPs have a translation or a compilation process where the JSP engine translates and compiles a
JSP file into a JSP Servlet. The translated and compiled JSP Servlet moves to the execution phase
(run time) where they can handle requests and send response.

Unless explicitly compiled ahead of time, JSP files are compiled the first time they are accessed. On
large production sites, or in situations involving complicated JSP files, compilation may cause
unacceptable delays to users first accessing the JSP page. The JSPs can be compiled ahead of time (ie
precompiled) using application server tools/settings or by writing your own script.
Explain the life cycle methods of a JSP?
Ans) Pre-translated: Before the JSP file has been translated and compiled into the Servlet.
Translated: The JSP file has been translated and compiled as a Servlet.
Initialized: Prior to handling the requests in the service method the container calls the jspInit() to
initialize the Servlet. Called only once per Servlet instance.
Servicing: Services the client requests. Container calls this method for each request.
Out of service: The Servlet instance is out of service. The container calls the jspDestroy() method.
What are different type of scripting elements?
Ans)
Declaration Element: is the embedded Java declaration statement, which gets inserted at the
Servlet class level.
<%! Calendar c = Calendar.getInstance(); %>
Important: declaring variables via this element is not thread-safe, because this variable ends up in
the generated Servlet as an instance variable, not within the body of the _jspservice() method.
Ensure their access is either read-only or synchronized.

Expression Element: is the embedded Java expression, which gets evaluated by the service
method.
<%= new Date()>

Scriptlet Elements: are the embedded Java statements, which get executed as part of the service
method.
(Note: Not recommended to use Scriptlet elements because they dont provide reusability and
79

maintainability. Use custom tags (like JSTL, JSF tags, etc) or beans instead).
<%
//Java codes
String userName=null;
userName=request.getParameter("userName");
%>

Action Elements: A JSP element that provides information for execution phase.
<jsp:useBean id="object_name" class="class_name"/>
<jsp:include page="scripts/login.jsp" />

Directive Elements: A JSP element that provides global information for the translation phase.
<%@ page import=?java.util.Date? %>
<%@ include file=?myJSP? %>
<%@ taglib uri=?tagliburi? prefix=?myTag?%>
What are the different scope values or what are the different scope values for
"jsp:usebean"?
Ans)
Scope Object Comment
Page PageContext Available to the handling JSP
page only.
Request Request Available to the handling JSP
page or Servlet and forwarded
JSP page or Servlet.
Session Session Available to any JSP Page or
Servlet within the same
session.
Application Application Available to all the JSP pages
and Servlets within the same
Web Application.
What are the differences between static and a dynamic include?
Ans)
Static <%@include%> Dynamic include
<include....>
During the translation or
compilation phase all the
included JSP pages are
compiled into a single Servlet.
The dynamically included JSP
is compiled into a separate
Servlet. It is a separate
resource, which gets to
process the request, and the
content generated by this
resource is included in the JSP
response.
No run time performance Has run time performance
80

overhead. overhead.
Is JSP variable declaration thread safe?
Ans) No. The declaration of variables in JSP is not thread-safe, because the declared variables end
up in the generated Servlet as an instance variable, not within the body of the _jspservice() method.
The following declaration is not thread safe: because these are declarations, and will only be
evaluated once when the page is loaded
<%! int a = 5 %>
The following declaration is thread safe: because the variables declared inside the scriplets have the
local scope and not shared.
<% int a = 5 %>;
Explain JSP URL mapping? What is URL hiding or protecting the JSP page?
Ans) The JSP resources usually reside directly or under subdirectories (e.g. myPath) of the
document root, which are directly accessible to the user through the URL. If you want to protect
your Web resources then hiding the JSP files behind the WEB-INF directory can protect the JSP files,
css (cascading style sheets) files, Java Script files, pdf files, image files, html files etc from direct
access. The request should be made to a servlet who is responsible for authenticating and
authorising the user before returning the protected JSP page or its resources.
What are custom tags? Explain how to build custom tags?
Ans) Custom JSP tag is a tag you define. You define how a tag, its attributes and its body are
interpreted, and then group your tags into collections called tag libraries that can be used in any
number of JSP files. So basically it is a reusable and extensible JSP only solution. The pre-built tags
also can speed up Web development.
Step 1
Create a Custom tag class using only doStartTag()
package myTagPkg;
public class MyTag extends TagSupport
{
int attr = null;
public int setAttr(int a ttr){this.attr = a ttr}
public int getAttr(){return attr;}
public int doStartTag() throws JspException {
.......
return 0;
}
public void release(){.....}
}
Step 2 The Tag library descriptor file (*.tld) maps the XML element names to the tag
implementations. The code sample MyTagDesc.tld is shown below:
81

<taglib>
<tag>
<name>tag1</name>
<tagclass>myTagPkg.MyTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>attr</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
</taglib>
Step 3
The web.xml deployment descriptor maps the URI to the location of the *.tld (Tag Library
Descriptor) file. The code sample web.xml file is shown below:
<web-app>
<taglib>
<taglib-uri>/WEB-INF/MyTagURI</taglib-uri>
<taglib-location>/WEB-INF/tags/MyTagDesc.tld</taglib-location>
</taglib>
</web-app>

STEP: 4
The JSP file declares and then uses the tag library as shown below:
<%@ taglib uri="/WEB-INF/ MyTagURI" prefix="myTag" %>
< myTag:tag1 attr=?abc? />
<taglib>
<tag>
<name>tag1</name>
<tagclass>myTagPkg.MyTag</tagclass>
<bodycontent>empty</bodycontent>
<attribute>
<name>attr</name>
<required>false</required>
<rtexprvalue>false</rtexprvalue>
</attribute>
</tag>
82

</taglib>
What is the difference between custom JSP tags and JavaBeans?
Ans) In the context of a JSP page, both accomplish similar goals but the differences are:
Custom Tags JavaBeans
Can manipulate JSP content. Can't manipulate JSP content.
Custom tags can simplify the complex
operations much better than the bean can.
But require a bit more work to set up.
Easier to set up.
Used only in JSPs in a relatively self-
contained manner.
Can be used in both Servlets and JSPs. You
can define a bean in one Servlet and use them
in another Servlet or a JSP page.
JavaBeans declaration and usage example:
<jsp:useBean id="identifier" class="packageName.className"/>
<jsp:setProperty name="identifier" property="classField" value="someValue" />
<jsp:getProperty name="identifier" property="classField" />
<%=identifier.getclassField() %>
What is a Expression?
A: An expression tag contains a scripting language expression that is evaluated, converted
to a String, and inserted where the expression appears in the JSP file. Because the value of
an expression is converted to a String, you can use an expression within text in a JSP file.
Like
<%= someexpression %>
<%= (new java.util.Date()).toLocaleString() %>
You cannot use a semicolon to end an expression.
Difference between forward and sendRedirect?
Ans) When you invoke a forward request, the request is sent to another resource on the
server, without the client being informed that a different resource is going to process the
request. This process occurs completly with in the web container. When a sendRedirtect
method is invoked, it causes the web container to return to the browser indicating that a
new URL should be requested. Because the browser issues a completly new request any
object that are stored as request attributes before the redirect occurs will be lost. This
extra round trip a redirect is slower than forward.
What are implicit objects? List them?
83

Ans) Certain objects that are available for the use in JSP documents without being declared
first. These objects are parsed by the JSP engine and inserted into the generated servlet.
The implicit objects are listed below:
request
response
pageContext
session
application
out
config
page
exception
How do I prevent the output of my JSP or Servlet pages from being cached by the
browser?
Ans) You will need to set the appropriate HTTP header attributes to prevent the dynamic
content output by the JSP page from being cached by the browser. Just execute the
following scriptlet at the beginning of your JSP pages to prevent them from being cached at
the browser. You need both the statements to take care of some of the older browser
versions.

<% response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>
How to implement a thread-safe JSP page? What are the advantages and
Disadvantages of using it?
Ans) JSPs can be thread-safe by having them implement the SingleThreadModel interface.
This is done by adding the directive
<%@ page isThreadSafe="false" %>
within your JSP page. With this, instead of a single instance of the servlet generated for
your JSP page loaded in memory, you will have N instances of the servlet loaded and
initialized, with the service method of each instance effectively synchronized. You can
typically control the number of instances (N) that are instantiated for all servlets
implementing SingleThreadModel through the admin screen for your JSP engine. More
importantly, avoid using the tag for variables. If you do use this tag, then you should set
isThreadSafe to true, as mentioned above. Otherwise, all requests to that page will access
those variables, causing a nasty race condition. SingleThreadModel is not recommended for
normal use. There are many pitfalls, including the example above of not being able to use
84

<%! %>. You should try really hard to make them thread-safe the old fashioned way: by
making them thread-safe .
Why to use the HttpServlet Init method to perform expensive operations that need
only be done once?
Ans) Because the servlet init() method is invoked when servlet instance is loaded, it is the
perfect location to carry out expensive operations that need only be performed during
initialization. By definition, the init() method is thread-safe. The results of operations in the
HttpServlet.init() method can be cached safely in servlet instance variables, which become
read-only in the servlet service method.
Why is it not a good practice to create HttpSessions in JSPs by default?
Ans) By default, JSP files create HttpSessions. This is in compliance with J2EETM to
facilitate the use of JSP implicit objects, which can be referenced in JSP source and tags
without explicit declaration. HttpSession is one of those objects. If you do not use
HttpSession in your JSP files then you can save some performance overhead with the
following JSP page directive:
<%@ page session="false"%>
What are the standard actions available in JSP?
Ans) The standard actions available in JSP are as follows:
<jsp:include>: It includes a response from a servlet or a JSP page into the current page. It
differs from an include directive in that it includes a resource at request processing time,
whereas the include directive includes a resource at translation time.
<jsp:forward>: It forwards a response from a servlet or a JSP page to another page.
<jsp:useBean>: It makes a JavaBean available to a page and instantiates the bean.
<jsp:setProperty>: It sets the properties for a JavaBean.
<jsp:getProperty>: It gets the value of a property from a JavaBean component and adds it to
the response.
<jsp:param>: It is used in conjunction with <jsp:forward>;, <jsp:, or plugin>; to add a
parameter to a request. These parameters are provided using the name-value pairs.
<jsp:plugin>: It is used to include a Java applet or a JavaBean in the current JSP page.
13. JDBC questions and answers
What are the steps involved in establishing a JDBC connection?
This action involves two steps: loading the JDBC driver and making the connection.
How can you load the drivers?
Loading the driver or drivers you want to use is very simple and involves just one
85

line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following
code will load it:
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
Your driver documentation will give you the class name to use. For instance, if the class
name is jdbc.DriverXYZ, you would load the driver with the following line of code:
Class.forName(jdbc.DriverXYZ);
What will Class.forName do while loading drivers?
It is used to create an instance of a driver and register it with the DriverManager.
When you have loaded a driver, it is available for making a connection with a DBMS.
How can you make the connection?
To establish a connection you need to have the appropriate driver connect to the
DBMS.The following line of code illustrates the general idea:
String url= jdbc:odbc:Fred;
Connection con = DriverManager.getConnection(url, Fernanda, J8?);
How can you create JDBC statements and what are they?
A Statement object is what sends your SQL statement to the DBMS. You simply
create a Statement object and then execute it, supplying the appropriate execute method
with the SQL statement you want to send. For a SELECT statement, the method to use is
executeQuery. For statements that create or modify tables, the method to use is
executeUpdate. It takes an instance of an active connection to create a Statement object. In
the following example, we use our Connection object con to create the Statement object
Statement stmt = con.createStatement();
How can you retrieve data from the ResultSet?
JDBC returns results in a ResultSet object, so we need to declare an instance of the
class ResultSet to hold our results. The following code demonstrates declaring the
ResultSet object rs.
ResultSet rs = stmt.executeQuery(SELECT COF_NAME, PRICE FROM COFFEES);
String s = rs.getString(COF_NAME);
86

The method getString is invoked on the ResultSet object rs, so getString() will
retrieve (get) the value stored in the column COF_NAME in the current row of rs.
What are the different types of Statements?
Regular statement (use createStatement method)
Prepared statement (use prepareStatement method)
Callable statement (use prepareCall)
How can you use PreparedStatement?
This special type of statement is derived from class Statement. If you need a
Statement object to execute many times, it will normally make sense to use a
PreparedStatement object instead. The advantage to this is that in most cases, this SQL
statement will be sent to the DBMS right away, where it will be compiled. As a result, the
PreparedStatement object contains not just an SQL statement, but an SQL statement that
has been precompiled. This means that when the PreparedStatement is executed, the DBMS
can just run the PreparedStatements SQL statement without having to compile it first.
PreparedStatement updateSales =con.prepareStatement("UPDATE COFFEES SET SALES = ?
WHERE COF_NAME LIKE ?");
What does setAutoCommit do?
When a connection is created, it is in auto-commit mode. This means that each
individual SQL statement is treated as a transaction and will be automatically committed
right after it is executed. The way to allow two or more statements to be grouped into a
transaction is to disable auto-commit mode:
con.setAutoCommit(false);
Once auto-commit mode is disabled, no SQL statements will be committed until you call the
method commit explicitly.
con.setAutoCommit(false);
PreparedStatement updateSales =
con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50); updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
87

PreparedStatement updateTotal =
con.prepareStatement("UPDATE COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);
How do you call a stored procedure from JDBC?
The first step is to create a CallableStatement object. As with Statement an and
PreparedStatement objects, this is done with an open Connection object. A
CallableStatement object contains a call to a stored procedure.
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
ResultSet rs = cs.executeQuery();
How do I retrieve warnings?
SQLWarning objects are a subclass of SQLException that deal with database access
warnings. Warnings do not stop the execution of an application, as exceptions do; they
simply alert the user that something did not happen as planned. A warning can be reported
on a Connection object, a Statement object (including PreparedStatement and
CallableStatement objects), or a ResultSet object. Each of these classes has a getWarnings
method, which you must invoke in order to see the first warning reported on the calling
object:
SQLWarning warning = stmt.getWarnings();
if (warning != null)
{
System.out.println("n---Warning---n");
while (warning != null)
{
88

System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.print("Vendor error code: ");
System.out.println(warning.getErrorCode());
System.out.println("");
warning = warning.getNextWarning();
}
}
How can you move the cursor in scrollable result sets?
One of the new features in the JDBC 2.0 API is the ability to move a result sets
cursor backward as well as forward. There are also methods that let you move the cursor
to a particular row and check the position of the cursor.
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery(SELECT COF_NAME, PRICE FROM COFFEES);
The first argument is one of three constants added to the ResultSet API to indicate
the type of a ResultSet object: TYPE_FORWARD_ONLY, TYPE_SCROLL_INSENSITIVE , and
TYPE_SCROLL_SENSITIVE. The second argument is one of two ResultSet constants for
specifying whether a result set is read-only or updatable: CONCUR_READ_ONLY and
CONCUR_UPDATABLE. The point to remember here is that if you specify a type, you must
also specify whether it is read-only or updatable. Also, you must specify the type first, and
because both parameters are of type int , the compiler will not complain if you switch the
order. Specifying the constant TYPE_FORWARD_ONLY creates a nonscrollable result set,
that is, one in which the cursor moves only forward. If you do not specify any constants for
the type and updatability of a ResultSet object, you will automatically get one that is
TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.
Whats the difference between TYPE_SCROLL_INSENSITIVE,and
TYPE_SCROLL_SENSITIVE?
89

You will get a scrollable ResultSet object if you specify one of these ResultSet
constants.The difference between the two has to do with whether a result set reflects
changes that are made to it while it is open and whether certain methods can be called to
detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE
does not reflect changes made while it is still open and one that is
TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if
they are closed and then reopened:
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet srs =stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
srs.afterLast();
while (srs.previous())
{
String name = srs.getString("COF_NAME");
float price = srs.getFloat("PRICE");
System.out.println(name + " " + price);
}
How to Make Updates to Updatable Result Sets?
Another new feature in the JDBC 2.0 API is the ability to update rows in a result set
using methods in the Java programming language rather than having to send an SQL
command. But before you can take advantage of this capability, you need to create a
ResultSet object that is updatable. In order to do this, you supply the ResultSet constant
CONCUR_UPDATABLE to the createStatement method.
Connection con =DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
90

14. Reading XML in JAVA
<?xml version="1.0"?>
<company>
<staff>
<firstname>yong</firstname>
<lastname>mook kim</lastname>
<nickname>mkyong</nickname>
<salary>100000</salary>
</staff>
<staff>
<firstname>low</firstname>
<lastname>yin fong</lastname>
<nickname>fong fong</nickname>
<salary>200000</salary>
</staff>
</company>
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;

public class ReadXMLFile {

public static void main(String argv[]) {

try {

File fXmlFile = new File("c:\\file.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();

System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("staff");
System.out.println("-----------------------");

for (int temp = 0; temp < nList.getLength(); temp++) {

Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {

Element eElement = (Element) nNode;

System.out.println("First Name : " + getTagValue("firstname", eElement));
System.out.println("Last Name : " + getTagValue("lastname", eElement));
System.out.println("Nick Name : " + getTagValue("nickname", eElement));
System.out.println("Salary : " + getTagValue("salary", eElement));

}
}
91

} catch (Exception e) {
e.printStackTrace();
}
}

private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0).getChildNodes();

Node nValue = (Node) nlList.item(0);

return nValue.getNodeValue();
}

}
15. Reading properties file in JAVA
import java.io.*;
import java.util.*;
public class ReadProperty{
String str, key;
public static void main(String[] args) {
ReadProperty r = new ReadProperty();
}
public ReadProperty(){
try{
int check = 0;
while(check == 0){
check = 1;
BufferedReader bf = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter file name which has properties extension :");
str = bf.readLine();
File f = new File(str + ".properties");
if(f.exists()){
Properties pro = new Properties();
FileInputStream in = new FileInputStream(f);
pro.load(in);
System.out.println("All key are given: " + pro.keySet());
System.out.print("Enter Key : ");
key = bf.readLine();
String p = pro.getProperty(key);
System.out.println(key + " : " + p);
}
else{
check = 0;
System.out.println("File not found!");
}
}
}
catch(IOException e){
System.out.println(e.getMessage());
}
}
92

}
16. DataSource in JAVA
import java.sql.Connection;
import org.apache.commons.dbcp.BasicDataSource;
public class BasicDataSourceExample {
public static void main(String args[]) throws Exception {
BasicDataSource bds = new BasicDataSource();
bds.setDriverClassName("com.mysql.jdbc.Driver");
bds.setUrl("jdbc:mysql://localhost/commons");
bds.setUsername("root");
bds.setPassword("");
// bds.setInitialSize(5);
Connection connection = bds.getConnection();
System.err.println(connection);
connection.close();
}
}
17. StringTokenizer in JAVA
A StringTokenizer is utility class used to break up string.

e.g.

StringTokenizer st = new StringTokenizer("Hello World");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}

Output:

Hello

World
18. Collection in details
The Collection interface (java.util.Collection) is one of the root interfaces of the Java collection classes.
Though you do not instantiate a Collection directly, but rather a subtype of Collection, you may often
treat these subtypes uniformly as a Collection. In this text you will see how.
Here is a list of the topics covered in this text:
1. Collection Subtypes
2. Adding and Removing Elements
93

3. Checking if a Collection Contains a Certain Element
4. Collection Size
5. Iterating a Collection

19. Collection Subtypes
The following interfaces (collection types) extends the Collection interface:
List
Set
SortedSet
NavigableSet
Queue
Deque
Java does not come with a usable implementation of the Collection interface, so you will have to use
one of the listed subtypes. The Collection interface just defines a set of methods (behaviour) that each
of these Collection subtypes share. This makes it possible ignore what specific type of Collection you are
using, and just treat it as a Collection. This is standard inheritance, so there is nothing magical about, but
it can still be a nice feature from time to time. Later sections in this text will describe the most used of
these common operations.
Here is a method that operates on a Collection:
94

public class MyCollectionUtil{
public static void doSomething(Collection collection) {

Iterator iterator = collection.iterator();
while(iterator.hasNext()){
Object object = iterator.next();
//do something to object here...
}
}
}
And here are a few ways to call this method with different Collection subtypes:
Set set = new HashSet();
List list = new ArrayList();
MyCollectionUtil.doSomething(set);
MyCollectionUtil.doSomething(list);
20. Adding and Removing Elements
Regardless of what Collection subtype you are using there are a few standard methods to add and
remove elements from a Collection. Adding and removing single elements is done like this:
String anElement = "an element";
Collection collection = new HashSet();
boolean didCollectionChange = collection.add(anElement);
boolean wasElementRemoved = collection.remove(anElement);
add() adds the given element to the collection, and returns true if the Collection changed as a result of
calling the add() method. A Set for instance may not have changed. If the Set already contained that
element, it is not added again. On the other hand, if you called add() on a List and the List already
contained that element, the element would then exist twice in the List.
95

remove() removes the given element and returns true if the removed element was present in the
Collection, and was removed. If the element was not present, the remove() method returns false.
You can also add and remove collections of objects. Here are a few examples:
Set aSet = ... // get Set with elements from somewhere
List aList = ... // get List with elements from somewhere
Collection collection = new HashSet();
collection.addAll(aSet); //returns boolean too, but ignored here.
collection.addAll(aList); //returns boolean too, but ignored here.
collection.removeAll(aList); //returns boolean too...
collection.retainAll(aSet); //returns boolean too...
addAll() adds all elements found in the Collection passed as parameter to the method. The Collection
object itself is not added. Only its elements. If you had called add() with the Collection as parameter
instead, the Collection object itself would have been added, not its elements.
Exactly how thet addAll() method behaves depends on the Collection subtype. Some Collection subtypes
allows the same element to be added more than once, and others don't.
removeAll() removes all elements found the Collection passed as parameter to the method. If the
Collection parameter contains any elements not found the target collection, these are just ignored.
retainAll() does the opposite of removeAll(). Instead of removing all the elements found in the
parameter Collection, it keeps all these elements, and removes all other elements. Keep in mind, that
only if the elements were already contained in the target collection, are they retained. Any new
elements found in the parameter Collection which are not in the target collection, are not automatically
added. They are just ignored.
Let's see an example using some pseudo-language:
Collection colA = [A,B,C]
Collection colB = [1,2,3]
Collection target = [];
target.addAll(colA); //target now contains [A,B,C]
target.addAll(colB); //target now contains [A,B,C,1,2,3]
target.retainAll(colB); //target now contains [1,2,3]
96

target.removeAll(colA); //nothing happens - already removed
target.removeAll(colB); //target is now empty.
21. Checking if a Collection Contains a Certain Element
The Collection interface has two methods to check if a Collection contains one or more certain
elements. These are the contains() and containsAll() methods. They are illustrated here:
Collection collection = new HashSet();
boolean containsElement = collection.contains("an element");
Collection elements = new HashSet();
boolean containsAll = collection.containsAll(elements);
contains() returns true if the collection contains the element, and false if not.
containsAll() returns true if the collection contains all the elements in the parameter collection, and false
if not.
22. Collection Size
You can check the size of a collection using the size() method. By "size" is meant the number of
elements in the collection. Here is an example:
int numberOfElements = collection.size();
23. Iterating a Collection
You can iterate all elements of a collection. This is done by obtaining an Iterator from the collection, and
iterate through that. Here is how it looks:
Collection collection = new HashSet();
//... add elements to the collection
Iterator iterator = collection.iterator();
while(iterator.hasNext()){
Object object = iterator.next();
//do something to object;
}
97

You can also use the new for-loop:
Collection collection = new HashSet();
//... add elements to the collection
for(Object object : collection) {
//do something to object;
}
24. List Implementations
Being a Collection subtype all methods in the Collection interface are also available in the List interface.
Since List is an interface you need to instantiate a concrete implementation of the interface in order to
use it. You can choose between the following List implementations in the Java Collections API:
java.util.ArrayList
java.util.LinkedList
java.util.Vector
java.util.Stack
There are also List implementations in the java.util.concurrent package, but I will leave the concurrency
utilities out of this tutorial.
Here are a few examples of how to create a List instance:
List listA = new ArrayList();
List listB = new LinkedList();
List listC = new Vector();
List listD = new Stack();
25. Adding and Accessing Elements
To add elements to a List you call its add() method. This method is inherited from the Collection
interface. Here are a few examples:
List listA = new ArrayList();
listA.add("element 1");
98

listA.add("element 2");
listA.add("element 3");
listA.add(0, "element 0");
The first three add() calls add a String instance to the end of the list. The last add() call adds a String at
index 0, meaning at the beginning of the list.
The order in which the elements are added to the List is stored, so you can access the elements in the
same order. You can do so using either the get(int index) method, or via the Iterator returned by the
iterator() method. Here is how:
List listA = new ArrayList();
listA.add("element 0");
listA.add("element 1");
listA.add("element 2");
//access via index
String element0 = listA.get(0);
String element1 = listA.get(1);
String element3 = listA.get(2);
//access via Iterator
Iterator iterator = listA.iterator();
while(iterator.hasNext(){
String element = (String) iterator.next();
}
//access via new for-loop
for(Object object : listA) {
String element = (String) object;
}
When iterating the list via its Iterator or via the for-loop (which also uses the Iterator behind the scene),
the elements are iterated in the same sequence they are stored in the list.
99

26. Removing Elements
You can remove elements in two ways:
1. remove(Object element)
2. remove(int index)
remove(Object element) removes that element in the list, if it is present. All subsequent elements in the
list are then moved up in the list. Their index thus decreases by 1.
remove(int index) removes the element at the given index. All subsequent elements in the list are then
moved up in the list. Their index thus decreases by 1.
27. Generic Lists
By default you can put any Object into a List, but from Java 5, Java Generics makes it possible to limit the
types of object you can insert into a List. Here is an example:
List<MyObject> list = new ArrayList<MyObject>();
This List can now only have MyObject instances inserted into it. You can then access and iterate its
elements without casting them. Here is how it looks:
MyObject myObject = list.get(0);
for(MyObject anObject : list){
//do someting to anObject...
}
28. Set Implementations
Being a Collection subtype all methods in the Collection interface are also available in the Set interface.
Since Set is an interface you need to instantiate a concrete implementation of the interface in order to
use it. You can choose between the following Set implementations in the Java Collections API:
java.util.EnumSet
java.util.HashSet
java.util.LinkedHashSet
java.util.TreeSet
100

Each of these Set implementations behaves a little differently with respect to the order of the elements
when iterating the Set, and the time (big O notation) it takes to insert and access elements in the sets.
HashSet is backed by a HashMap. It makes no guarantees about the sequence of the elements when you
iterate them.
LinkedHashSet differs from HashSet by guaranteeing that the order of the elements during iteration is
the same as the order they were inserted into the LinkedHashSet. Reinserting an element that is already
in the LinkedHashSet does not change this order.
TreeSet also guarantees the order of the elements when iterated, but the order is the sorting order of
the elements. In other words, the order in which the elements whould be sorted if you used a
Collections.sort() on a List or array containing these elements. This order is determined either by their
natural order (if they implement Comparable), or by a specific Comparator implementation.
There are also Set implementations in the java.util.concurrent package, but I will leave the concurrency
utilities out of this tutorial.
Here are a few examples of how to create a Set instance:
Set setA = new EnumSet();
Set setB = new HashSet();
Set setC = new LinkedHashSet();
Set setD = new TreeSet();
29. Adding and Accessing Elements
To add elements to a Set you call its add() method. This method is inherited from the Collection
interface. Here are a few examples:
Set setA = new HashSet();
setA.add("element 1");
setA.add("element 2");
setA.add("element 3");
The three add() calls add a String instance to the set.
When iterating the elements in the Set the order of the elements depends on what Set implementation
you use, as mentioned earlier. Here is an iteration example:
Set set A = new HashSet();
101

setA.add("element 0");
setA.add("element 1");
setA.add("element 2");
//access via Iterator
Iterator iterator = setA.iterator();
while(iterator.hasNext(){
String element = (String) iterator.next();
}
//access via new for-loop
for(Object object : setA) {
String element = (String) object;
}
30. Removing Elements
You remove elements by calling the remove(Object o) method. There is no way to remove an object
based on index in a Set, since the order of the elements depends on the Set implementation.
31. Generic Sets
By default you can put any Object into a Set, but from Java 5, Java Generics makes it possible to limit the
types of object you can insert into a Set. Here is an example:
Set<MyObject> set = new HashSet<MyObject>();
This Set can now only have MyObject instances inserted into it. You can then access and iterate its
elements without casting them. Here is how it looks:
for(MyObject anObject : set){
//do someting to anObject...
}
102

32. Map Implementations
Since Map is an interface you need to instantiate a concrete implementation of the interface in order to
use it. You can choose between the following Map implementations in the Java Collections API:
java.util.HashMap
java.util.Hashtable
java.util.EnumMap
java.util.IdentityHashMap
java.util.LinkedHashMap
java.util.Properties
java.util.TreeMap
java.util.WeakHashMap
In my experience, the most commonly used Map implementations are HashMap and TreeMap.
Each of these Set implementations behaves a little differently with respect to the order of the elements
when iterating the Set, and the time (big O notation) it takes to insert and access elements in the sets.
HashMap maps a key and a value. It does not guarantee any order of the elements stored internally in
the map.
TreeMap also maps a key and a value. Furthermore it guarantees the order in which keys or values are
iterated - which is the sort order of the keys or values. Check out the JavaDoc for more details.
Here are a few examples of how to create a Map instance:
Map mapA = new HashMap();
Map mapB = new TreeMap();
33. Adding and Accessing Elements
To add elements to a Map you call its put() method. Here are a few examples:
Map mapA = new HashMap();
mapA.put("key1", "element 1");
mapA.put("key2", "element 2");
mapA.put("key3", "element 3");
103

The three put() calls maps a string value to a string key. You can then obtain the value using the key. To
do that you use the get() method like this:
String element1 = (String) mapA.get("key1");
You can iterate either the keys or the values of a Map. Here is how you do that:
// key iterator
Iterator iterator = mapA.keySet().iterator();
// value iterator
Iterator iterator = mapA.values();
Most often you iterate the keys of the Map and then get the corresponding values during the iteration.
Here is how it looks:
Iterator iterator = mapA.keySet().iterator();
while(iterator.hasNext(){
Object key = iterator.next();
Object value = mapA.get(key);
}
//access via new for-loop
for(Object key : mapA.keySet()) {
Object value = mapA.get(key);
}
34. Removing Elements
You remove elements by calling the remove(Object key) method. You thus remove the (key, value) pair
matching the key.
35. Generic Maps
By default you can put any Object into a Map, but from Java 5, Java Generics makes it possible to limit
the types of object you can use for both keys and values in a Map. Here is an example:
Map<String, MyObject> map = new HashSet<String, MyObject>();
104

This Map can now only accept String objects for keys, and MyObject instances for values. You can then
access and iterate keys and values without casting them. Here is how it looks:
for(MyObject anObject : map.values()){
//do someting to anObject...
}
for(String key : map.keySet()){
MyObject value = map.get(key);
//do something to value
}
36. Array list
The List interface represents a list of Object instances. This means that we could put any object into a
List. Here is an example:
List list = new ArrayList();
list.add(new Integer(2));
list.add("a String");
Because any object could be added, you would also have to cast any objects obtained from these
objects. For instance:
Integer integer = (Integer) list.get(0);
String string = (String) list.get(1);
Very often you only use a single type with a collection. For instance, you only keep String's or something
else in the collection, and not mixed types like I did in the example above.
With Java's Generics features you can set the type of the collection to limit what kind of objects can be
inserted into the collection. Additionally, you don't have to cast the values you obtain from the
collection. Here is an example using Java's Generic's features:
List<String> strings = new ArrayList<String>();
strings.add("a String");
String aString = strings.get(0);
Nice, right?
105

Java 5 also got a new for-loop (also referred to as "for-each") which works well with generified
collections. Here is an example:
List<String> strings = new ArrayList<String>();
//... add String instances to the strings list...
for(String aString : strings){
System.out.println(aString);
}
This for-each loop iterates through all String instances kept in the strings list. For each iteration, the next
String instance is assigned to the aString variable. This for-loop is shorter than original while-loop where
you would iterate the collections Iterator and call Iterator.next() to obtain the next instance.
37. Hash Map
The Map interface maps unique keys to value means it associate value to unique keys which you use to
retrieve value at a later date. Some of the key points are :
Using a key and a value, you can store the value in Map object. You can retrieve it later by using
it's key.
When no element exists in the invoking Map, many methods throw a
'NoSuchElementException'.
A ClassCastException is thrown when an object is incompatible with the elements in a map.
A NullPointerException is thrown if an attempt is made to use a null object and null is not
allowed in the map.
An UnsupportedOperationException is thrown when an attempt is made to change an
unmodifiable map.
Declaration
HashMap<String, Object> map = new HashMap<String, Object>();

Map<String, Object> map = new HashMap<String, Object>();
The difference between the above two declaration is the interface they implement.
The advantage of using Map<String, Object> is that you can substitute the underlying
implementation without any code compatibility problem. But this is not possible in the case of
HashMap<String, Object>.
106


Methods Description
void clear( ) Removes all key/value pairs from the invoking map.
boolean containsKey(Object k)
Returns true if the invoking map contains k as a key.
Otherwise, returns false.
boolean containsValue(Object v)
Returns true if the map contains v as a value. Otherwise,
returns false.
Set entrySet( )
Returns a Set that contains the entries in the map.
The set contains objects of type Map.Entry. This
method provides a set-view of the invoking map.
boolean equals(Object obj)
Returns true if obj is a Map and contains the same entries.
Otherwise, returns false.
Object get(Object k) Returns the value associated with the key k.
int hashCode( ) Returns the hash code for the invoking map.
boolean isEmpty( )
Returns true if the invoking map is empty. Otherwise,
returns false.
Set keySet( )
Returns a Set that contains the keys in the invoking map.
This method provides a set-view of the keys in the invoking map.
Object put(Object k, Object v)
Puts an entry in the invoking map, overwriting any previous value
associated with the key. The key and value are k and v,
respectively. Returns null if the key did not already exist.
Otherwise, the previous value linked to the key is returned.
void putAll(Map m) Puts all the entries from m into this map.
Object remove(Object k) Removes the entry whose key equals k.
int size( ) Returns the number of key/value pairs in the map.
Collection values( )
Returns a collection containing the values in the map. This method
provides a collection-view of the values in the map.
107


Example
import java.util.*;

public class MapDemo {
public static void main(String[] args) {
Map m1 = new HashMap();
m1.put("Ankit", "8");
m1.put("Kapil", "31");
m1.put("Saurabh", "12");
m1.put("Apoorva", "14");
System.out.println();
System.out.println("Elements of Map");
System.out.print(m1);
}

}