Wednesday, 3 December 2014

Java interview questions and answers


Maven
==========
Maven is a high-level, intelligent project management, build and deployment tool provided by Apache?s software foundation group.
Maven deals with application development lifecycle management. Maven was originally developed to manage and to minimize the complexities of building the Jakarta Turbine project.

Spring Aspect Oriented Programming
=========================================
Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects. Put it simple, it’s just an interceptor to intercept some processes, for example, when a method is execute, Spring AOP can hijack the executing method, and add extra functionality before or after the method execution.

In Spring AOP, 4 type of advices are supported :

Before advice – Run before the method execution
After returning advice – Run after the method returns a result
After throwing advice – Run after the method throws an exception
Around advice – Run around the method execution, combine all three advices above.

Add extra functionalities to a existing function. Method (Concern). Extrafunctionality(Crosscutting Concern)

Class
======
Class is a prototype(rule) or a blueprint which defines states behaviour for the object of the class.

Singleton Pattern
==================
It disallows to create more than one object in a class. This is useful when exactly one object is needed to coordinate actions across the system. In the same time it provides a global point of access to that instance.

OOPs

The four main concepts are involved in OOP:
  1. Abstraction
  2. Encapsulation
  3. Inheritance
  4. Polymorphism
Abstraction is hiding of information from others. In case of Java, its hiding implementation of a method/ object. For example if an interface is available to outer world, so end user won’t know about implementing class details. This is just a kind of abstraction. Abstraction could be anywhere in java, wherever we hide some information, we call it abstraction.
Encapsulation is combining data and method along with implementation hiding within the class. Implementation hiding is done with the help of access modifiers (public, protected, package, private).
Inheritance is the capability of a class to use the properties and methods of another class while adding its own functionality. Although inheritance may sometimes imply (especially in Java, where the keyword for inheritance is extends) that you are going to add new methods to the interface, that’s not necessarily true. The second and more important way to differentiate your new class is to change the behavior of an existing base-class method. This is referred to as overriding that method.
Polymorphism is something like one name many forms. Polymorphism is also known as dynamic binding or late binding or run-time binding.
---------------------------------------------------------------------------------------------------------------------------
Inheritance?

Definition 1:
Java Inheritance defines an is-a relationship between a superclass and its subclasses. This means that an object of a subclass can be used wherever an object of the superclass can be used. Class Inheritance in java mechanism is used to build new classes from existing classes.
Definition 2:
Inheritance means to acquire property of others. It also means that we can use code of other functions and methods. Means Code reusability. In this object are defines by classes that are super class and which classes uses property of that class is known as sub class. It is very useful in Object Oriented Languages.
-------------------------------------------------------------------------------------------------------------------------
What is Association?
Association is a relationship between two classes. In this relationship the object of one instance perform an action on behalf of the other class. The typical behaviour can be invoking the method of other class and using the member of the other class.

   
public class MyMainClass
{
 public void init()
  {
    new OtherClass.init();
  }
}
-------------------------------------------------------------------------------------------------------------------------
What is Aggregation?

Aggregation has a relationship between two classes. In this relationship the object of one class is a member of the other class. Aggregation always insists for a direction.
   
public class MyMainClass
{
  OtherClass otherClassObj = new OtherClass();
}
-------------------------------------------------------------------------------------------------------------------------
What is Composition?
Composition is a special type of aggregation relationship with a difference that its the compulsion for the OtherClass object to exist for the existence of MyMainClass.

import java.util.ArrayList;

public class Aggregation
{
 public static void main(String[] args)
  {
    MusicPlayer player = new MusicPlayer();
    Car car = new Car();
    car.addPlayer(player);
  }
}

 Java 1.7 features.
    1) JDBC 4.1 more efficient introduced with the following features:
        The ability to use a try-with-resources statement to automatically close resources of type Connection, ResultSet, and Statement
        RowSet 1.1: The introduction of the RowSetFactory interface and the RowSetProvider class, which enable you to create all types of row sets supported by your JDBC driver.
    2) String objects can be as Switch literals.
        case "ONE": sop("one"); break;
    3) Automatic Type referece during Generic instance creation.
        Map> sample = HashMap<>(); 
        <> - operator called as diamond operator.
    4) try statement defining resources. No need of finally method to close this resources.
        try(file reader){
            return (readline)
        }
    5) Catch block to handle multiple exceptions.
        catch( arrayourofboune | numberformatexception | ex)
        since we cant use the main exception with in multple exception.
    6) JVM enhancement.

    7) IO - Zip File System Provider, Custom file system provider, java.nio.*, etc 


String Vs StringBuffer Vs StringBuilder

String is immutable while StringBuffer and StringBuilder is mutable object.

StringBuffer is synchronized while StringBuilder is not which makes StringBuilder faster than StringBuffer.


Concatenation operator "+" is internal implemented using either StringBuffer or StringBuilder.


Criteria to choose among String, StringBuffer and StringBuilder(Simple)

          Use String if you require immutability, 
          Use Stringbuffer in java if you need mutable + threadsafety 
          Use StringBuilder in Java if you require mutable + without thread-safety.

Criteria to choose among String, StringBuffer and StringBuilder(Explained in detail)
          If your text is not going to change use a string Class because a String object is immutable        
          If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.
          If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous.

ArrayList vs LinkedList

Both implements List interface.

       1) ArrayList is implment re sizable array.
       2) LinkedList is implment doubly Linkedlist.

Difference.

       1) Data structure of both is different.
       2) ArrayList - Getting and searching operation is fast(Getting from array index), Where remove opeation is too costly since it require rearrange all the index.
       3) On linkedList we need to iterate through all elements, Does not provide random or indexed base access.
       4) Insertion are very easy in Linkedlist since its not reuqire to rearranging an index.
       5) Linkedlist is more over head then arraylist, Since the node have data and address of the next and previous data.

When to use LinkedList:

                Since application inserts or remove more than retrieval then Linkedlist  is better option.
                If application can live with out random data access then Linkedlist is better option.

List of Available Design Patterns - GOF.

Creational Design Pattern
1) Abstract Factory pattern
2) Builder pattern
3) Factory pattern
4) Prototype pattern
5) Singletone pattern

Structural Design Pattern
1) Adapter
2) Bridge
3) Composite
4) Facade
5) Flyweight
6) Proxy

Behaviroral Design Pattern
1) Chain of responsiblity
2) Composite
3) Interpretor
4) Iterator
5) Memento
6) Observer
7) State
8) Strategy
9) Template Method
10) Visitor  

Spring key points

IOC or inversion of control / DI or dependency injection?
                 This Spring interview question is first step towards Spring framework and many interviewer starts Spring interview from this question. As the name implies Inversion of control means now we have inverted the control of creating the object from our own using new operator to container or framework. Now it’s the responsibility of container to create object as required. We maintain one xml file where we configure our components, services, all the classes and their property. We just need to mention which service is needed by which component and container will create the object for us. This concept is known as dependency injection because all object dependency (resources) is injected into it by framework.
Example:
  <bean id="createNewStock" class="springexample.stockMarket.CreateNewStockAccont">
        <property name="newBid"/>
  </bean>
In this example CreateNewStockAccont class contain getter and setter for newBid and container will instantiate newBid and set the value automatically when it is used. This whole process is also called wiring in Spring and by using annotation it can be done automatically by Spring, refereed as auto-wiring of bean in Spring.
------------------------------------------------------------------------------------------------------------
AOP?
      The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. AOP is a programming technique that allows developer to modularize crosscutting concerns,  that cuts across the typical divisions of responsibility, such as logging and transaction management. Spring AOP, aspects are implemented using regular classes or regular classes annotated with the @Aspect annotation
Jointpoint?
    A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being called, an exception being thrown, or even a field being modified. These are the points where your aspect’s code can be inserted into the normal flow of your application to add new behavior.
Advice?
    Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, and advice is inserted into an application at joinpoints.
Pointcut?
    A pointcut is something that defines at what joinpoints an advice should be applied. Advices can be applied at any joinpoint that is supported by the AOP framework. These Pointcuts allow you to specify where the advice can be applied.
------------------------------------------------------------------------------------------------------------
Core container module?
       This module is provides the fundamental functionality of the spring framework. In this module BeanFactory is the heart of any spring-based application. The entire framework was built on the top of this module. This module makes the Spring container.
------------------------------------------------------------------------------------------------------------
Application context module?
       The Application context module makes spring a framework. This module extends the concept of BeanFactory, providing support for internationalization (I18N) messages, application lifecycle events, and validation. This module also supplies many enterprise services such JNDI access, EJB integration, remoting, and scheduling. It also provides support to other framework.

Java - Annotations - Reflection

A Metadata Facility for the Java Programming Language.

Built-in Annotations in Java:
             @Override
                          Essentially tells to the compiler that method must be an overridden method. If not, then the compilers can report them as errors
             @SuppressWarnings
             @Deprecated

User-defined Annotations:
             Things that we need to consider while creating user defined annotation is as follows. (the same will be used for all annotations)
             Target Annotation
                              @Target(ElementType.METHOD) (Constructor, Field, Type, etc)
              Retention Annotation
                             @Retention(RetentionPolicy.CLASS) (Source Code, Class file, Run-time)

Reflection:
               Information related to Annotation types using Reflection(java Reflection API) for any type of java elements like class, interface, method, variables, etc.
 Performance Improvement - Java 
DURING DESIGN APPLICATION:

1) Excessive logging
              Use log into buffer and write at the end.
              Use async logging for better performance.
              Use framework like log4j, SLF4J. 
              Don't use System.err, System.out - There is no way to turn it off. 

2) Incorrect application server configuration.
               Use appropiate heap size based on JVM.
               Use proper thread pool, connection pool, connection time, child connection settings, logger levels, etc.

3) Incorrect usage of Java EE
             
4) Improper usage of caching.
               What is the cache hit ratio?
               How much memory the cache take?
               How performance testing with respect to cache? Is it disabled?
               Can cache monitored / managed at run time? (No of objects in cache, hit ratio, amount of memory used, enable/disable cache, flushing the content, etc).
               Use cache if and only if caching is needed.
               Verify the functional and performance behaviour of your cache with performance tests.
               Make sure your cache can be managed and monitored at runtime.

5) Excessive memory usage

6) Badly performing libraries               

  • without checking whether that library is really needed (and does not overlap with functionality already offered by other libraries used),
  • without checking whether that library can offer good performance or whether a better performing alternative is available,
  • without defining how the library is going to be used within the application.
DEPLOYMENT:
Environment tunning, Like tomcat tunning on Memory, thread, Time to live, etc.
    Few other options you should be aware of during Environment tunning:
  1. Add the -server option to the JVM options for Tomcat, which should result in better performance for server applications. Note that this option, in some cases, causes the JVM to crash for no apparent reason. If you face this problem, remove the option.
  2. Minimize logging in Tomcat by setting debug="0" everywhere in <Tomcat>/conf/server.xml.
  3. Remove any unnecessary resources from the Tomcat configuration file. Some examples include the Tomcat examples Web application and extra <Connector>, <Listener> elements.
  4. Set the autodeploy attribute of the <Host> tag to false (unless you need any of the default Tomcat applications like Tomcat Manager).
  5. Make sure you have set reloadable="false" for all your Web application contexts in <Tomcat>/conf/server.xml.
Database tunning. Size, ram, no of connection, etc.

Application tunning, Like code optimization, SQL query optimization, Sql profiler, etc
  1. Avoid using synchronized block in the code.
  2. Classes, Methods, Variables - where every possible use final variable.
  3. provide proper logging to help dubugging.

Ant or Maven

Maven:
  • Has its own structure of project layout.
  • Maven has conventions. It knows where your source code is because you followed the convention.
  • Maven has a lifecycle which was invoked when you executed mvn install. This command told Maven to execute a series of sequential lifecycle phases until it reached the install lifecycle phase.
  • Dependency Management and Versioned artifact support.
  • Maven is a build system
Ant:
  • The definition of project layout is your responsibility.
  • Ant doesn’t have formal conventions like a common project directory structure or default behavior.
  • Ant doesn’t have a lifecycle. You have to define goals and goal dependencies. You have to attach a sequence of tasks to each goal manually.
  • Ant is a build tool.

What is the design pattern?

The Design patterns are language independent staggering for solving common object-oriented design problems. SUN suggest GOF Design Patterns.

Why Tomcat 7?

Apache Tomcat version 7.0 implements the Servlet 3.0 and JavaServer Pages 2.2 Specification.
Tomcat 7:
                1) Application memory leave and prevention.
                2) Support for external content directly into web application.
                3) lot of code cleanup for connectors and lifecycle.
                4) Full support of Java Servlet Specification 3.0.|
                5) Simplified embedding.

Tips for using tomcat:
                1) Use Shared library concepts.
                2) Custom error pages.
                3) Tweak memory settings.
                4) Use IP/Hostname filters to allow subset machines to connect.
                5) Secure directory listing.
                6) Use GZip compression.
Tomcat supports:
                      1) SSL.
                      2) Proxy support.
                      3) Load Balancer.
                      4) Virtual Hosting.
                      5) Logging.
                      6) SSI, CGI.
                      7) Embedded Tomcat.

REST Vs Soap

REST: Representational state transfer, It’s an architecture.
              REST architectures consist of clients and servers. Clients initiate requests to servers; servers process requests and return appropriate responses. Requests and responses are built around the transfer of representations of resources
               REST architecture work with Http protocol, so it’s purely stateless,
               Client request can catch the responses to improve the performances,
               It’s a layered architecture; we can improve the system by enabling load-balancer, cache server, etc.
               It provides / designed for uniform interface.
                REST: bandwidth usage is lighter.
SOAP:
               It’s a an protocol,
               It can run on Http, Jms, Ftp, SMTP protocols.
               This supports Transaction, security, etc But REST users to build this custom plumbing,
 

IaaS vs. PaaS vs. SaaS

SaaS:
Software as a Services. Essentially based on the concept of renting application functionality from a service provider rather than buying, installing and running software yourself. delivering the equivalent of a complete application suite.
Some time we call it as "Storage as a Services".  Some time called as "on-demand software"


PaaS:
Platform as a Services.

IaaS:
Infrastructure as a service.

No comments:

Post a Comment