Java - J2EE Interview Preparation

Java-J2EE Interview Preparation
  •  Mutable (Changable) Vs Immutable (Not Changable)? 

Mutable object – You can change the states and fields after the object is created

Sting is im-mutable, Stringbuffer is mutable and Date is mutable.

  • How to create a Mutable class?
To create a mutable class in Java you have to make sure the following requirements are satisfied:
    • Provide a method to modify the field values
    • Getter and Setter method
  • How to create an Immutable class?

A class should be declared as  final  so that it can't be extended.
All the fields should be made private so that direct access is not allowed
No setter methods
Make all mutable fields final, so that they can be assigned only once.
Advantages : Advantages 
immutable objects can safely be shared among multiple threads , increasingly mutable objects must be made thread-safe via careful design and implementation. Strings and HashMaps are best examples. If HashMap is not immutable hashkey for value keeps changing and map will be broken.
    Singleton vs Immutable
An immutable object is initialized by its constructor only, while a singleton is instantiated by a static method.

  • How do you create a singleton class in java? 

  • A singleton class is a class that can have only one object (an instance of the class) at a time.
  • After the first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created.
    • Make constructor as private.
    • Write a static method that has return type object of this singleton class.
class Singleton {
    private static Singleton single_instance = null;
    public String s;
    private Singleton ()
        s = "Hello I am a string part of Singleton class";
    public static Singleton getInstance ()
        if (single_instance == null)
            single_instance = new Singleton ();
        return single_instance;

class Tests {
    // Main driver method
    public static void main (String args [])
        // Instantiating Singleton class with variable x
        Singleton x = Singleton.getInstance ();
        // Instantiating Singleton class with variable y
        Singleton y = Singleton.getInstance ();

  • Map Vs Flat Map?
List<List<String>> lists = Arrays.asList(Arrays.asList("1","2"),Arrays.asList("3"),Arrays.asList("33","44"));
System.out.println("FlatMap" ->; ->;

Stream Vs parllelStream 

The parallel stream by default uses Common ForkJoinPool. commonPool which has one less thread than number of processor.

HashMap - Weak Hashmap - identity HashMap

Java.util.HashMap class is a Hashing based implementation. In HashMap, we have a key and a value pair. 
Even though the object is specified as key in hashmap, it does not have any reference and it is not eligible for garbage collection if it is associated with HashMap i.e. HashMap dominates over Garbage Collector.


WeakHashMap is an implementation of the Map interface. WeakHashMap is almost same as HashMap except in case of WeakHashMap, if object is specified as key doesn’t contain any references- it is eligible for garbage collection even though it is associated with WeakHashMap. i.e Garbage Collector dominates over WeakHashMap.

Map<String, String> ihm = new IdentityHashMap<>();

The IdentityHashMap implements Map interface using Hashtable, using reference-equality in place of object-equality when comparing keys (and values). This class is not a general-purpose Map implementation. While this class implements the Map interface, it intentionally violates Map’s general contract, which mandates the use of the equals() method when comparing objects. This class is used when the user requires the objects to be compared via reference. It belongs to java.util package.

When do we use java inner classes?
It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together . Nesting such "helper classes" makes their package more streamlined.

Use a non-static nested class (or inner class) if you require access to an enclosing instance's non-public fields and methods. Use a static nested class if you don't require this access.
  • Inner classes are used to get functionality that can get an object better than the method.
  • They can be used in the case when a set of multiple operations are required and chances of reusability are good inside the class and they will not be accessed but methods outside The Outer Class.
  • Inner Classes Are Made To Achieve Multiple Inheritances Also.
  • Inner Classes Are Used When They Are Useful In The Class Context.
  • They Are Used To Separate Logic Inside Classes.
  • Inner Class Means One Class That Is A Member Of Another Class. There are basically four types of inner classes in java.

1) Nested Inner class

2) Method Local inner classes

3) Anonymous inner classes

4) Static nested classes

 Method overloading means having two or more methods with the same name but different signatures in the same scope. These two methods may exist in the same class or another one in base class and another in derived class.Generally, you should consider overloading a method when You Have Required Same Reason That Take Different Signatures, But Conceptually Do The Same Thing.
These two methods would have the same signature, but different implementation. One of these would. Method overriding means having a different implementation of the same method in the inherited class. These cannot exist in the same class.
Overriding methods
Overriding method definitionsIn a derived class, if you include a method definition that has the same name and exactly the same number and types of parameters as a method already defined in the base class, this new definition replaces the old definition of the method.
A subclass inherits methods from a superclass. Sometimes, it is necessary for the subclass to modify the methods defined in the superclass. This is referred to as method overriding. The following example demonstrates method overriding.
  • Constructor
  •      It will invoke when an object is instantiated.
  •      Will have same name as class name.
  •      This will not have any return type. Not even void.
  •       It will be called only once when an object is created.
  •       It cannot be override.
  •       It can be overload.
  • Interface Vs Abstract class
Please refer this link on this topic: 
  • Final 
    •  Members, Variables are final means Constant
    •  Method is final means cant override
    • Class is final means cant inherit ie cant extend
  • Finally
    • The code which needs to executed before even if any exception occurs or not.
  • Finalize
    • If any resource needs to be freeze before the object gets destroyed we can use finalize Garbage collector internally call finalize.
  • Inheritance
    • Taking the properties of another class
  • Encapsulation
    • Wrapping the member and method with the use of access specifiers to prevent from the outside use
  • Exceptions:  T hrowable >>
    • Error (checked exception) compile time exception no such Method, class not found exception
    • Exception (unchecked exception) runtime exception Index out of bounce, Null pointer exception
  • Try: Try:
    • Nested try is allowed try can have either catch or finally
    • Exception should be on top and IOException subclass should be in down that the order
    • try {} catch (IOException) {} catch (Exception)
  • Catch: Catches the exception and handle it.
  • Finally: It will execute the code no matter whether the exception is catches or not .
  • Throw: To manually throw an exception
  • Throws: Any exception that will throws by an system built-in exception .
  • Threads : Running multiple process in a sequence .
    • Threads shares same heap memory but different stack memory
    • Two ways of creating threads: Extends thread and Implements Runnable Interface
    • What are the different states of a thread's life-cycle? Ans) The different states of threads are as follows:
      1) New – When a thread is instantiated it is in New state until the start () method is called on the thread instance. In this state the thread is not considered to be alive.
      2) Runnable – The thread enters into this state after the start method is called in the thread instance. The thread may enter into the Runnable state from Running state. In this state the thread is considered to be alive.
      3) Running - When The Thread Scheduler Picks Up The Thread From The Runnable Thread'S Pool, The Thread Starts Running And The Thread Is Said To Be In Running State.
      4) Waiting / Blocked / Sleeping – In these states the thread is said to be alive but not runnable. The thread switches to this state because of reasons like wait method called or sleep method has been called on the running thread or thread might be waiting for some i / o resource so blocked.
      5) Dead – When the thread finishes its execution ie the run () method execution completes, it is said to be in dead state. A dead state can not be started again. If a start ( ) method is invoked on a dead thread a run-time exception will occur.
    • Sleep Vs Wait?
      1) wait is called from synchronized context only while sleep can be called without synchronized block.
      2) wait is called on Object while sleep is called on Thread.
      3) waiting thread can be awake by calling notify and notifyAll while sleeping thread can not be awaken by calling notify method.
      4) wait is normally done on condition, Thread wait until a condition is true while sleep is just to put your thread on sleep.
      5) wait release lock on object while waiting while sleep doesn' t release lock while waiting.
      6) The notifyAll () method must be called from a synchronized context.
    • What is garbage collection? What is the process that is responsible for doing that in java?
      Ans: Reclaiming the unused memory by the invalid objects. Garbage collector is responsible for this process.
    •  What kind of thread is the Garbage collector thread?
      Ans. It is a daemon thread.
    • What is a daemon thread?
      Ans: These are the threads which can run without user intervention. The JVM can exit when there are daemon threads by killing them abruptly.
  • Synchronization: It is the process of making only one thread to access the resource at a time by using synchronized (this).
    • we can use synchronize block also to avoid the deadlock condition
  • String Vs StringBuffer: Read more about this here :
  • Static class loading: Class will be loaded statically with new operator
  • Dynamic class loading: Class.forName (); string class name
  • Connection pool:
    • It's a technique to allow multiple clinets to make use of a cached set of shared and reusable connection objects providing access to a database.
    • Opening / Closing database connections is an expensive process and hence connection pools improve the performance of execution of commands on a database for which we maintain connection objects in the pool.
    • It facilitates reuse of the same connection object to serve a number of client requests.
    • Every time a client request is received, the pool is searched for an available connection object and it's highly likely that it gets a free connection object.
    • It's normally used in a web-based enterprise application where the application server handles the responsibilities of creating connection objects, adding them to the pool, assigning them to the incoming requests, taking the used connection objects back, returning them back to the pool, etc. ..
  • Wrapperclass: As the name says, a wrapper class wraps (encloses) around a data type and gives it an object appearance. Wherever, the data type is required as an object, this object can be used. Wrapper classes include methods to unwrap the object And give back the data type. It can be compared with a chocolate. The manufacturer wraps the chocolate with some foil or paper to prevent from pollution. The user takes the chocolate, removes and throws the wrapper and eats it.
    • Example: Example:
    • int k = 100;
    • Integer it1 = new Integer (k);
    • The int data type k is converted into an object, it1 using Integer class. The it1 object can be used in Java programming wherever k is required an object.
  • Session tracking:
    • By using URL Rewriting
    • Using session object
    • Using cookies
    • Using hidden fields
  • Collections : Read this article for more information on collecitons

  • Sorting list in collection --using sort method: refere this article for more information:
  • JSP Scripting elements:
    • JSP scripting elements enable you insert Java code into the servlet that will be generated from the current JSP page.
      • There are three forms:
        •     Expressions of the form <% = Java_expression%> that are evaluated and inserted into output, Example: Your hostname: <% = request.getRemoteHost ()%>
        •     Scriptlets of the form <% java_code%> that are inserted into the servlets service method, and Example: <%
          String name = request.getParameter ("name");
          out.println ("name:" + name);
        •     Declarations of the form <%! Java_code%> that are inserted into the body of the servlet class, outside of any existing methods. Example: <%!
          public int getValue () {
              return 78;
  • Difference between JSP & Servlet: Servlet is html in java, JSP is java in html. JSP is a webpage scripting language that can generate dynamic content while Servlets are Java programs that are already compiled which also creates dynamic web content.In MVC, jsp act as a view and servlet act as a controller.
  • What is the servlet lifecycle?

    Instantiation and initialization
    The servlet engine creates an instance of the servlet. The servlet engine creates the servlet configuration object and uses it to pass the servlet initialization parameters to the init () method. The initialization parameters persist until The servlet is destroyed and are applied to all invocations of that servlet.
    Servicing requests
    The servlet engine creates a request object and a response object. The servlet engine invokes the servlet service () method, passing the request and response objects.
    The service () method gets information about the request from the request object, processes the request, and uses methods of the response object to create the client response. The service method can invoke other methods to process the request, such as doGet (), doPost (), or methods you write.
    Termination After a servlet's destroy () method is invoked, the servlet engine unloads the servlet, and the Java virtual machine eventually performs garbage collection on the memory resources associated with the servlet.
    The servlet engine stops a servlet by invoking the servlet's destroy () method. Typically, a servlet's destroy () method is invoked when the servlet engine is stopping a Web application which contains the servlet. The destroy () method runs only one time during the lifetime of the servlet and signals the end of the servlet.

  • Design patterns: Refer this link for more information on designpatterns:
  • Webservices:
    • Web services are Web based applications that use open, XML-based standards and transport protocols to exchange data with clients. Web services are developed using Java Technology APIs Web services are Web based applications that use open, XML-based standards and transport protocols to exchange data. with clients. Web services are developed using Java Technology APIs.
    • Web services are client and server applications that communicate over the World Wide Web's (WWW) HyperText Transfer Protocol (HTTP). As described by the World Wide Web Consortium (W3C), web services provide a standard means of interoperating between software applications running on a web services are characterized by their great interoperability and extensibility, as well as their machine-processable descriptions, thanks to the use of XML.
  • Simple Webservice code for online Webservice Stock Quote 
  • Hibernate:
    • Hibernate is an object-relational mapping (ORM) library for the Java language, providing a framework for mapping an object-oriented domain model to a traditional relational database. Hibernate solves object-relational impedance mismatch problems by replacing direct persistence-related database accesses with high-level object handling functions.
    • Hibernate's primary feature is mapping from Java classes to database tables (and from Java data types to SQL data types). Hibernate also provides data query and retrieval facilities. It generates SQL calls and relieves the developer from manual result set handling and object conversion. Applications using Hibernate are portable to supported SQL databases with little performance overhead
    • If you are designing the database schema and your domain objects afresh.
    • You envision that your domain objects and your schema will be in sync, for example an automobile vendor application where your vehicle objects are likely to be close to your table structures. Just an example.
    • You really want to use an ORM and tie your objects closely to schema.
    • Want to use a ORM framework to handle connections etc.
  • Struts:
    • Apache Struts is a web page development framework and an open source software that helps developers build web applications quickly and easily. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework.
    • Struts is based on famous MVC design pattern. The role played by Structs is controller in Model / View / Controller (MVC) style. The View is played by JSP and Model is played by JDBC or generic data source classes. set of programmable components that allow developers to define exactly how the application interacts with the user.
    • core classes of Struts: Action, ActionForm, ActionServlet, ActionMapping, ActionForward are basic classes of Struts.
    • configuration files used in Struts:, struts-config.xml .These two files are used to bridge the gap between the Controller and the Model.

  • J DBC: Http://Www.Krishnababug.Com/2014/02/jdbc-java-interview-questions.Html
  • SQL Injection :
  • xcfd
 References: [ 1 ] [ 2 ] [ 3 ] [ 4 ]

    0 comments to "Java - J2EE Interview Preparation"

    Post a Comment

    Whoever writes Inappropriate/Vulgar comments to context, generally want to be anonymous …So I hope U r not the one like that?
    For lazy logs, u can at least use Name/URL option which doesn’t even require any sign-in, The good thing is that it can accept your lovely nick name also and the URL is not mandatory too.
    Thanks for your patience
    ~Krishna(I love "Transparency")

    Popular Posts

    Enter your email address:

    Buffs ...


    Powered by WidgetsForFree