Saturday, September 20, 2014

IMP Questions and answer in Heap and Stack Memory area in Java

Question - Stack Vs Heap Memory

Answer - Main difference between heap and stack is that stack memory is used to store local variables and function call, while heap memory is used to store objects in Java. No matter, where object is created in code e.g. as member variable, local variable or class variable, they are always created inside heap space in Java.

In a multi-threaded application, each thread will have its own stack, but, all the different threads will share the heap. Because the different threads share the heap in a multi-threaded application, this also means that there has to be some coordination between the threads so that they don’t try to access and manipulate the same piece(s) of memory in the heap at the same time.

Question - Can an object be stored on the stack instead of the heap?

Answer -  Yes, an object can be stored on the stack. If you create an object inside a function without 
using the “new” operator then this will create and store the object on the stack, and not on the heap. 

Servlet


Life-cycle of Servlet : 


Steps in 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.

Wednesday, September 3, 2014

Java Interview Questions for Experience and Freshers

                                                         General Interview Questions


Que 1 - Difference between == and equals method ?

Ans : The == operator compares two objects to determine if they are the same object in memory i.e. present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.

== compares references while .equals compares contents.

 public class EqualsTest {

                    public static void main(String[] args) {

                                         String s1 = ?abc?;
                                         String s2 = s1;
                                         String s5 = ?abc?;
                                         String s3 = new String(?abc?);
                                         String s4 = new String(?abc?);
                                         System.out.println(?== comparison : ? + (s1 == s5));
                                         System.out.println(?== comparison : ? + (s1 == s2));
                                         System.out.println(?Using equals method : ? + s1.equals(s2));
                                         System.out.println(?== comparison : ? + s3 == s4);
                                         System.out.println(?Using equals method : ? + s3.equals(s4));
                    }
}
Output
== comparison : true
== comparison : true
Using equals method : true
false
Using equals method : true
Que 2 - What is the difference between an Abstract class and Interface ?
Ans :
1.       Abstract classes may have some executable methods and methods left unimplemented. Interfaces contain no implementation code.
2.       An class can implement any number of interfaces, but subclass at most one abstract class.
3.       An abstract class can have non abstract methods. All methods of an interface are abstract.
4.       An abstract class can have instance variables. An interface cannot.
5.       An abstract class can define constructor. An interface cannot.
6.       An abstract class can have any visibility: public, protected, private or none (package). An interface's visibility must be public or none (package).
7.       An abstract class inherits from Object and includes methods such as clone() and equals().


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.
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.
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.
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. privatemethods 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.
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.
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.
Que - Difference between Class.forName() and ClassLoader.loadClass() ?
Both methods try to dynamically locate and load a java.lang.Class object corresponding to a given class name. However, their behavior differs regarding which java.lang.ClassLoader they use for class loading and whether or not the resulting Class object is initialized.
The most common form of Class.forName(), the one that takes a single String parameter, always uses the caller's classloader. This is the classloader that loads the code executing the forName() method. By comparison, ClassLoader.loadClass() is an instance method and requires you to select a particular classloader, which may or may not be the loader that loads that calling code. If picking a specific loader to load the class is important to your design, you should use ClassLoader.loadClass() or the three-parameter version of forName() added in Java 2 Platform, Standard Edition (J2SE): Class.forName(String, boolean, ClassLoader).
Additionally, Class.forName()'s common form initializes the loaded class. The visible effect of this is the execution of the class's static initializers as well as byte code corresponding to initialization expressions of all static fields (this process occurs recursively for all the class's superclasses). This differs from ClassLoader.loadClass() behavior, which delays initialization until the class is used for the first time.
You can take advantage of the above behavioral differences. For example, if you are about to load a class you know has a very costly static initializer, you may choose to go ahead and load it to ensure it is found in the classpath but delay its initialization until the first time you need to make use of a field or method from this particular class.
The three-parameter method Class.forName(String, boolean, ClassLoader) is the most general of them all. You can delay initialization by setting the second parameter to false and pick a given classloader using the third parameter. I recommend always using this method for maximum flexibility.

Tuesday, September 2, 2014


Java Collections

The Java Collections API's provide Java developers with a set of classes and interfaces that
 makes it easier to handle collections of objects. In a sense Collection's works a bit like arrays, 
except their size can change dynamically, and they have more advanced behavior 
than arrays.
    Map
     |
 SortedMap
Guide to Selecting Appropriate Map/Collection in Java 
What is the difference between Enumeration and Iterator? 
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.
Difference between HashMap and HashTable? Can we make hashmap synchronized? 

1. 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).
2. HashMap does not guarantee that the order of the map will remain constant over time.
3. HashMap is non synchronized whereas Hashtable is synchronized.
4. Iterator in the HashMap is fail-safe while the enumerator for the Hashtable isn't.

Note on Some Important Terms 
1)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.

2)Fail-safe 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.

HashMap can be synchronized by 
Map m = Collections.synchronizeMap(hashMap);

Implementations

This table is a good summary of commonly used collection implementation classes.
General-purpose Implementations:
InterfacesImplementations
Hash tableResizable arrayTreeLinked listHash table + Linked list
SetHashSetTreeSetLinkedHashSet
ListArrayListLinkedList
Queue
MapHashMapTreeMapLinkedHashMap
Collection Resources -
http://bighai.com/ppjava/?p=158 
http://www.interview-questions-java.com/java-collections.htm 
http://www.javafaq.nu/java-article991.html