1.What are the principle concepts of OOPS?
There are four principle concepts upon which object oriented design and programming rest. They are:
- Abstraction
- Polymorphism
- Inheritance
- Encapsulation
(i.e. easily remembered as A-PIE).
2.What is Abstraction?
Abstraction refers to the act of representing essential features without including the background details or explanations.
3.What is Encapsulation?
Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.
4.What is the difference between abstraction and encapsulation?
- Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.
- Abstraction solves the problem in the design side while Encapsulation is the Implementation.
- Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.
5.What is Inheritance?
- Inheritance is the process by which objects of one class acquire the properties of objects of another class.
- A class that is inherited is called a superclass.
- The class that does the inheriting is called a subclass.
- Inheritance is done by using the keyword extends.
- The two most common reasons to use inheritance are:
- To promote code reuse
- To use polymorphism
6.What is Polymorphism?
Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.
7.How does Java implement polymorphism?
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java).
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
- In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods).
- In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).
8.Explain the different forms of Polymorphism.
There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface.
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
Note: From a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
- Method overloading
- Method overriding through inheritance
- Method overriding through the Java interface
9.What is runtime polymorphism or dynamic method dispatch?
In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.
10.What is Dynamic Binding?
Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.
11.What is method overloading?
Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type.
Note:
Note:
- Overloaded methods MUST change the argument list
- Overloaded methods CAN change the return type
- Overloaded methods CAN change the access modifier
- Overloaded methods CAN declare new or broader checked exceptions
- A method can be overloaded in the same class or in a subclass
12.What is method overriding?
Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type.
Note:
Note:
- The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected).
- You cannot override a method marked final
- You cannot override a method marked static
13.What are the differences between method overloading and method overriding?
| Overloaded Method | Overridden Method |
Arguments | Must change | Must not change |
Return type | Can change | Can’t change except for covariant returns |
Exceptions | Can change | Can reduce or eliminate. Must not throw new or broader checked exceptions |
Access | Can change | Must not make more restrictive (can be less restrictive) |
Invocation | Reference type determines which overloaded version is selected. Happens at compile time. | Object type determines which method is selected. Happens at runtime. |
14.Can overloaded methods be override too?
Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future.
15.Is it possible to override the main method?
NO, because main is a static method. A static method can't be overridden in Java.
16.How to invoke a superclass version of an Overridden method?
To invoke a superclass method that has been overridden in a subclass, you must either call the method directly through a superclass instance, or use the super prefix in the subclass itself. From the point of the view of the subclass, the super prefix provides an explicit reference to the superclass' implementation of the method.
// From subclass
super.overriddenMethod();
17.What is super?
super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword.
Note:
Note:
- You can only go back one level.
- In the constructor, if you use super(), it must be the very first code, and you cannot access any this.xxx variables or methods to compute its parameters.
18.How do you prevent a method from being overridden?
To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means "this is the final implementation of this method", the end of its inheritance hierarchy.
public final void exampleMethod() {
// Method statements
}
// Method statements
}
19.What is an Interface?
An interface is a description of a set of methods that conforming implementing classes must have.
Note:
Note:
- You can’t mark an interface as final.
- Interface variables must be static.
- An Interface cannot extend anything but another interfaces.
20.Can we instantiate an interface?
You can’t instantiate an interface directly, but you can instantiate a class that implements an interface.
21.Can we create an object for an interface?
Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfill all the methods defined in it.
22.Do interfaces have member variables?
Interfaces may have member variables, but these are implicitly public, static, and final- in other words, interfaces can declare only constants, not instance variables that are available to all implementations and may be used as key references for method arguments for example.
23.What modifiers are allowed for methods in an Interface?
Only public and abstract modifiers are allowed for methods in interfaces.
24.What is a marker interface?
Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializableinterface and Cloneable are typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.
25.What is an abstract class?
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation.
Note:
Note:
- If even a single method is abstract, the whole class must be declared abstract.
- Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
- You can’t mark a class as both abstract and final.
26.Can we instantiate an abstract class?
An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).
27.What are the differences between Interface and Abstract class?
Abstract Class | Interfaces |
An abstract class can provide complete, default code and/or just the details that have to be overridden. | An interface cannot provide any code at all,just the signature. |
In case of abstract class, a class may extend only one abstract class. | A Class may implement several interfaces. |
An abstract class can have non-abstract methods. | All methods of an Interface are abstract. |
An abstract class can have instance variables. | An Interface cannot have instance variables. |
An abstract class can have any visibility: public, private, protected. | An Interface visibility must be public (or) none. |
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly. | If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method. |
An abstract class can contain constructors. | An Interface cannot contain constructors. |
Abstract classes are fast. | Interfaces are slow as it requires extra indirection to find corresponding method in the actual class. |
28.When should I use abstract classes and when should I use interfaces?
Use Interfaces when…
- You see that something in your design will change frequently.
- If various implementations only share method signatures then it is better to use Interfaces.
- you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.
Use Abstract Class when…
- If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
- When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.
- Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.
29.When you declare a method as abstract, can other nonabstract methods access it?
Yes, other nonabstract methods can access a method that you declare as abstract.
30.Can there be an abstract class with no abstract methods in it?
Yes, there can be an abstract class without abstract methods.
Java Basic Interview Questions
31.What is Constructor?
- A constructor is a special method whose task is to initialize the object of its class.
- It is special because its name is the same as the class name.
- They do not have return types, not even void and therefore they cannot return values.
- They cannot be inherited, though a derived class can call the base class constructor.
- Constructor is invoked whenever an object of its associated class is created.
32.How does the Java default constructor be provided?
If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter-constructor (default-constructor) for the class in the byte code. The access modifier (public/private/etc.) of the default constructor is the same as the class itself.
33.Can constructor be inherited?
No, constructor cannot be inherited, though a derived class can call the base class constructor.
34.What are the differences between Contructors and Methods?
| Constructors | Methods |
Purpose | Create an instance of a class | Group Java statements |
Modifiers | Cannot be abstract, final, native, static, or synchronized | Can be abstract, final, native, static, or synchronized |
Return Type | No return type, not even void | void or a valid return type |
Name | Same name as the class (first letter is capitalized by convention) -- usually a noun | Any name except the class. Method names begin with a lowercase letter by convention -- usually the name of an action |
this | Refers to another constructor in the same class. If used, it must be the first line of the constructor | Refers to an instance of the owning class. Cannot be used by static methods. |
super | Calls the constructor of the parent class. If used, must be the first line of the constructor | Calls an overridden method in the parent class |
Inheritance | Constructors are not inherited | Methods are inherited |
35.How are this() and super() used with constructors?
- Constructors use this to refer to another constructor in the same class with a different parameter list.
- Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.
36.What are the differences between Class Methods and Instance Methods?
Class Methods | Instance Methods |
Class methods are methods which are declared as static. The method can be called without creating an instance of the class | Instance methods on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword. Instance methods operate on specific instances of classes. |
Class methods can only operate on class members and not on instance members as class methods are unaware of instance members. | Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class. |
Class methods are methods which are declared as static. The method can be called without creating an instance of the class. | Instance methods are not declared as static. |
37.How are this() and super() used with constructors?
- Constructors use this to refer to another constructor in the same class with a different parameter list.
- Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.
38.What are Access Specifiers?
One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. Java allows you to control access to classes, methods, and fields via so-called access specifiers..
39.What are Access Specifiers available in Java?
Java offers four access specifiers, listed below in decreasing accessibility:
- Public- public classes, methods, and fields can be accessed from everywhere.
- Protected- protected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package.
- Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.
- Private- private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses.
Situation | public | protected | default | private |
Accessible to class from same package? | yes | yes | yes | no |
Accessible to class from different package? | yes | no, unless it is a subclass | no | no |
40.What is final modifier?
The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method.
- final Classes- A final class cannot have subclasses.
- final Variables- A final variable cannot be changed once it is initialized.
- final Methods- A final method cannot be overridden by subclasses.
41.What are the uses of final method?
There are two reasons for marking a method as final:
- Disallowing subclasses to change the meaning of the method.
- Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.
42.What is static block?
Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute.
43.What are static variables?
Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static keyword as a modifier.
static type varIdentifier;
where, the name of the variable is varIdentifier and its data type is specified by type.
Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables.
Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables.
44.What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.
45.What are static methods?
Methods declared with the keyword static as modifier are called static methods or class methods. They are so called because they affect a class as a whole, not a particular instance of the class. Static methods are always invoked without reference to a particular instance of a class.
Note:The use of a static method suffers from the following restrictions:
Note:The use of a static method suffers from the following restrictions:
- A static method can only call other static methods.
- A static method must only access static data.
- A static method cannot reference to the current object using keywords super or this.
Java Collections Interview Questions
46.What is an Iterator ?
- The Iterator interface is used to step through the elements of a Collection.
- Iterators let you process each element of a Collection.
- Iterators are a generic way to go through all the elements of a Collection no matter how it is organized.
- Iterator is an Interface implemented a different way for every Collection.
47.How do you traverse through a collection using its Iterator?
To use an iterator to traverse through the contents of a collection, follow these steps:
- Obtain an iterator to the start of the collection by calling the collection̢۪s iterator() method.
- Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
- Within the loop, obtain each element by calling next().
48.How do you remove elements during Iteration?
Iterator also has a method remove() when remove is called, the current element in the iteration is deleted.
49.What is the difference between Enumeration and Iterator?
Enumeration | Iterator |
Enumeration doesn't have a remove() method | Iterator has a remove() method |
Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects | Can be abstract, final, native, static, or synchronized |
Note: So Enumeration is used whenever we want to make Collection objects as Read-only.
50.How is ListIterator?
ListIterator is just like Iterator, except it allows us to access the collection in either the forward or backward direction and lets us modify an element
51.What is the List interface?
- The List interface provides support for ordered collections of objects.
- Lists may contain duplicate elements.
52.What are the main implementations of the List interface ?
The main implementations of the List interface are as follows :
- ArrayList : Resizable-array implementation of the List interface. The best all-around implementation of the List interface.
- Vector : Synchronized resizable-array implementation of the List interface with additional "legacy methods."
- LinkedList : Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques).
53.What are the advantages of ArrayList over arrays ?
Some of the advantages ArrayList has over arrays are:
- It can grow dynamically
- It provides more powerful insertion and search mechanisms than arrays.
54.Difference between ArrayList and Vector ?
ArrayList | Vector |
ArrayList is NOT synchronized by default. | Vector List is synchronized by default. |
ArrayList can use only Iterator to access the elements. | Vector list can use Iterator and Enumeration Interface to access the elements. |
The ArrayList increases its array size by 50 percent if it runs out of room. | A Vector defaults to doubling the size of its array if it runs out of room |
ArrayList has no default size. | While vector has a default size of 10. |
55.How to obtain Array from an ArrayList ?
Array can be obtained from an ArrayList using toArray() method on ArrayList.
List arrayList = new ArrayList();
arrayList.add(…
arrayList.add(…
Object a[] = arrayList.toArray();
56.Why insertion and deletion in ArrayList is slow compared to LinkedList ?
- ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array.
- During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.
57.Why are Iterators returned by ArrayList called Fail Fast ?
Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
58.How do you decide when to use ArrayList and When to use LinkedList?
If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation.
59.What is the Set interface ?
- The Set interface provides methods for accessing the elements of a finite mathematical set
- Sets do not allow duplicate elements
- Contains no methods other than those inherited from Collection
- It adds the restriction that duplicate elements are prohibited
- Two Set objects are equal if they contain the same elements
60.What are the main Implementations of the Set interface ?
The main implementations of the List interface are as follows:
- HashSet
- TreeSet
- LinkedHashSet
- EnumSet
61.What is a HashSet ?
- A HashSet is an unsorted, unordered Set.
- It uses the hashcode of the object being inserted (so the more efficient your hashcode() implementation the better access performance you’ll get).
- Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it.
62.What is a TreeSet ?
TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time.
63.What is an EnumSet ?
An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created.
64.Difference between HashSet and TreeSet ?
HashSet | TreeSet |
HashSet is under set interface i.e. it does not guarantee for either sorted order or sequence order. | TreeSet is under set i.e. it provides elements in a sorted order (acceding order). |
We can add any type of elements to hash set. | We can add only similar types of elements to tree set. |
65.What is a Map ?
- A map is an object that stores associations between keys and values (key/value pairs).
- Given a key, you can find its value. Both keys and values are objects.
- The keys must be unique, but the values may be duplicated.
- Some maps can accept a null key and null values, others cannot.
66.What are the main Implementations of the Map interface ?
The main implementations of the List interface are as follows:
- HashMap
- HashTable
- TreeMap
- EnumMap
67.What is a TreeMap ?
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.
68.How do you decide when to use HashMap and when to use TreeMap ?
For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.
69.Difference between HashMap and Hashtable ?
HashMap | Hashtable |
HashMap lets you have null values as well as one null key. | HashTable does not allows null values as key and value. |
The iterator in the HashMap is fail-safe (If you change the map while iterating, you’ll know). | The enumerator for the Hashtable is not fail-safe. |
HashMap is unsynchronized. | Hashtable is synchronized. |
Note: Only one NULL is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values.
70.How does a Hashtable internally maintain the key-value pairs?
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.
65.What is a Map ?
- A map is an object that stores associations between keys and values (key/value pairs).
- Given a key, you can find its value. Both keys and values are objects.
- The keys must be unique, but the values may be duplicated.
- Some maps can accept a null key and null values, others cannot.
66.What are the main Implementations of the Map interface ?
The main implementations of the List interface are as follows:
- HashMap
- HashTable
- TreeMap
- EnumMap
67.What is a TreeMap ?
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.
68.How do you decide when to use HashMap and when to use TreeMap ?
For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.
69.Difference between HashMap and Hashtable ?
HashMap | Hashtable |
HashMap lets you have null values as well as one null key. | HashTable does not allows null values as key and value. |
The iterator in the HashMap is fail-safe (If you change the map while iterating, you’ll know). | The enumerator for the Hashtable is not fail-safe. |
HashMap is unsynchronized. | Hashtable is synchronized. |
Note: Only one NULL is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values.
70.How does a Hashtable internally maintain the key-value pairs?
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.
24 Collections Framework Interview Questions & Answers for Java developers
Java Collections framework API is a unified architecture for representing and manipulating collections. The API contains Interfaces, Implementations & Algorithm to help java programmer in everyday programming. In nutshell, this API does 6 things at high level
- Reduces programming efforts. - Increases program speed and quality.
- Allows interoperability among unrelated APIs.
- Reduces effort to learn and to use new APIs.
- Reduces effort to design new APIs.
- Encourages & Fosters software reuse.
To be specific, There are six collection java interfaces. The most basic interface is Collection. Three interfaces extend Collection: Set, List, and SortedSet. The other two collection interfaces, Map and SortedMap, do not extend Collection, as they represent mappings rather than true collections.
Some of the collection classes provide traversal of their contents via a java.util.Iterator interface. This interface allows you to walk through a collection of objects, operating on each object in turn. Remember when using Iterators that they contain a snapshot of the collection at the time the Iterator was obtained; generally it is not advisable to modify the collection itself while traversing an Iterator.
Iterator : Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements ListIterator : extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.
Map is Interface which is part of Java collections framework. This is to store Key Value pair, and Hashmap is class that implements that using hashing technique.
Both Hashtable & HashMap provide key-value access to data. The Hashtable is one of the original collection classes in Java (also called as legacy classes). HashMap is part of the new Collections Framework, added with Java 2, v1.2. There are several differences between HashMap and Hashtable in Java as listed below
- The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls. (HashMap allows null values as key and value whereas Hashtable doesn’t allow nulls).
- HashMap does not guarantee that the order of the map will remain constant over time. But one of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable.
- HashMap is non synchronized whereas Hashtable is synchronized.
- Iterator in the HashMap is fail-fast while the enumerator for the Hashtable isn't. So this could be a design consideration.
- What does synchronized means in Hashtable context?
Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
At high level - Fail-fast is a property of a system or software with respect to its response to failures. A fail-fast system is designed to immediately report any failure or condition that is likely to lead to failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly-flawed process. When a problem occurs, a fail-fast system fails immediately and visibly. Failing fast is a non-intuitive technique: "failing immediately and visibly" sounds like it would make your software more fragile, but it actually makes it more robust. Bugs are easier to find and fix, so fewer go into production. In Java, Fail-fast term can be related to context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally", a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn't modify the collection "structurally". However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
From Sun FAQ Page: Many Collection implementations (including all of the ones provided by the JDK) will have a public clone method, but it would be mistake to require it of all Collections. For example, what does it mean to clone a Collection that's backed by a terabyte SQL database? Should the method call cause the company to requisition a new disk farm? Similar arguments hold for serializable. If the client doesn't know the actual type of a Collection, it's much more flexible and less error prone to have the client decide what type of Collection is desired, create an empty Collection of this type, and use the addAll method to copy the elements of the original collection into the new one. Note on Some Important Terms
- Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
- Fail-fast is relevant from the context of iterators. If an iterator has been created on a collection object and some other thread tries to modify the collection object "structurally”, a concurrent modification exception will be thrown. It is possible for other threads though to invoke "set" method since it doesn’t modify the collection "structurally”. However, if prior to calling "set", the collection has been modified structurally, "IllegalArgumentException" will be thrown.
- How can we make Hashmap synchronized?
HashMap can be synchronized by Map m = Collections.synchronizedMap(hashMap);
There are multiple aspects to this decision: 1. The basic difference between a Hashtable and an HashMap is that, Hashtable is synchronized while HashMap is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Hashtable. While if not multiple threads are going to access the same instance then use HashMap. Non synchronized data structure will give better performance than the synchronized one. 2. If there is a possibility in future that - there can be a scenario when you may require to retain the order of objects in the Collection with key-value pair then HashMap can be a good choice. As one of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you can easily swap out the HashMap for a LinkedHashMap. This wouldn't be as easy if you were using Hashtable. Also if you have multiple thread accessing you HashMap then Collections.synchronizedMap() method can be leveraged. Overall HashMap gives you more flexibility in terms of possible future changes.
Vector & ArrayList both classes are implemented using dynamically resizable arrays, providing fast random access and fast traversal. ArrayList and Vector class both implement the List interface. Both the classes are member of Java collection framework, therefore from an API perspective, these two classes are very similar. However, there are still some major differences between the two. Below are some key differences
- Vector is a legacy class which has been retrofitted to implement the List interface since Java 2 platform v1.2
- Vector is synchronized whereas ArrayList is not. Even though Vector class is synchronized, still when you want programs to run in multithreading environment using ArrayList with Collections.synchronizedList() is recommended over Vector.
- ArrayList has no default size while vector has a default size of 10.
- The Enumerations returned by Vector's elements method are not fail-fast. Whereas ArraayList does not have any method returning Enumerations.
- What is the Difference between Enumeration and Iterator interface?
Enumeration and Iterator are the interface available in java.util package. The functionality of Enumeration interface is duplicated by the Iterator interface. New implementations should consider using Iterator in preference to Enumeration. Iterators differ from enumerations in following ways:
1. Enumeration contains 2 methods namely hasMoreElements() & nextElement() whereas Iterator contains three methods namely hasNext(), next(),remove().
2. Iterator adds an optional remove operation, and has shorter method names. Using remove() we can delete the objects but Enumeration interface does not support this feature.
3. Enumeration interface is used by legacy classes. Vector.elements() & Hashtable.elements() method returns Enumeration. Iterator is returned by all Java Collections Framework classes. java.util.Collection.iterator() method returns an instance of Iterator.
Why Java Vector class is considered obsolete or unofficially deprecated? or Why should I always use ArrayList over Vector?
You should use ArrayList over Vector because you should default to non-synchronized access. Vector synchronizes each individual method. That's almost never what you want to do. Generally you want to synchronize a whole sequence of operations. Synchronizing individual operations is both less safe (if you iterate over a Vector, for instance, you still need to take out a lock to avoid anyone else changing the collection at the same time) but also slower (why take out a lock repeatedly when once will be enough)? Of course, it also has the overhead of locking even when you don't need to. It's a very flawed approach to have synchronized access as default. You can always decorate a collection using Collections.synchronizedList - the fact that Vector combines both the "resized array" collection implementation with the "synchronize every operation" bit is another example of poor design; the decoration approach gives cleaner separation of concerns. Vector also has a few legacy methods around enumeration and element retrieval which are different than the List interface, and developers (especially those who learned Java before 1.2) can tend to use them if they are in the code. Although Enumerations are faster, they don't check if the collection was modified during iteration, which can cause issues, and given that Vector might be chosen for its syncronization - with the attendant access from multiple threads, this makes it a particularly pernicious problem. Usage of these methods also couples a lot of code to Vector, such that it won't be easy to replace it with a different List implementation. Despite all above reasons Sun may never officially deprecate Vector class. (Read details Deprecate Hashtable and Vector)
An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.
The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, where as using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used when ever we want to make Collection objects as Read-only.
The basic difference between a Vector and an ArrayList is that, vector is synchronized while ArrayList is not. Thus whenever there is a possibility of multiple threads accessing the same instance, one should use Vector. While if not multiple threads are going to access the same instance then use ArrayList. Non synchronized data structure will give better performance than the synchronized one.
The java.lang.Object has two methods defined in it. They are - public boolean equals(Object obj) public int hashCode(). These two methods are used heavily when objects are stored in collections. There is a contract between these two methods which should be kept in mind while overriding any of these methods. The Java API documentation describes it in detail. The hashCode() method returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable or java.util.HashMap. The general contract of hashCode is: Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application. If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables. As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. The equals(Object obj) method indicates whether some other object is "equal to" this one. The equals method implements an equivalence relation on non-null object references: It is reflexive: for any non-null reference value x, x.equals(x) should return true. It is symmetric: for any non-null reference values x and y, x.equals(y) should return true if and only if y.equals(x) returns true. It is transitive: for any non-null reference values x, y, and z, if x.equals(y) returns true and y.equals(z) returns true, then x.equals(z) should return true. It is consistent: for any non-null reference values x and y, multiple invocations of x.equals(y) consistently return true or consistently return false, provided no information used in equals comparisons on the objects is modified. For any non-null reference value x, x.equals(null) should return false. The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true). Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes. A practical Example of hashcode() & equals(): This can be applied to classes that need to be stored in Set collections. Sets use equals() to enforce non-duplicates, and HashSet uses hashCode() as a first-cut test for equality. Technically hashCode() isn't necessary then since equals() will always be used in the end, but providing a meaningful hashCode() will improve performance for very large sets or objects that take a long time to compare using equals().
What is the difference between Sorting performance of Arrays.sort() vs Collections.sort() ? Which one is faster? Which one to use and when?
Many developers are concerned about the performance difference between java.util.Array.sort() java.util.Collections.sort() methods. Both methods have same algorithm the only difference is type of input to them. Collections.sort() has a input as List so it does a translation of List to array and vice versa which is an additional step while sorting. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array. So clearly it should be used when you have a array available with you and you want to sort it.
Java has implementation of BlockingQueue available since Java 1.5. Blocking Queue interface extends collection interface, which provides you power of collections inside a queue. Blocking Queue is a type of Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. A typical usage example would be based on a producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers. An ArrayBlockingQueue is a implementation of blocking queue with an array used to store the queued objects. The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. ArrayBlockingQueue requires you to specify the capacity of queue at the object construction time itself. Once created, the capacity cannot be increased. This is a classic "bounded buffer" (fixed size buffer), in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Attempts to put an element to a full queue will result in the put operation blocking; attempts to retrieve an element from an empty queue will be blocked.
Though the Map interface is part of collections framework, it does not extend collection interface. This is by design, and the answer to this questions is best described in Sun's FAQ Page: This was by design. We feel that mappings are not collections and collections are not mappings. Thus, it makes little sense for Map to extend the Collection interface (or vice versa). If a Map is a Collection, what are the elements? The only reasonable answer is "Key-value pairs", but this provides a very limited (and not particularly useful) Map abstraction. You can't ask what value a given key maps to, nor can you delete the entry for a given key without knowing what value it maps to. Collection could be made to extend Map, but this raises the question: what are the keys? There's no really satisfactory answer, and forcing one leads to an unnatural interface. Maps can be viewed as Collections (of keys, values, or pairs), and this fact is reflected in the three "Collection view operations" on Maps (keySet, entrySet, and values). While it is, in principle, possible to view a List as a Map mapping indices to elements, this has the nasty property that deleting an element from the List changes the Key associated with every element before the deleted element. That's why we don't have a map view operation on Lists.
Which implementation of the List interface provides for the fastest insertion of a new element into the middle of the list?
a. Vector b. ArrayList c. LinkedList ArrayList and Vector both use an array to store the elements of the list. When an element is inserted into the middle of the list the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.
java.util.ArrayList and java.util.LinkedList are two Collections classes used for storing lists of object referencesHere are some key differences:
o ArrayList uses primitive object array for storing objects whereas LinkedList is made up of a chain of nodes. Each node stores an element and the pointer to the next node. A singly linked list only has pointers to next. A doubly linked list has a pointer to the next and the previous element. This makes walking the list backward easier.
o ArrayList implements the RandomAccess interface, and LinkedList does not. The commonly used ArrayList implementation uses primitive Object array for internal storage. Therefore an ArrayList is much faster than a LinkedList for random access, that is, when accessing arbitrary list elements using the get method. Note that the get method is implemented for LinkedLists, but it requires a sequential scan from the front or back of the list. This scan is very slow. For a LinkedList, there's no fast way to access the Nth element of the list.
o Adding and deleting at the start and middle of the ArrayList is slow, because all the later elements have to be copied forward or backward. (Using System.arrayCopy()) Whereas Linked lists are faster for inserts and deletes anywhere in the list, since all you do is update a few next and previous pointers of a node.
o Each element of a linked list (especially a doubly linked list) uses a bit more memory than its equivalent in array list, due to the need for next and previous pointers.
o ArrayList may also have a performance issue when the internal array fills up. The arrayList has to create a new array and copy all the elements there. The ArrayList has a growth algorithm of (n*3)/2+1, meaning that each time the buffer is too small it will create a new one of size (n*3)/2+1 where n is the number of elements of the current buffer. Hence if we can guess the number of elements that we are going to have, then it makes sense to create a arraylist with that capacity during object creation (using construtor new ArrayList(capacity)). Whereas LinkedLists should not have such capacity issues.
Where will you use ArrayList and Where will you use LinkedList? Or Which one to use when (ArrayList / LinkedList).
Below is a snippet from SUN's site. The Java SDK contains 2 implementations of the List interface - ArrayList and LinkedList. If you frequently add elements to the beginning of the List or iterate over the List to delete elements from its interior, you should consider using LinkedList. These operations require constant-time in a LinkedList and linear-time in an ArrayList. But you pay a big price in performance. Positional access requires linear-time in a LinkedList and constant-time in an ArrayList.
What is performance of various Java collection implementations/algorithms? What is Big 'O' notation for each of them ?
Each java collection implementation class have different performance for different methods, which makes them suitable for different programming needs.
o Performance of Map interface implementations
Hashtable
An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a "hash collision", a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.
HashMap
This implementation provides constant-time [ Big O Notation is O(1) ] performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
TreeMap
The TreeMap implementation provides guaranteed log(n) [ Big O Notation is O(log N) ] time cost for the containsKey, get, put and remove operations.
LinkedHashMap
A linked hash map has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashMap. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashMap, as iteration times for this class are unaffected by capacity.
o Performance of Set interface implementations
HashSet
The HashSet class offers constant-time [ Big O Notation is O(1) ] performance for the basic operations (add, remove, contains and size), assuming the hash function disperses the elements properly among the buckets. Iterating over this set requires time proportional to the sum of the HashSet instance's size (the number of elements) plus the "capacity" of the backing HashMap instance (the number of buckets). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.
TreeSet
The TreeSet implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
LinkedHashSet
A linked hash set has two parameters that affect its performance: initial capacity and load factor. They are defined precisely as for HashSet. Note, however, that the penalty for choosing an excessively high value for initial capacity is less severe for this class than for HashSet, as iteration times for this class are unaffected by capacity.
o Performance of List interface implementations
LinkedList
- Performance of get and remove methods is linear time [ Big O Notation is O(n) ] - Performance of add and Iterator.remove methods is constant-time [ Big O Notation is O(1) ]
ArrayList
- The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. [ Big O Notation is O(1) ] - The add operation runs in amortized constant time [ Big O Notation is O(1) ] , but in worst case (since the array must be resized and copied) adding n elements requires linear time [ Big O Notation is O(n) ] - Performance of remove method is linear time [ Big O Notation is O(n) ] - All of the other operations run in linear time [ Big O Notation is O(n) ]. The constant factor is low compared to that for the LinkedList implementation.
10 Core Java Interview Questions & Answers for Senior Experienced Developer
A Java object is considered immutable when its state cannot change after it is created. Use of immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. java.lang.String and java.lang.Integer classes are the Examples of immutable objects from the Java Development Kit. Immutable objects simplify your program, since they :
- are simple to use test and construct.
- are automatically thread-safe.
- do not require a copy constructor.
- do not require an implementation of clone.
- allow hashCode to use lazy initialization, and to cache its return value.
- do not need to be copied defensively when used as a field.
- are good Map keys and Set elements (these objects must not change state while stored in the collection).
- have their class invariant established once upon construction, and it never needs to be checked again.
- always have "failure atomicity" (a term used by Joshua Bloch) : if an immutable object throws an exception, it's never left in an undesirable or indeterminate state.
· How to create a immutable object in Java? Does all property of immutable object needs to be final?
To create a object immutable You need to make the class final and all its member final so that once objects gets crated no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor. Also its NOT necessary to have all the properties final since you can achieve same functionality by making member as non final but private and not modifying them except in constructor.
Below is the main difference between these three most commonly used classes.
- String class objects are immutable whereas StringBuffer and StringBuilder objects are mutable.
- StringBuffer is synchronized while StringBuilder is not synchronized.
- Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder.
Criteria to choose among String, StringBuffer and StringBuilder
- If the Object value is not going to change use String Class because a String object is immutable.
- If the Object value can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
- In case the Object value can change, and will be modified by multiple threads, use a StringBuffer because StringBuffer is synchronized.
It is very useful to have strings implemented as final or immutable objects. Below are some advantages of String Immutability in Java
- Immutable objects are thread-safe. Two threads can both work on an immutable object at the same time without any possibility of conflict.
- Security: the system can pass on sensitive bits of read-only information without worrying that it will be altered
- You can share duplicates by pointing them to a single instance.
- You can create substrings without copying. You just create a pointer into an existing base String guaranteed never to change. Immutability is the secret behind Java’s very fast substring implementation.
- Immutable objects are much better suited to be Hashtable keys. If you change the value of an object that is used as a hash table key without removing it and re-adding it you lose the mapping.
- Since String is immutable, inside each String is a char[] exactly the correct length. Unlike a StringBuilder there is no need for padding to allow for growth.
- If String were not final, you could create a subclass and have two strings that look alike when "seen as Strings", but that are actually different.
The Java Spec says that everything in Java is pass-by-value. There is no such thing as "pass-by-reference" in Java. The difficult thing can be to understand that Java passes "objects as references" passed by value. This can certainly get confusing and I would recommend reading this article from an expert:http://javadude.com/articles/passbyvalue.htm Also read this interesting thread with example on StackOverflow :Java Pass By Ref or Value
This Error is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. Note: Its an Error (extends java.lang.Error) not Exception. Two important types of OutOfMemoryError are often encountered
1. java.lang.OutOfMemoryError: Java heap space
The quick solution is to add these flags to JVM command line when Java runtime is started:
1. -Xms1024m -Xmx1024m
2. java.lang.OutOfMemoryError: PermGen space
The solution is to add these flags to JVM command line when Java runtime is started:
1. -XX:+CMSClassUnloadingEnabled-XX:+CMSPermGenSweepingEnabled
Long Term Solution: Increasing the Start/Max Heap size or changing Garbage Collection options may not always be a long term solution for your Out Of Memory Error problem. Best approach is to understand the memory needs of your program and ensure it uses memory wisely and does not have leaks. You can use a Java memory profiler to determine what methods in your program are allocating large number of objects and then determine if there is a way to make sure they are no longer referenced, or to not allocate them in the first place.
· What is the use of the finally block? Is finally block in Java guaranteed to be called? When finally block is NOT called?
Finally is the block of code that executes always. The code in finally block will execute even if an exception is occurred. Finally block is NOT called in following conditions
- If the JVM exits while the try or catch code is being executed, then the finally block may not execute. This may happen due to System.exit() call.
- if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.
- If a exception is thrown in finally block and not handled then remaining code in finally block may not be executed.
From the JavaDoc of java.sql.Date:
A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT. To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.
Explanation: A java.util.Date represents date and time of day, a java.sql.Date only represents a date (the complement of java.sql.Date is java.sql.Time, which only represents a time of day, but also extends java.util.Date).
The marker interface is a design pattern, used with languages that provide run-time type information about objects. It provides a way to associate metadata with a class where the language does not have explicit support for such metadata. To use this pattern, a class implements a marker interface, and code that interact with instances of that class test for the existence of the interface. Whereas a typical interface specifies functionality (in the form of method declarations) that an implementing class must support, a marker interface need not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. There can be some hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used. Java utilizes this pattern very well and the example interfaces are
- java.io.Serializable - Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.
- java.rmi.Remote - The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. Only those methods specified in a "remote interface", an interface that extends java.rmi.Remote are available remotely.
- java.lang.Cloneable - A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class. Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.
- javax.servlet.SingleThreadModel - Ensures that servlets handle only one request at a time. This interface has no methods.
- java.util.EvenListener - A tagging interface that all event listener interfaces must extend.
The "instanceof" keyword in java can be used to test if an object is of a specified type. So this keyword in combination with Marker interface can be used to take different actions based on type of interface an object implements.
· Why main() in java is declared as public static void main? What if the main method is declared as private?
Public - main method is called by JVM to run the method which is outside the scope of project therefore the access specifier has to be public to permit call from anywhere outside the application static - When the JVM makes are call to the main method there is not object existing for the class being called therefore it has to have static method to allow invocation from class. void - Java is platform independent language therefore if it will return some value then the value may mean different to different platforms so unlike C it can not assume a behavior of returning value to the operating system. If main method is declared as private then - Program will compile properly but at run-time it will give "Main method not public." error.
12 JDBC Interview Questions & Answers for Java Developers - Java Database Connectivity
1. What are available drivers in JDBC?
JDBC technology drivers fit into one of four categories:
- A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun, see JDBC-ODBC Bridge Driver.
- A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.
- A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products.
- A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.
2. What are the types of statements in JDBC?
the JDBC API has 3 Interfaces, (1. Statement, 2. PreparedStatement, 3. CallableStatement ). The key features of these are as follows: Statement
o This interface is used for executing a static SQL statement and returning the results it produces.
o The object of Statement class can be created using Connection.createStatement() method.
PreparedStatement
o A SQL statement is pre-compiled and stored in a PreparedStatement object.
o This object can then be used to efficiently execute this statement multiple times.
o The object of PreparedStatement class can be created using Connection.prepareStatement() method. This extends Statement interface.
CallableStatement
o This interface is used to execute SQL stored procedures.
o This extends PreparedStatement interface.
o The object of CallableStatement class can be created using Connection.prepareCall() method.
What is a stored procedure? How to call stored procedure using JDBC API?
Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters. Stored procedures can be called using CallableStatement class in JDBC API. Below code snippet shows how this can be achieved.
0. CallableStatement cs = con.prepareCall("{call MY_STORED_PROC_NAME}");
1. ResultSet rs = cs.executeQuery();
What is Connection pooling? What are the advantages of using a connection pool?
Connection Pooling is a technique used for sharing the server resources among requested clients. It was pioneered by database vendors to allow multiple clients to share a cached set of connection objects that provides access to a database.
Getting connection and disconnecting are costly operation, which affects the application performance, so we should avoid creating multiple connection during multiple database interactions. A pool contains set of Database connections which are already connected, and any client who wants to use it can take it from pool and when done with using it can be returned back to the pool.
Apart from performance this also saves you resources as there may be limited database connections available for your application.
How to do database connection using JDBC thin driver ?
This is one of the most commonly asked questions from JDBC fundamentals, and knowing all the steps of JDBC connection is important.
0. import java.sql.*;
1. class JDBCTest {
2. public static void main (String args []) throws Exception
3. {
4. //Load driver class
5. Class.forName ("oracle.jdbc.driver.OracleDriver");
6. //Create connection
7. Connection conn = DriverManager.getConnection
8. ("jdbc:oracle:thin:@hostname:1526:testdb", "scott", "tiger");
9. // @machineName:port:SID, userid, password
10.
11. Statement stmt = conn.createStatement();
12. ResultSet rs = stmt.executeQuery("select 'Hi' from dual");
13. while (rs.next())
14. System.out.println (rs.getString(1)); // Print col 1 => Hi
15. stmt.close();
16. }
17.}
What does Class.forName() method do?
Method forName() is a static method of java.lang.Class. This can be used to dynamically load a class at run-time. Class.forName() loads the class if its not already loaded. It also executes the static block of loaded class. Then this method returns an instance of the loaded class. So a call to Class.forName('MyClass') is going to do following
- Load the class MyClass.
- Execute any static block code of MyClass.
- Return an instance of MyClass.
JDBC Driver loading using Class.forName is a good example of best use of this method. The driver loading is done like this
0. Class.forName("org.mysql.Driver");
All JDBC Drivers have a static block that registers itself with DriverManager and DriverManager has static initializer method registerDriver() which can be called in a static blocks of Driver class. A MySQL JDBC Driver has a static initializer which looks like this:
1. static {
2. try {
3. java.sql.DriverManager.registerDriver(new Driver());
4. } catch (SQLException E) {
5. throw new RuntimeException("Can't register driver!");
6. }
7. }
Class.forName() loads driver class and executes the static block and the Driver registers itself with the DriverManager.
Which one will you use Statement or PreparedStatement? Or Which one to use when (Statement/PreparedStatement)? Compare PreparedStatement vs Statement.
By Java API definitions: Statement is a object used for executing a static SQL statement and returning the results it produces. PreparedStatement is a SQL statement which is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times. There are few advantages of using PreparedStatements over Statements
0. Since its pre-compiled, Executing the same query multiple times in loop, binding different parameter values each time is faster. (What does pre-compiled statement means? The prepared statement(pre-compiled) concept is not specific to Java, it is a database concept. Statement precompiling means: when you execute a SQL query, database server will prepare a execution plan before executing the actual query, this execution plan will be cached at database server for further execution.)
1. In PreparedStatement the setDate()/setString() methods can be used to escape dates and strings properly, in a database-independent way.
2. SQL injection attacks on a system are virtually impossible when using PreparedStatements.
What does setAutoCommit(false) do?
A JDBC connection is created in auto-commit mode by default. This means that each individual SQL statement is treated as a transaction and will be automatically committed as soon as it is executed. If you require two or more statements to be grouped into a transaction then you need to disable auto-commit mode using below command
0. con.setAutoCommit(false);
Once auto-commit mode is disabled, no SQL statements will be committed until you explicitly call the commit method. A Simple transaction with use of autocommit flag is demonstrated below.
1. con.setAutoCommit(false);
2. PreparedStatement updateStmt =
3. con.prepareStatement( "UPDATE EMPLOYEE SET SALARY = ? WHERE EMP_NAME LIKE ?");
4. updateStmt.setInt(1, 5000); updateSales.setString(2, "Jack");
5. updateStmt.executeUpdate();
6. updateStmt.setInt(1, 6000); updateSales.setString(2, "Tom");
7. updateStmt.executeUpdate();
8. con.commit();
9. con.setAutoCommit(true);
What are database warnings and How can I handle database warnings in JDBC?
Warnings are issued by database to notify user of a problem which may not be very severe. Database warnings do not stop the execution of SQL statements. In JDBC SQLWarning is an exception that provides information on database access warnings. Warnings are silently chained to the object whose method caused it to be reported. Warnings may be retrieved from Connection, Statement, and ResultSet objects. Handling SQLWarning from connection object
0. //Retrieving warning from connection object
1. SQLWarning warning = conn.getWarnings();
2.
3. //Retrieving next warning from warning object itself
4. SQLWarning nextWarning = warning.getNextWarning();
5.
6. //Clear all warnings reported for this Connection object.
7. conn.clearWarnings();
Handling SQLWarning from Statement object
8. //Retrieving warning from statement object
9. stmt.getWarnings();
10.
11. //Retrieving next warning from warning object itself
12. SQLWarning nextWarning = warning.getNextWarning();
13.
14. //Clear all warnings reported for this Statement object.
15. stmt.clearWarnings();
Handling SQLWarning from ResultSet object
16.//Retrieving warning from resultset object
17. rs.getWarnings();
18.
19. //Retrieving next warning from warning object itself
20. SQLWarning nextWarning = warning.getNextWarning();
21.
22. //Clear all warnings reported for this resultset object.
23. rs.clearWarnings();
The call to getWarnings() method in any of above way retrieves the first warning reported by calls on this object. If there is more than one warning, subsequent warnings will be chained to the first one and can be retrieved by calling the method SQLWarning.getNextWarning on the warning that was retrieved previously. A call toclearWarnings() method clears all warnings reported for this object. After a call to this method, the method getWarnings returns null until a new warning is reported for this object. Trying to call getWarning() on a connection after it has been closed will cause an SQLException to be thrown. Similarly, trying to retrieve a warning on a statement after it has been closed or on a result set after it has been closed will cause an SQLException to be thrown. Note that closing a statement also closes a result set that it might have produced.
What is Metadata and why should I use it?
JDBC API has 2 Metadata interfaces DatabaseMetaData & ResultSetMetaData. The DatabaseMetaData provides Comprehensive information about the database as a whole. This interface is implemented by driver vendors to let users know the capabilities of a Database Management System (DBMS) in combination with the driver based on JDBC technology ("JDBC driver") that is used with it. Below is a sample code which demonstrates how we can use the DatabaseMetaData
0. DatabaseMetaData md = conn.getMetaData();
1. System.out.println("Database Name: " + md.getDatabaseProductName());
2. System.out.println("Database Version: " + md.getDatabaseProductVersion());
3. System.out.println("Driver Name: " + md.getDriverName());
4. System.out.println("Driver Version: " + md.getDriverVersion());
The ResultSetMetaData is an object that can be used to get information about the types and properties of the columns in a ResultSet object. Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns. Below a sample code which demonstrates how we can use the ResultSetMetaData
5. ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
6. ResultSetMetaData rsmd = rs.getMetaData();
7. int numberOfColumns = rsmd.getColumnCount();
8. boolean b = rsmd.isSearchable(1);
What is RowSet? or What is the difference between RowSet and ResultSet? or Why do we need RowSet? or What are the advantages of using RowSet over ResultSet?
RowSet is a interface that adds support to the JDBC API for the JavaBeans component model. A rowset, which can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time. The RowSet interface provides a set of JavaBeans properties that allow a RowSet instance to be configured to connect to a JDBC data source and read some data from the data source. A group of setter methods (setInt, setBytes, setString, and so on) provide a way to pass input parameters to a rowset's command property. This command is the SQL query the rowset uses when it gets its data from a relational database, which is generally the case. Rowsets are easy to use since the RowSet interface extends the standard java.sql.ResultSet interface so it has all the methods of ResultSet. There are two clear advantages of using RowSet over ResultSet
o RowSet makes it possible to use the ResultSet object as a JavaBeans component. As a consequence, a result set can, for example, be a component in a Swing application.
o RowSet be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a RowSet object implementation (e.g. JdbcRowSet) with the data of a ResultSet object and then operate on the RowSet object as if it were the ResultSet object.
What is a connected RowSet? or What is the difference between connected RowSet and disconnected RowSet? or Connected vs Disconnected RowSet, which one should I use and when?
Connected RowSet
A RowSet object may make a connection with a data source and maintain that connection throughout its life cycle, in which case it is called a connected rowset. A rowset may also make a connection with a data source, get data from it, and then close the connection. Such a rowset is called a disconnected rowset. A disconnected rowset may make changes to its data while it is disconnected and then send the changes back to the original source of the data, but it must reestablish a connection to do so. Example of Connected RowSet: A JdbcRowSet object is a example of connected RowSet, which means it continually maintains its connection to a database using a JDBC technology-enabled driver.
Disconnected RowSet
A disconnected rowset may have a reader (a RowSetReader object) and a writer (a RowSetWriter object) associated with it. The reader may be implemented in many different ways to populate a rowset with data, including getting data from a non-relational data source. The writer can also be implemented in many different ways to propagate changes made to the rowset's data back to the underlying data source. Example of Disconnected RowSet: A CachedRowSet object is a example of disconnected rowset, which means that it makes use of a connection to its data source only briefly. It connects to its data source while it is reading data to populate itself with rows and again while it is propagating changes back to its underlying data source. The rest of the time, a CachedRowSet object is disconnected, including while its data is being modified. Being disconnected makes a RowSet object much leaner and therefore much easier to pass to another component. For example, a disconnected RowSet object can be serialized and passed over the wire to a thin client such as a personal digital assistant (PDA).
What is the benefit of having JdbcRowSet implementation? Why do we need a JdbcRowSet like wrapper around ResultSet?
The JdbcRowSet implementation is a wrapper around a ResultSet object that has following advantages over ResultSet
o This implementation makes it possible to use the ResultSet object as a JavaBeans component. A JdbcRowSet can be used as a JavaBeans component in a visual Bean development environment, can be created and configured at design time and executed at run time.
o It can be used to make a ResultSet object scrollable and updatable. All RowSet objects are by default scrollable and updatable. If the driver and database being used do not support scrolling and/or updating of result sets, an application can populate a JdbcRowSet object with the data of a ResultSet object and then operate on the JdbcRowSet object as if it were the ResultSet object.
20 Multi Threading Interview Questions & Answers for Java Developers
With respect to multi-threading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one Java thread to modify a shared variable while another thread is in the process of using or updating same shared variable. This usually leads to erroneous behavior or program.
A Java thread could be implemented by using Runnable interface or by extending the Thread class. The Runnable is more advantageous, when you are going for multiple inheritance.
Thread.start() method (native method) of Thread class actually does the job of running the Thread.run() method in a thread. If we directly call Thread.run() method it will executed in same thread, so does not solve the purpose of creating a new thread.
We need run() & start() method both because JVM needs to create a separate thread which can not be differentiated from a normal method call. So this job is done by start method native implementation which has to be explicitly called. Another advantage of having these two methods is we can have any object run as a thread if it implements Runnable interface. This is to avoid Java’s multiple inheritance problems which will make it difficult to inherit another class with Thread.
Below are some key points about ThreadLocal variables
- A thread-local variable effectively provides a separate copy of its value for each thread that uses it.
- ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread
- In case when multiple threads access a ThreadLocal instance, separate copy of Threadlocal variable is maintained for each thread.
- Common use is seen in DAO pattern where the DAO class can be singleton but the Database connection can be maintained separately for each thread. (Per Thread Singleton)
ThreadLocal variable are difficult to understand and I have found below reference links very useful in getting better understanding on them
This exception is thrown when you try to call wait()/notify()/notifyAll() any of these methods for an Object from a point in your program where u are NOT having a lock on that object.(i.e. u r not executing any synchronized block/method of that object and still trying to call wait()/notify()/notifyAll()) wait(), notify() and notifyAll() all throw IllegalMonitorStateException. since This exception is a subclass of RuntimeException so we r not bound to catch it (although u may if u want to). and being a RuntimeException this exception is not mentioned in the signature of wait(), notify(), notifyAll() methods.
Thread.sleep() sends the current thread into the "Not Runnable" state for some amount of time. The thread keeps the monitors it has aquired -- i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt() it will wake up the sleeping thread. Note that sleep is a static method, which means that it always affects the current thread (the one that is executing the sleep method). A common mistake is to call t.sleep() where t is a different thread; even then, it is the current thread that will sleep, not the t thread. t.suspend() is deprecated. Using it is possible to halt a thread other than the current thread. A suspended thread keeps all its monitors and since this state is not interruptable it is deadlock prone. object.wait() sends the current thread into the "Not Runnable" state, like sleep(), but with a twist. Wait is called on a object, not a thread; we call this object the "lock object." Before lock.wait() is called, the current thread must synchronize on the lock object; wait() then releases this lock, and adds the thread to the "wait list" associated with the lock. Later, another thread can synchronize on the same lock object and call lock.notify(). This wakes up the original, waiting thread. Basically, wait()/notify() is like sleep()/interrupt(), only the active thread does not need a direct pointer to the sleeping thread, but only to the shared lock object.
Synchronized static methods have a lock on the class "Class", so when a thread enters a synchronized static method, the class itself gets locked by the thread monitor and no other thread can enter any static synchronized methods on that class. This is unlike instance methods, as multiple threads can access "same synchronized instance methods" at same time for different instances.
· Can a thread call a non-synchronized instance method of an Object when a synchronized method is being executed ?
Yes, a Non synchronized method can always be called without any problem. In fact Java does not do any check for a non-synchronized method. The Lock object check is performed only for synchronized methods/blocks. In case the method is not declared synchronized Jave will call even if you are playing with shared data. So you have to be careful while doing such thing. The decision of declaring a method as synchronized has to be based on critical section access. If your method does not access a critical section (shared resource or data structure) it need not be declared synchronized. Below is the example which demonstrates this, The Common class has two methods synchronizedMethod1() and method1() MyThread class is calling both the methods in separate threads,
1. public class Common {
2.
3. public synchronized void synchronizedMethod1() {
4. System.out.println("synchronizedMethod1 called");
5. try {
6. Thread.sleep(1000);
7. } catch (InterruptedException e) {
8. e.printStackTrace();
9. }
10.System.out.println("synchronizedMethod1 done");
11.}
12.public void method1() {
13.System.out.println("Method 1 called");
14.try {
15.Thread.sleep(1000);
16.} catch (InterruptedException e) {
17.e.printStackTrace();
18.}
19.System.out.println("Method 1 done");
20.}
21.}
1. public class MyThread extends Thread {
2. private int id = 0;
3. private Common common;
4.
5. public MyThread(String name, int no, Common object) {
6. super(name);
7. common = object;
8. id = no;
9. }
10.
11.public void run() {
12.System.out.println("Running Thread" + this.getName());
13.try {
14.if (id == 0) {
15.common.synchronizedMethod1();
16.} else {
17.common.method1();
18.}
19.} catch (Exception e) {
20.e.printStackTrace();
21.}
22.}
23.
24.public static void main(String[] args) {
25.Common c = new Common();
26.MyThread t1 = new MyThread("MyThread-1", 0, c);
27.MyThread t2 = new MyThread("MyThread-2", 1, c);
28.t1.start();
29.t2.start();
30.}
31.}
Here is the output of the program
1. Running ThreadMyThread-1
2. synchronizedMethod1 called
3. Running ThreadMyThread-2
4. Method 1 called
5. synchronizedMethod1 done
6. Method 1 done
This shows that method1() - is called even though the synchronizedMethod1() was in execution.
No. If a object has synchronized instance methods then the Object itself is used a lock object for controlling the synchronization. Therefore all other instance methods need to wait until previous method call is completed. See the below sample code which demonstrate it very clearly. The Class Common has 2 methods called synchronizedMethod1() and synchronizedMethod2() MyThread class is calling both the methods
1. public class Common {
2. public synchronized void synchronizedMethod1() {
3. System.out.println("synchronizedMethod1 called");
4. try {
5. Thread.sleep(1000);
6. } catch (InterruptedException e) {
7. e.printStackTrace();
8. }
9. System.out.println("synchronizedMethod1 done");
10.}
11.
12.public synchronized void synchronizedMethod2() {
13.System.out.println("synchronizedMethod2 called");
14.try {
15.Thread.sleep(1000);
16.} catch (InterruptedException e) {
17.e.printStackTrace();
18.}
19.System.out.println("synchronizedMethod2 done");
20.}
21.}
1. public class MyThread extends Thread {
2. private int id = 0;
3. private Common common;
4.
5. public MyThread(String name, int no, Common object) {
6. super(name);
7. common = object;
8. id = no;
9. }
10.
11.public void run() {
12.System.out.println("Running Thread" + this.getName());
13.try {
14.if (id == 0) {
15.common.synchronizedMethod1();
16.} else {
17.common.synchronizedMethod2();
18.}
19.} catch (Exception e) {
20.e.printStackTrace();
21.}
22.}
23.
24.public static void main(String[] args) {
25.Common c = new Common();
26.MyThread t1 = new MyThread("MyThread-1", 0, c);
27.MyThread t2 = new MyThread("MyThread-2", 1, c);
28.t1.start();
29.t2.start();
30.}
31.}
Deadlock is a situation where two or more threads are blocked forever, waiting for each other. This may occur when two threads, each having a lock on one resource, attempt to acquire a lock on the other's resource. Each thread would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. In terms of Java API, thread deadlock can occur in following conditions:
- When two threads call Thread.join() on each other.
- When two threads use nested synchronized blocks to lock two objects and the blocks lock the same objects in different order.
Starvation and livelock are much less common a problem than deadlock, but are still problems that every designer of concurrent software is likely to encounter.
LiveLock
Livelock occurs when all threads are blocked, or are otherwise unable to proceed due to unavailability of required resources, and the non-existence of any unblocked thread to make those resources available. In terms of Java API, thread livelock can occur in following conditions:
- When all the threads in a program execute Object.wait(0) on an object with zero parameter. The program is live-locked and cannot proceed until one or more threads call Object.notify() or Object.notifyAll() on the relevant objects. Because all the threads are blocked, neither call can be made.
- When all the threads in a program are stuck in infinite loops.
Starvation
Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by "greedy" threads. For example, suppose an object provides a synchronized method that often takes a long time to return. If one thread invokes this method frequently, other threads that also need frequent synchronized access to the same object will often be blocked. Starvation occurs when one thread cannot access the CPU because one or more other threads are monopolizing the CPU. In Java, thread starvation can be caused by setting thread priorities inappropriately. A lower-priority thread can be starved by higher-priority threads if the higher-priority threads do not yield control of the CPU from time to time.
Earlier versions of Java had no mechanism to handle/detect deadlock. Since JDK 1.5 there are some powerful methods added in the java.lang.management package to diagnose and detect deadlocks. The java.lang.management.ThreadMXBean interface is management interface for the thread system of the Java virtual machine. It has two methods which can leveraged to detect deadlock in a Java application.
- findMonitorDeadlockedThreads() - This method can be used to detect cycles of threads that are in deadlock waiting to acquire object monitors. It returns an array of thread IDs that are deadlocked waiting on monitor.
- findDeadlockedThreads() - It returns an array of thread IDs that are deadlocked waiting on monitor or ownable synchronizers.
An object is considered immutable if its state cannot change after it is constructed. Maximum reliance on immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. Examples of immutable objects from the JDK include String and Integer. Immutable objects greatly simplify your multi threaded program, since they are
- Simple to construct, test, and use.
- Automatically thread-safe and have no synchronization issues.
To create a object immutable You need to make the class final and all its member final so that once objects gets crated no one can modify its state. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.
A Thread Dump is a complete list of active threads. A java thread dump is a way of finding out what each thread in the JVM is doing at a particular point of time. This is especially useful when your java application seems to have some performance issues. Thread dump will help you to find out which thread is causing this. There are several ways to take thread dumps from a JVM. It is highly recommended to take more than 1 thread dump and analyze the results based on it. Follow below steps to take thread dump of a java process
- Step 1
On UNIX, Linux and Mac OSX Environment run below command:
ps -el | grep java
On Windows:
Press Ctrl+Shift+Esc to open the task manager and find the PID of the java process - Step 2:
Use jstack command to print the Java stack traces for a given Java process PID
jstack [PID]
More details of jstack command can be found here : JSTACK Command Manual
Thread leak is when a application does not release references to a thread object properly. Due to this some Threads do not get garbage collected and the number of unused threads grow with time. Thread leak can often cause serious issues on a Java application since over a period of time too many threads will be created but not released and may cause applications to respond slow or hang.
If an application has thread leak then with time it will have too many unused threads. Try to find out what type of threads is leaking out. This can be done using following ways
- Give unique and descriptive names to the threads created in application. - Add log entry in all thread at various entry and exit points in threads.
- Change debugging config levels (debug, info, error etc) and analyze log messages.
- When you find the class that is leaking out threads check how new threads are instantiated and how they're closed.
- Make sure the thread is Guaranteed to close properly by doing following - Handling all Exceptions properly.
- Make sure the thread is Guaranteed to close properly by doing following
- Handling all Exceptions properly.
- releasing all resources (e.g. connections, files etc) before it closes.
A thread pool is a collection of threads on which task can be scheduled. Instead of creating a new thread for each task, you can have one of the threads from the thread pool pulled out of the pool and assigned to the task. When the thread is finished with the task, it adds itself back to the pool and waits for another assignment. One common type of thread pool is the fixed thread pool. This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread. Below are key reasons to use a Thread Pool
- Using thread pools minimizes the JVM overhead due to thread creation. Thread objects use a significant amount of memory, and in a large-scale application, allocating and de-allocating many thread objects creates a significant memory management overhead.
- You have control over the maximum number of tasks that are being processed in parallel (= number of threads in the pool).
Most of the executor implementations in java.util.concurrent use thread pools, which consist of worker threads. This kind of thread exists separately from the Runnable and Callable tasks it executes and is often used to execute multiple tasks.
Yes, the run method of a runnable class can be synchronized. If you make run method synchronized then the lock on runnable object will be occupied before executing the run method. In case we start multiple threads using the same runnable object in the constructor of the Thread then it would work. But until the 1st thread ends the 2nd thread cannot start and until the 2nd thread ends the next cannot start as all the threads depend on lock on same object
As per Java Language Specification, constructors cannot be synchronized because other threads cannot see the object being created before the thread creating it has finished it. There is no practical need of a Java Objects constructor to be synchronized, since it would lock the object being constructed, which is normally not available to other threads until all constructors of the object finish
15 Java Serialization Interview Questions and Answers for Experienced Developers
Serialization is a mechanism by which you can save or transfer the state of an object by converting it to a byte stream. This can be done in java by implementing Serialiazable interface. Serializable is defined as a marker interface which needs to be implemented for transferring an object over a network or persistence of its state to a file. Since its a marker interface, it does not contain any methods. Implementation of this interface enables the conversion of object into byte stream and thus can be transferred. The object conversion is done by the JVM using its default serialization mechanism.
Serialization is required for a variety of reasons. It is required to send across the state of an object over a network by means of a socket. One can also store an object’s state in a file. Additionally, manipulation of the state of an object as streams of bytes is required. The core of Java Serialization is the Serializable interface. When Serializable interface is implemented by your class it provides an indication to the compiler that java Serialization mechanism needs to be used to serialize the object.
This is one of top serialization questions that is asked in many big companies to test your in-depth understanding of serialization. Serializable is a marker interface therefore you are not forced to implement any methods, however Externalizable contains two methods readExternal() and writeExternal() which must be implemented. Serializable interface provides a inbuilt serialization mechanism to you which can be in-efficient at times. However Externilizable interface is designed to give you greater control over the serialization mechanism. The two methods provide you immense opportunity to enhance the performance of specific object serialization based on applicationneeds. Serializable interface provides a default serialization mechanism, on the other hand, Externalizable interface instead of relying on default Java Serialization provides flexibility to control this mechanism. One can drastically improve the application performance by implementing the Externalizable interface correctly. However there is also a chance that you may not write the best implementation, so if you are not really sure about the best way to serialize, I would suggest your stick to the default implementation using Serializable interface.
Most of the times when you want to do a selective attribute serialization you can use Serializable interface with transient modifier for variables not to be serialized. However, use of Externalizable interface can be really effective in cases when you have to serialize only some dynamically selected attributes of a large object. Lets take an example, Some times when you have a big Java object with hundreds of attributes and you want to serialize only a dozen dynamically selected attributes to keep the state of the object you should use Externalizable interface writeObject method to selectively serialize the chosen attributes. In case you have small objects and you know that most or all attributes are required to be serialized then you should be fine with using Serializable interface and use of transient variable as appropriate.
The default Java Serialization mechanism is really useful, however it can have a really bad performance based on your application and business requirements. The serialization process performance heavily depends on the number and size of attributes you are going to serialize for an object. Below are some tips you can use for speeding up the marshaling and un-marshaling of objects during Java serialization process.
- Mark the unwanted or non Serializable attributes as transient. This is a straight forward benefit since your attributes for serialization are clearly marked and can be easily achieved using Serialzable interface itself.
- Save only the state of the object, not the derived attributes. Some times we keep the derived attributes as part of the object however serializing them can be costly. Therefore consider calcualting them during de-serialization process.
- Serialize attributes only with NON-default values. For examples, serializing a int variable with value zero is just going to take extra space however, choosing not to serialize it would save you a lot of performance. This approach can avoid some types of attributes taking unwanted space. This will require use of Externalizable interface since attribute serialization is determined at runtime based on the value of each attribute.
- Use Externalizable interface and implement the readObject and writeObject methods to dynamically identify the attributes to be serialized. Some times there can be a custom logic used for serialization of various attributes.
The serialVersionUID represents your class version, and you should change it if the current version of your class is not backwards compatible with its earlier versions. This is extract from Java API Documentation
The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.
Most of the times, we probably do not use serialization directly. In such cases, I would suggest to generate a default serializable uid by clicking the quick fix option in eclipse.
If you don't define serialVersionUID in your serilizable class, Java compiler will make one by creating a hash code using most of your class attributes and features. When an object gets serialized, this hash code is stamped on the object which is known as the SerialVersionUID of that object. This ID is required for the version control of an object. SerialVersionUID can be specified in the class file also. In case, this ID is not specified by you, then Java compiler will regenerate a SerialVersionUID based on updated class and it will not be possible for the already serialized class to recover when a class field is added or modified. Its recommended that you always declare a serialVersionUID in your Serializable classes.
Declaring an explicit serialVersionUID field in your classes saves some CPU time only the first time the JVM process serializes a given Class. However the gain is not significant, In case when you have not declared the serialVersionUID its value is computed by JVM once and subsequently kept in a soft cache for future use.
9. What are the alternatives to Serialization? If Serialization is not used, is it possible to persist or transfer an object using any other approach?
In case, Serialization is not used, Java objects can be serialized by many ways, some of the popular methods are listed below:
- Saving object state to database, this is most common technique used by most applications. You can use ORM tools (e.g. hibernate) to save the objects in a database and read them from the database.
- Xml based data transfer is another popular mechanism, and a lot of XML based web services use this mechanism to transfer data over network. Also a lot of tools save XML files to persist data/configurations.
- JSON Data Transfer - is recently popular data transfer format. A lot of web services are being developed in JSON due to its small footprint and inherent integration with web browser due to JavaScript format.
The transient keyword in Java is used to indicate that a field should not be serialized. Once the process of de-serialization is carried out, the transient variables do not undergo a change and retain their default value. Marking unwanted fields as transient can help you boost the serialization performance. Below is a simple example where you can see the use of transient keyword.
1. class MyVideo implements Serializable
2. {
3. private Video video;
4. private transient Image thumbnailVideo;
5.
6. private void generateThumbnail()
7. {
8. // Generate thumbnail.
9. }
10.
11. private void readObject(ObjectInputStream inputStream)
12. throws IOException, ClassNotFoundException
13. {
14. inputStream.defaultReadObject();
15. generateThumbnail();
16. }
17.}
Why does serialization NOT save the value of static class attributes? Why static variables are not serialized?
The Java variables declared as static are not considered part of the state of an object since they are shared by all instances of that class. Saving static variables with each serialized object would have following problems
o It will make redundant copy of same variable in multiple objects which makes it in-efficient.
o The static variable can be modified by any object and a serialized copy would be stale or not in sync with current value.
How to Serialize a collection in java? How to serialize a ArrayList, Hashmap or Hashset object in Java?
All standard implementations of collections List, Set and Map interface already implement java.io.Serializable. All the commonly used collection classes like java.util.ArrayList, java.util.Vector, java.util.Hashmap, java.util.Hashtable, java.util.HashSet, java.util.TreeSet do implement Serializable. This means you do not really need to write anything specific to serialize collection objects. However you should keep following things in mind before you serialize a collection object - Make sure all the objects added in collection are Serializable. - Serializing the collection can be costly therefore make sure you serialize only required data isntead of serializing the whole collection. - In case you are using a custom implementation of Collection interface then you may need to implement serialization for it.
Is it possible to customize the serialization process? How can we customize the Serialization process?
Yes, the serialization process can be customized. When an object is serialized, objectOutputStream.writeObject (to save this object) is invoked and when an object is read, ObjectInputStream.readObject () is invoked. What most people do not know is that Java Virtual Machine provides you with an option to define these methods as per your needs. Once this is done, these two methods will be invoked by the JVM instead of the application of the default serialization process. Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:
0. private void writeObject(java.io.ObjectOutputStream out)
1. throws IOException
2. private void readObject(java.io.ObjectInputStream in)
3. throws IOException, ClassNotFoundException;
4. private void readObjectNoData()
5. throws ObjectStreamException;
How can a sub-class of Serializable super class avoid serialization? If serializable interface is implemented by the super class of a class, how can the serialization of the class be avoided?
In Java, if the super class of a class is implementing Serializable interface, it means that it is already serializable. Since, an interface cannot be unimplemented, it is not possible to make a class non-serializable. However, the serialization of a new class can be avoided. For this, writeObject () and readObject() methods should be implemented in your class so that a Not Serializable Exception can be thrown by these methods. And, this can be done by customizing the Java Serialization process. Below the code that demonstrates it
0. class MySubClass extends SomeSerializableSuperClass {
1. private void writeObject(java.io.ObjectOutputStream out)
2. throws IOException {
3. throw new NotSerializableException(“Can not serialize this class”);
4. }
5. private void readObject(java.io.ObjectInputStream in)
6. throws IOException, ClassNotFoundException {
7. throw new NotSerializableException(“Can not serialize this class”);
8. }
9. private void readObjectNoData()
10. throws ObjectStreamException; {
11. throw new NotSerializableException(“Can not serialize this class”);
12.}
13.}
This is one of a difficult tricky questions and answering this correctly would mean you are an expert in Java Serialization concept.
In an already serialized object, the most challenging task is to change the structure of a class when a new field is added or removed. As per the specifications of Java Serialization, addition of any method or field is considered to be a compatible change whereas changing of class hierarchy or non-implementation of Serializable interface is considered to be a non-compatible change. You can go through the Java serialization specification for the extensive list of compatible and non-compatible changes. If a serialized object need to be compatible with an older version, it is necessary that the newer version follows some rules for compatible and incompatible changes. A compatible change to the implementing class is one that can be applied to a new version of the class, which still keeps the object stream compatible with older version of same class. Some Simple Examples of compatible changes are:
In an already serialized object, the most challenging task is to change the structure of a class when a new field is added or removed. As per the specifications of Java Serialization, addition of any method or field is considered to be a compatible change whereas changing of class hierarchy or non-implementation of Serializable interface is considered to be a non-compatible change. You can go through the Java serialization specification for the extensive list of compatible and non-compatible changes. If a serialized object need to be compatible with an older version, it is necessary that the newer version follows some rules for compatible and incompatible changes. A compatible change to the implementing class is one that can be applied to a new version of the class, which still keeps the object stream compatible with older version of same class. Some Simple Examples of compatible changes are:
o Addition of a new field or class will not affect serialization, since any new data in the stream is simply ignored by older versions. the newly added field will be set to its default values when the object of an older version of the class is un marshaled.
o The access modifiers change (like private, public, protected or default) is compatible since they are not reflected in the serialized object stream.
o Changing a transient field to a non-transient field is compatible change since it is similar to adding a field.
o Changing a static field to a non-static field is compatible change since it is also similar to adding a field.
Some Simple Examples of incompatible changes are:
o Changing implementation from Serializable to Externalizable interface can not be done since this will result in the creation of an incompatible object stream.
o Deleting a existing Serializable fields will cause a problem.
o Changing a non-transient field to a transient field is incompatible change since it is similar to deleting a field.
o Changing a non-static field to a static field is incompatible change since it is also similar to deleting a field.
o Changing the type of a attribute within a class would be incompatible, since this would cause a failure when attempting to read and convert the original field into the new field.
o Changing the package of class is incompatible. Since the fully-qualified class name is written as part of the object byte stream.
Java serialization is one of the most commonly misunderstood areas. Many developers still think its only used for saving objects on the file system.
JSP Interview Questions
1.What are the advantages of JSP over Servlet?
JSP is a serverside technology to make content generation a simple appear.The advantage of JSP is that they are document-centric. Servlets, on the other hand, look and act like programs. A Java Server Page can contain Java program fragments that instantiate and execute Java classes, but these occur inside an HTML template file and are primarily used to generate dynamic content. Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development.
2.What is the life-cycle of JSP?
When a request is mapped to a JSP page for the first time, it translates the JSP page into a servlet class and compiles the class. It is this servlet that services the client requests.
A JSP page has seven phases in its lifecycle, as listed below in the sequence of occurrence:
A JSP page has seven phases in its lifecycle, as listed below in the sequence of occurrence:
- Translation
- Compilation
- Loading the class
- Instantiating the class
- jspInit() invocation
- _jspService() invocation
- jspDestroy() invocation
3.What is the jspInit() method?
The jspInit() method of the javax.servlet.jsp.JspPage interface is similar to the init() method of servlets. This method is invoked by the container only once when a JSP page is initialized. It can be overridden by a page author to initialize resources such as database and network connections, and to allow a JSP page to read persistent configuration data.
4.What is the _jspService() method?
SThe _jspService() method of the javax.servlet.jsp.HttpJspPage interface is invoked every time a new request comes to a JSP page. This method takes the HttpServletRequest and HttpServletResponse objects as its arguments. A page author cannot override this method, as its implementation is provided by the container.
5.What is the jspDestroy() method?
The jspDestroy() method of the javax.servlet.jsp.JspPage interface is invoked by the container when a JSP page is about to be destroyed. This method is similar to the destroy() method of servlets. It can be overridden by a page author to perform any cleanup operation such as closing a database connection.
6.What JSP lifecycle methods can I override?
You cannot override the _jspService() method within a JSP page. You can however, override the jspInit() and jspDestroy() methods within a JSP page. jspInit() can be useful for allocating resources like database connections, network connections, and so forth for the JSP page. It is good programming practice to free any allocated resources within jspDestroy().
7.How can I override the jspInit() and jspDestroy() methods within a JSP page?
The jspInit() and jspDestroy() methods are each executed just once during the lifecycle of a JSP page and are typically declared as JSP declarations:
<%!
public void jspInit() {
. . .
}
%>
<%!
public void jspDestroy() {
. . .
}
%>
8.What are implicit objects in JSP?
Implicit objects in JSP are the Java objects that the JSP Container makes available to developers in each page. These objects need not be declared or instantiated by the JSP author. They are automatically instantiated by the container and are accessed using standard variables; hence, they are called implicit objects.The implicit objects available in JSP are as follows:
- request
- response
- pageContext
- session
- application
- out
- config
- page
- exception
The implicit objects are parsed by the container and inserted into the generated servlet code. They are available only within the jspService method and not in any declaration.
9.What are the different types of JSP tags?
The different types of JSP tags are as follows:
10.What are JSP directives?
- JSP directives are messages for the JSP engine. i.e., JSP directives serve as a message from a JSP page to the JSP container and control the processing of the entire page
- They are used to set global values such as a class declaration, method implementation, output content type, etc.
- They do not produce any output to the client.
- Directives are always enclosed within <%@ ….. %> tag.
- Ex: page directive, include directive, etc.
11.What is page directive?
- A page directive is to inform the JSP engine about the headers or facilities that page should get from the environment.
- Typically, the page directive is found at the top of almost all of our JSP pages.
- There can be any number of page directives within a JSP page (although the attribute – value pair must be unique).
- The syntax of the include directive is: <%@ page attribute="value">
- Example:<%@ include file="header.jsp" %>
12.What are the attributes of page directive?
There are thirteen attributes defined for a page directive of which the important attributes are as follows:
- import: It specifies the packages that are to be imported.
- session: It specifies whether a session data is available to the JSP page.
- contentType: It allows a user to set the content-type for a page.
- isELIgnored: It specifies whether the EL expressions are ignored when a JSP is translated to a servlet.
13.What is the include directive?
There are thirteen attributes defined for a page directive of which the important attributes are as follows:
- The include directive is used to statically insert the contents of a resource into the current JSP.
- This enables a user to reuse the code without duplicating it, and includes the contents of the specified file at the translation time.
- The syntax of the include directive is as follows:
<%@ include file = "FileName" %> - This directive has only one attribute called file that specifies the name of the file to be included.
14.What are the JSP standard actions?
- The JSP standard actions affect the overall runtime behavior of a JSP page and also the response sent back to the client.
- They can be used to include a file at the request time, to find or instantiate a JavaBean, to forward a request to a new page, to generate a browser-specific code, etc.
- Ex: include, forward, useBean,etc. object
15.What are the standard actions available in JSP?
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.
16.What is the <jsp:useBean> standard action?
The <jsp:useBean> standard action is used to locate an existing JavaBean or to create a JavaBean if it does not exist. It has attributes to identify the object instance, to specify the lifetime of the bean, and to specify the fully qualified classpath and type.
17.What are the scopes available in <jsp:useBean>?
The scopes available in <jsp:useBean> are as follows:
- page scope:: It specifies that the object will be available for the entire JSP page but not outside the page.
- request scope: It specifies that the object will be associated with a particular request and exist as long as the request exists.
- application scope: It specifies that the object will be available throughout the entire Web application but not outside the application.
- session scope: It specifies that the object will be available throughout the session with a particular client.
18.What is the <jsp:forward> standard action?
- The <jsp:forward> standard action forwards a response from a servlet or a JSP page to another page.
- The execution of the current page is stopped and control is transferred to the forwarded page.
- The syntax of the <jsp:forward> standard action is :
<jsp:forward page="/targetPage" />
Here, targetPage can be a JSP page, an HTML page, or a servlet within the same context.
- If anything is written to the output stream that is not buffered before <jsp:forward>, an IllegalStateException will be thrown.
Note : Whenever we intend to use <jsp:forward> or <jsp:include> in a page, buffering should be enabled. By default buffer is enabled.
19.What is the <jsp:include> standard action?
The <jsp:include> standard action enables the current JSP page to include a static or a dynamic resource at runtime. In contrast to the include directive, the include action is used for resources that change frequently. The resource to be included must be in the same context.The syntax of the <jsp:include> standard action is as follows:
<jsp:include page="targetPage" flush="true"/>
Here, targetPage is the page to be included in the current JSP.
<jsp:include page="targetPage" flush="true"/>
Here, targetPage is the page to be included in the current JSP.
20.What is the difference between include directive and include action?
Include directive | Include action |
The include directive, includes the content of the specified file during the translation phase–when the page is converted to a servlet. | The include action, includes the response generated by executing the specified page (a JSP page or a servlet) during the request processing phase–when the page is requested by a user. |
The include directive is used to statically insert the contents of a resource into the current JSP. | The include standard action enables the current JSP page to include a static or a dynamic resource at runtime. |
Use the include directive if the file changes rarely. It’s the fastest mechanism. | Use the include action only for content that changes often, and if which page to include cannot be decided until the main page is requested. |
21.Differentiate between pageContext.include and jsp:include?
The <jsp:include> standard action and the pageContext.include() method are both used to include resources at runtime. However, the pageContext.include() method always flushes the output of the current page before including the other components, whereas <jsp:include> flushes the output of the current page only if the value of flush is explicitly set to true as follows:
<jsp:include page="/index.jsp" flush="true"/>
22.What is the jsp:setProperty action?
You use jsp:setProperty to give values to properties of beans that have been referenced earlier. You can do this in two contexts. First, you can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:
<jsp:useBean id="myName" ... />
...
<jsp:setProperty name="myName" property="myProperty" ... />
In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated or an existing bean was found.
A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as below:
A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean element, as below:
<jsp:useBean id="myName" ... >
...
<jsp:setProperty name="myName"
property="someProperty" ... />
</jsp:useBean>
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing one was found.
23.What is the jsp:getProperty action?
The <jsp:getProperty> action is used to access the properties of a bean that was set using the <jsp:getProperty> action. The container converts the property to a String as follows:
- If it is an object, it uses the toString() method to convert it to a String.
- If it is a primitive, it converts it directly to a String using the valueOf() method of the corresponding Wrapper class.
- The syntax of the <jsp:getProperty> method is: <jsp:getProperty name="Name" property="Property" />
Here, name is the id of the bean from which the property was set. The property attribute is the property to get. A user must create or locate a bean using the <jsp:useBean> action before using the <jsp:getProperty> action.
24.What is the <jsp:param> standard action?
The <jsp:param> standard action is used with <jsp:include> or <jsp:forward> to pass parameter names and values to the target resource. The syntax of the <jsp:param> standard action is as follows:
<jsp:param name="paramName" value="paramValue"/>
<jsp:param name="paramName" value="paramValue"/>
25.What is the jsp:plugin action ?
This action lets you insert the browser-specific OBJECT or EMBED element needed to specify that the browser run an applet using the Java plugin.
26.What are scripting elements?
JSP scripting elements let you insert Java code into the servlet that will be generated from the current JSP page. There are three forms:
- Expressions of the form <%= expression %> that are evaluated and inserted into the output,
- Scriptlets of the form <% code %> that are inserted into the servlet's service method,
- Declarations of the form <%! code %> that are inserted into the body of the servlet class, outside of any existing methods.
27.What is a scriptlet?
A scriptlet contains Java code that is executed every time a JSP is invoked. When a JSP is translated to a servlet, the scriptlet code goes into the service() method. Hence, methods and variables written in scriptlets are local to the service() method. A scriptlet is written between the <% and %> tags and is executed by the container at request processing time.
28.What are JSP declarations?
As the name implies, JSP declarations are used to declare class variables and methods in a JSP page. They are initialized when the class is initialized. Anything defined in a declaration is available for the whole JSP page. A declaration block is enclosed between the <%! and %> tags. A declaration is not included in the service() method when a JSP is translated to a servlet.
29.What is a JSP expression?
A JSP expression is used to write an output without using the out.print statement. It can be said as a shorthand representation for scriptlets. An expression is written between the <%= and %> tags. It is not required to end the expression with a semicolon, as it implicitly adds a semicolon to all the expressions within the expression tags.
30.How is scripting disabled?
Scripting is disabled by setting the scripting-invalid element of the deployment descriptor to true. It is a subelement of jsp-property-group. Its valid values are true and false. The syntax for disabling scripting is as follows:
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<scripting-invalid>true</scripting-invalid>
</jsp-property-group>
Servlets Interview Questions
1.What is the Servlet?
A servlet is a Java programming language class that is used to extend the capabilities of servers that hostapplications accessed by means of a request- response programming model.
2.What are the new features added to Servlet 2.5?
Following are the changes introduced in Servlet 2.5:
- A new dependency on J2SE 5.0
- Support for annotations
- Loading the class
- Several web.xml conveniences
- A handful of removed restrictions
- Some edge case clarifications
Learn more about Servlets 2.5 features |
3.What are the uses of Servlet?
Typical uses for HTTP Servlets include:
- Processing and/or storing data submitted by an HTML form.
- Providing dynamic content, e.g. returning the results of a database query to the client.
- A Servlet can handle multiple request concurrently and be used to develop high performance system
- Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.
4.What are the advantages of Servlet over CGI?
Servlets have several advantages over CGI:
- A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request.
- A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request.
- There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
- Several web.xml conveniences
- A handful of removed restrictions
- Some edge case clarifications
5.What are the phases of the servlet life cycle?
The life cycle of a servlet consists of the following phases:
- Servlet class loading : For each servlet defined in the deployment descriptor of the Web application, the servlet container locates and loads a class of the type of the servlet. This can happen when the servlet engine itself is started, or later when a client request is actually delegated to the servlet.
- Servlet instantiation : After loading, it instantiates one or more object instances of the servlet class to service the client requests.
- Initialization (call the init method) : After instantiation, the container initializes a servlet before it is ready to handle client requests. The container initializes the servlet by invoking its init() method, passing an object implementing the ServletConfig interface. In the init() method, the servlet can read configuration parameters from the deployment descriptor or perform any other one-time activities, so the init() method is invoked once and only once by the servlet container.
- Request handling (call the service method) : After the servlet is initialized, the container may keep it ready for handling client requests. When client requests arrive, they are delegated to the servlet through the service() method, passing the request and response objects as parameters. In the case of HTTP requests, the request and response objects are implementations of HttpServletRequest and HttpServletResponse respectively. In the HttpServlet class, the service() method invokes a different handler method for each type of HTTP request, doGet() method for GET requests, doPost() method for POST requests, and so on.
- Removal from service (call the destroy method) : A servlet container may decide to remove a servlet from service for various reasons, such as to conserve memory resources. To do this, the servlet container calls the destroy() method on the servlet. Once the destroy() method has been called, the servlet may not service any more client requests. Now the servlet instance is eligible for garbage collection
The life cycle of a servlet is controlled by the container in which the servlet has been deployed.
6.Why do we need a constructor in a servlet if we use the init method?
Even though there is an init method in a servlet which gets called to initialize it, a constructor is still required to instantiate the servlet. Even though you as the developer would never need to explicitly call the servlet's constructor, it is still being used by the container (the container still uses the constructor to create an instance of the servlet). Just like a normal POJO (plain old java object) that might have an init method, it is no use calling the init method if you haven't constructed an object to call it on yet.
7.How the servlet is loaded?
A servlet can be loaded when:
- First request is made.
- Server starts up (auto-load).
- There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
- Administrator manually loads.
8.How a Servlet is unloaded?
A servlet is unloaded when:
- Server shuts down.
- Administrator manually unloads.
9.What is Servlet interface?
The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or , more commonly by extending a class that implements it.
Note: Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet andjavax.servlet.http.HttpServlet.
10.What is the GenericServlet class?
GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface.
Note: This class is known as generic servlet, since it is not specific to any protocol.
Note: This class is known as generic servlet, since it is not specific to any protocol.
11.What's the difference between GenericServlet and HttpServlet?
GenericServlet | HttpServlet |
The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP protocol-specific methods. | An abstract class that simplifies writing HTTP servlets. It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. |
The GenericServlet does not include protocol-specific methods for handling request parameters, cookies, sessions and setting response headers. | The HttpServlet subclass passes generic service method requests to the relevant doGet() or doPost() method. |
GenericServlet is not specific to any protocol. | HttpServlet only supports HTTP and HTTPS protocol. |
12.Why is HttpServlet declared abstract?
The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. This is a convenience implementation of the Servlet interface, which means that developers do not need to implement all service methods. If your servlet is required to handle doGet() requests for example, there is no need to write a doPost() method too.
13.Can servlet have a constructor ?
One can definitely have constructor in servlet.Even you can use the constrctor in servlet for initialization purpose,but this type of approch is not so common. You can perform common operations with the constructor as you normally do.The only thing is that you cannot call that constructor explicitly by the new keyword as we normally do.In the case of servlet, servlet container is responsible for instantiating the servlet, so the constructor is also called by servlet container only.
14.What are the types of protocols supported by HttpServlet ?
It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.
15.What is the difference between doGet() and doPost()?
# | doGet() | doPost() |
1 | In doGet() the parameters are appended to the URL and sent along with header information. | In doPost(), on the other hand will (typically) send the information through a socket back to the webserver and it won't show up in the URL bar. |
2 | The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters. | You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects! |
3 | doGet() is a request for information; it does not (or should not) change anything on the server. (doGet() should be idempotent) | doPost() provides information (such as placing an order for merchandise) that the server is expected to remember |
4 | Parameters are not encrypted | Parameters are encrypted |
5 | doGet() is faster if we set the response content length since the same connection is used. Thus increasing the performance | doPost() is generally used to update or post some information to the server.doPost is slower compared to doGet since doPost does not write the content length |
6 | doGet() should be idempotent. i.e. doget should be able to be repeated safely many times | This method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable. |
7 | doGet() should be safe without any side effects for which user is held responsible | This method does not need to be either safe |
8 | It allows bookmarks. | It disallows bookmarks. |
Core Java interview questions
1. Can there be an abstract class with no abstract methods in it? - Yes
2. Can an Interface be final? - No
3. Can an Interface have an inner class? - Yes.
public interface abc
{
static int i=0; void dd();
class a1
{
a1()
{
int j;
System.out.println("inside");
};
public static void main(String a1[])
{
System.out.println("in interfia");
}
}
}
4. Can we define private and protected modifiers for variables in interfaces? - No
5. What is Externalizable? - Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)
6. What modifiers are allowed for methods in an Interface? - Only public and abstract modifiers are allowed for methods in interfaces.
7. What is a local, member and a class variable? - Variables declared within a method are “local” variables. Variables declared within the class i.e not within any methods are “member” variables (global variables). Variables declared within the class i.e not within any methods and are defined as “static” are class variables
8. What are the different identifier states of a Thread? - The different identifiers of a Thread are: R - Running or runnable thread, S - Suspended thread, CW - Thread waiting on a condition variable, MW - Thread waiting on a monitor lock, MS - Thread suspended waiting on a monitor lock
9. What are some alternatives to inheritance? - Delegation is an alternative to inheritance. Delegation means that you include an instance of another class as an instance variable, and forward messages to the instance. It is often safer than inheritance because it forces you to think about each message you forward, because the instance is of a known class, rather than a new class, and because it doesn’t force you to accept all the methods of the super class: you can provide only the methods that really make sense. On the other hand, it makes you write more code, and it is harder to re-use (because it is not a subclass).
10. Why isn’t there operator overloading? - Because C++ has proven by example that operator overloading makes code almost impossible to maintain. In fact there very nearly wasn’t even method overloading in Java, but it was thought that this was too useful for some very basic methods like print(). Note that some of the classes like DataOutputStream have unoverloaded methods like writeInt() and writeByte().
11. What does it mean that a method or field is “static”? - Static variables and methods are instantiated only once per class. In other words they are class variables, not instance variables. If you change the value of a static variable in a particular object, the value of that variable changes for all instances of that class. Static methods can be referenced with the name of the class rather than the name of a particular object of the class (though that works too). That’s how library methods like System.out.println() work. out is a static field in the java.lang.System class.
12. How do I convert a numeric IP address like 192.18.97.39 into a hostname like java.sun.com?
13. String hostname = InetAddress.getByName("192.18.97.39").getHostName();
14. Difference between JRE/JVM/JDK?
15. Why do threads block on I/O? - Threads block on i/o (that is enters the waiting state) so that other threads may execute while the I/O operation is performed.
16. What is synchronization and why is it important? - With respect to multithreading, synchronization is the capability to control the access of multiple threads to shared resources. Without synchronization, it is possible for one thread to modify a shared object while another thread is in the process of using or updating that object’s value. This often leads to significant errors.
17. Is null a keyword? - The null value is not a keyword.
18. Which characters may be used as the second character of an identifier,but not as the first character of an identifier? - The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.
19. What modifiers may be used with an inner class that is a member of an outer class? - A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.
20. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters? - Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.
21. What are wrapped classes? - Wrapped classes are classes that allow primitive types to be accessed as objects.
22. What restrictions are placed on the location of a package statement within a source code file? - A package statement must appear as the first line in a source code file (excluding blank lines and comments).
23. What is the difference between preemptive scheduling and time slicing? - Under preemptive scheduling, the highest priority task executes until it enters the waiting or dead states or a higher priority task comes into existence. Under time slicing, a task executes for a predefined slice of time and then reenters the pool of ready tasks. The scheduler then determines which task should execute next, based on priority and other factors.
24. What is a native method? - A native method is a method that is implemented in a language other than Java.
25. What are order of precedence and associativity, and how are they used? - Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left
26. What is the catch or declare rule for method declarations? - If a checked exception may be thrown within the body of a method, the method must either catch the exception or declare it in its throws clause.
27. Can an anonymous class be declared as implementing an interface and extending a class? - An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.
28. What is the range of the char type? - The range of the char type is 0 to 2^16 - 1.
No comments:
Post a Comment