Wednesday, November 19, 2014

J2EE interview Questions and Answers

.

Q .       Difference between HibernateTemplate and JdbcTemplate in Spring?



If you have a normalized database where you can easily map tables to Java classes that represent business entities, then you may do well with HibernateTemplate (And even better with Spring JPA Repositories).

If you have a legacy database that is not normalized and mapping tables to business entities is a hard work, you'll have to use JdbcTemplate.
Hibernate is a really huge solution with data persistence and ORM including JPA implementation. Also there are defined many ways how to manage entities in Hibernate, how to persist, transactions, etc. In hibernate you can use SQL, HQL or java annotations. 
JDBC template is just a simple tool that helps you to manage SQL queries and transactions. Probably it is better JDBC wrapper or helper. Also if you prefer managing database queries (SQL) yourself or if you are a beginner, try Spring JdbcTemplate to understand, how it works. Even if you are working on a bigger application, think about using Hibernate. However it needs some time to know Hibernate.

Spring provides hibernate DAO template and it has many advantages like 
1) It removes boiler plate code like getting connection from data source, try/catch block for closing connection. So that developer can focus on writing business logic rather then writing boilier plate code every where. 
2) Spring hibernateTemplate also throws RunTime exception compared to checkd exception which allows to remove writing try/catch block in each DAO. 
3) It also gives richer template class, using which developer can write query code easily. This template class also allows to get session explicitly, so if developer wants to get session object and work on it, then it's possible. 
Disadvantage 
1) It doesn't support to cann stored procedure. 
2) Don't have method to execute SQL query .


Java SE (formerly J2SE) is the basic Java environment. In Java SE, you make all the "standards" programs with Java, using the API described here. You only need a JVM to use Java SE.
Java EE (formerly J2EE) is the enterprise edition of Java. With it, you make websites, Java Beans, and more powerful server applications. Besides the JVM, you need an application server Java EE-compatible, like GlassfishJBoss, and others.
Java SE stands for Java standard edition and is normally for developing desktop applications, forms the core/base API.
Java EE stands for Java enterprise edition for applications which run on servers, for example web sites.
Java ME stands for Java micro edition for applications which run on resource constrained devices (small scale devices) like cell phones, for example games.
Java SE refers to the standard version of Java and its libraries. Java EE refers to the Enterprise edition of Java which is used to deploy web applications.


Q . Are Spring Beans Thread Safe?

No.
Spring has different bean scopes (e.g. Prototype, Singleton, etc.) but all these scopes enforce is when the bean is created. For example a "prototype" scoped bean will be created each time this bean is "injected", whereas a "singleton" scoped bean will be created once and shared within the application context. There are other scopes but they just define a time span (e.g. a "scope") of when a new instance will be created.
The above has little, if anything to do with being thread safe, since if several threads have access to a bean (no matter the scope), it would only depend on the design of that bean to be or not to be "thread safe".
The reason I said "little, if anything" is because it might depend on the problem you are trying to solve. For example if you are concerned whether 2 or more HTTP requests may create a problem for the same bean, there is a "request" scope that will create a new instance of a bean for each HTTP request, hence you can "think" of a particular bean as being "safe" in the context of multiple HTTP requests. But it is still not truly thread safe by Spring since if several threads use this bean within the same HTTP request, it goes back to a bean design (your design of a bean backing class).

Q .  How to Make/Design a Thread Safe "Object"?

There are several ways, probably too long to list here but here are a few examples:
  • Design your beans immutable: for example have no setters and only use constructor arguments to create a bean. There are other ways, such as Builder pattern, etc..
  • Design your beans stateless: for example a bean that does something can be just a function (or several). This bean in most cases can and should be stateless, which means it does not have any state, it only does things with function arguments you provide each time (on each invocation)
  • Design your beans persistent: which is a special case of "immutable", but has some very nice properties. Usually is used in functional programming, where Spring (at least yet) not as useful as in imperative world, but I have used them with Scala/Spring projects.
  • Design your beans with locks [last resort]: I would recommend against this unless you are working on a lower level library. The reason is we (humans) are not good thinking in terms of locks. Just the way we are raised and nurtured. Everything happens in parallel without us needing to "put that rain on pause, let me get an umbrella". Computers however are all about locks when you are talking "multiple things at the same time", hence there are some of us (exceptional people) who are doing their fair share and implementing libraries based on these locks. Most of other humans can just use these libraries and worry not about concurrency.
Spring framework does not do anything under the hood concerning the multithreaded behavior of a singleton bean. It is the developer's responsibility to deal with concurrency issue and thread safety of the singleton bean.


Q . When to use LazyLoading and Eager Loading in Hibernate ? Why ?

I believe there is only two ways of loading objects using Hibernate and that is lazy loading and one is eager loading. Lazy loading has its own advantages, it is not loading lots of objects but only when you need them. I also have learned that if you want to force to load all the children for an object you can simply call the parent.getChildren().size(). So let's say we have the following objects

Here are a few thoughts:
1) If you are going to always use something (for sure), you can eager load it.
2) Related to 1, if you are almost never going to use something, lazy load it.
3) Lazy loading tends to be more useful when large collections are involved.
4) Eagerly loading things will reduce session-related errors, at the potential cost of a performance hit.
5) For complicated data models and/or large databases, you are going to see how your app does under load an adjust your strategies.
6) It's difficult to get it right the first time. Do what feels right, and don't be afraid to change if necessary. 
7) For large datasets, you are going to probably end up writing custom hql/queries anyway, where the default mappings can be overwritten, so lazy vs eager won't matter so much.
If you believe #6, then don't get stuck trying to plan too far ahead, and change it if you have to.
WRT your specific example, I would probably write a bunch of queries to access the data (driven by appropriate business needs, of course)
1) A query that loads the customer, and leaves the orders in the db (so lazy loading) that I would call when I need to get customer info
2) A query that loads the customer and all order info, for cases where I need it. So this case I'll ignore the default mapping.
With those two queries in place, in my service layers I have the tools I need to do what is correct based on the context of the situation.
LAZY loading is used in cases where the related entity size is huge and it's not required to be fetched every time on the other hand
EAGER should be used with proper analysis as it loads the relationship every time the main entity is loaded.
So if a relationship is absolutely necessary for business logic computation you should think of making use of EAGER loading; LAZY loading will serve most of the cases and provides less performance trouble.

Q . Difference between IOC and Dependency Injection in Spring?



IoC introduction

In traditional programming, the flow of the business logic is determined by objects that are statically assigned to one another. With inversion of control, the flow depends on the object graph that is instantiated by the assembler and is made possible by object interactions being defined through abstractions. The binding process is achieved through dependency injection, although some argue that the use of a service locator also provides inversion of control.
Inversion of control as a design guideline serves the following purposes:
  1. There is a decoupling of the execution of a certain task from implementation.
  2. Every module can focus on what it is designed for.
  3. Modules make no assumptions about what other systems do but rely on their contracts.
  4. Replacing modules has no side effect on other modules.

Differentiating with dependency injection

Inversion of control is a design paradigm with the goal of giving more control to the targeted components of your application, the ones getting the work done.
Dependency injection is a pattern used to create instances of objects that other objects rely on without knowing at compile time which class will be used to provide that functionality. Inversion of control relies on dependency injection because a mechanism is needed in order to activate the components providing the specific functionality.
The two concepts work together in this way to allow for much more flexible, reusable, and encapsulated code to be written. As such, they are important concepts in designing object-oriented solutions.

Implementing inversion of control design pattern

In object-oriented programming, there are several basic techniques to implement inversion of control. These are:
  1. using a factory pattern
  2. using a service locator pattern
  3. using a dependency injection of any given below type:
    • a constructor injection
    • a setter injection
    • an interface injection

IoC in spring framework

The org.springframework.beans and org.springframework.context packages provide the basis for the Spring Framework’s IoC container. The BeanFactory interface provides an advanced configuration mechanism capable of managing objects of any nature. The ApplicationContext interface builds on top of the BeanFactory (it is a sub-interface) and adds other functionality such as easier integration with Spring’s AOP features, message resource handling (for use in internationalization), event propagation, and application-layer specific contexts such as the WebApplicationContext for use in web applications.
The org.springframework.beans.factory.BeanFactory is the actual representation of the Spring IoC container that is responsible for containing and otherwise managing the aforementioned beans. The BeanFactory interface is the central IoC container interface in Spring.
container-magic
There are a number of implementations of the BeanFactory interface. The most commonly used BeanFactory implementation is the XmlBeanFactory class. Other commonly used class is XmlWebApplicationContext. Depending on the bean definition, the factory will return either an independent instance of a contained object (the Prototype design pattern), or a single shared instance (a superior alternative to the Singleton design pattern, in which the instance is a singleton in the scope of the factory). Which type of instance will be returned depends on the bean factory configuration: the API is the same.
Before we dive into dependency injection types, let first identify the ways of creating a bean in spring framework as it will help in understanding the things in next section.

Ways to instantiate beans in spring

A bean definition can be seen as a recipe for creating one or more actual objects. The container looks at the recipe for a named bean when asked, and uses the configuration metadata encapsulated by that bean definition to create (or acquire) an actual object.
Instantiation using a constructor
When creating a bean using the constructor approach, all normal classes are usable by and compatible with Spring. That is, the class being created does not need to implement any specific interfaces or be coded in a specific fashion. Just specifying the bean class should be enough. When using XML-based configuration metadata you can specify your bean class like so:

<bean id="exampleBean"/>
Instantiation using a static factory method
When defining a bean which is to be created using a static factory method, along with the class attribute which specifies the class containing the static factory method, another attribute named factory-method is needed to specify the name of the factory method itself.

<bean id="exampleBean" factory-method="createInstance"/>
Spring expects to be able to call this method and get back a live object, which from that point on is treated as if it had been created normally via a constructor.
Instantiation using an instance factory method
In a fashion similar to instantiation via a static factory method, instantiation using an instance factory method is where the factory method of an existing bean from the container is invoked to create the new bean.


<bean id="myFactoryBean"  class="...">
<bean id="exampleBean"  factory-bean="myFactoryBean"  
           factory-method="createInstance"></bean>

Various dependency injection mechanisms

The basic principle behind Dependency Injection (DI) is that objects define their dependencies only through constructor arguments, arguments to a factory method, or properties which are set on the object instance after it has been constructed or returned from a factory method. Then, it is the job of the container to actually inject those dependencies when it creates the bean. This is fundamentally the inverse, hence the name Inversion of Control (IoC).
Setter injection :
   Setter-based DI is realized by calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.
   public class TestSetter {
    DemoBean demoBean = null;
    public void setDemoBean(DemoBean demoBean) {
        this.demoBean = demoBean;
    }
}
Constructor injection :
 Constructor-based DI is realized by invoking a constructor with a number of arguments, each representing a collaborator. Additionally, calling a static factory method with specific arguments to construct the bean, can be considered almost equivalent, and the rest of this text will consider arguments to a constructor and arguments to a static factory method similarly.
Interface injection :  In this methodology we implement an interface from the IOC framework. IOC framework will use the interface method to inject the object in the main class. It is much more appropriate to use this approach when you need to have some logic that is not applicable to place in a property. Such as logging support.

public void SetLogger(ILogger logger)
{
  _notificationService.SetLogger(logger);
  _productService.SetLogger(logger);
}

Some Questions : 

Q  .  What is difference between component and service?
A component is a glob of software that’s intended to be used, without change, by an application that is out of the control of the writers of the component. By ‘without change’ means that the using application doesn’t change the source code of the components, although they may alter the component’s behavior by extending it in ways allowed by the component writers.
A service is similar to a component in that it’s used by foreign applications. The main difference is that a component to be used locally (think jar file, assembly, dll, or a source import). A service will be used remotely through some remote interface, either synchronous or asynchronous (eg web service, messaging system, RPC, or socket.)
Q  . How DI is different from Service locator pattern?
The key benefit of a Dependency Injector is that it allows to plug-in a suitable implementation of a service according to environment and usage. Injection isn’t the only way to break this dependency, another is to use a service locator. The basic idea behind a service locator is to have an object that knows how to get hold of all of the services that an application might need. It then scans all such services and store them as a singleton Registry. When asked for a service implementation, a requester can query the registry with a token and get appropriate implementation.
Mostly these registries are populated via some configuration files. The key difference is that with a Service Locator every user of a service has a dependency to the locator. The locator can hide dependencies to other implementations, but you do need to see the locator.
Q   .  Which one should be better to use i.e. service locator or dependency injection?
Well, it as I already said that key difference is that with a Service Locator every user of a service has a dependency to the locator. It means you must know the details of service locator in terms of input and output. So, it actually becomes the deciding factor which pattern to choose from.
If it is easy and necessary to maintain registry information then go for service locator, or else simply use dependency injection as it does not bother the users of service with any per-requisites.
Q  .  Which is better constructor injection or setter injection?
The choice between setter and constructor injection is interesting as it mirrors a more general issue with object-oriented programming -- should you fill fields in a constructor or with setters.
Constructors with parameters give you a clear statement of what it means to create a valid object in an obvious place. If there’s more than one way to do it, create multiple constructors that show the different combinations. Another advantage with constructor initialization is that it allows you to clearly hide any fields that are immutable by simply not providing a setter. I think this is important -- if something shouldn’t change then the lack of a setter communicates this very well. If you use setters for initialization, then this can become a pain.
But If you have a lot of constructor parameters things can look messy, particularly in languages without keyword parameters. If you have multiple ways to construct a valid object, it can be hard to show this through constructors, since constructors can only vary on the number and type of parameters. Constructors also suffer if you have simple parameters such as strings. With setter injection you can give each setter a name to indicate what the string is supposed to do. With constructors you are just relying on the position, which is harder to follow.
My preference is to start with constructor injection, but be ready to switch to setter injection as soon as the problems I’ve outlined above start to become a problem.
Q   . What is Bean Factory ?
A BeanFactory is like a factory class that contains a collection of beans. The BeanFactory holds Bean Definitions of multiple beans within itself and then instantiates the bean whenever asked for by clients.
BeanFactory is able to create associations between collaborating objects as they are instantiated. This removes the burden of configuration from bean itself and the beans client. BeanFactory also takes part in the life cycle of a bean, making calls to custom initialization and destruction methods.
Q  . What is Application Context?
A bean factory is fine to simple applications, but to take advantage of the full power of the Spring framework, you may want to move up to Springs more advanced container, the application context. On the surface, an application context is same as a bean factory.Both load bean definitions, wire beans together, and dispense beans upon request. But it also provides:
  • A means for resolving text messages, including support for internationalization.
  • A generic way to load file resources.
  • Events to beans that are registered as listeners.
Q . What are the common implementations of the Application Context ?
The three commonly used implementation of ‘Application Context’ are
1) ClassPathXmlApplicationContext : It Loads context definition from an XML file located in the classpath, treating context definitions as classpath resources. The application context is loaded from the application’s classpath by using the code .
ApplicationContext context = new ClassPathXmlApplicationContext(“bean.xml”);
2) FileSystemXmlApplicationContext : It loads context definition from an XML file in the filesystem. The application context is loaded from the file system by using the code .
ApplicationContext context = new FileSystemXmlApplicationContext(“bean.xml”);
3) XmlWebApplicationContext : It loads context definition from an XML file contained within a web application.
Q .What should be used preferably BeanFactory or ApplicationContext?
A BeanFactory pretty much just instantiates and configures beans. An ApplicationContext also does that, and it provides the supporting infrastructure to enable lots of enterprise-specific features such as transactions and AOP. In short, favor the use of an ApplicationContext.

Q . What is the purpose of Marker Interface in java ?

I know what is marker interface - An interface with no methods. Example: Serializable, Remote, Cloneable.
I am wondering what is the purpose of marker interface. This is my understanding:-
Basically it is just to identify the special objects from normal objects. Like in case of serialization , objects that need to be serialized must implement serializable interface and down the line writeObject() method must be checking somewhere if it is a instance of serializable or not. As far as i think ,Thats the only purpose for which writeObject using interface serializable(marker interface). Right? or jvm provides some extra functionality too on the basis of serializable interface?
Similar kind of logic is true for cloneable interface.
Now lets see how it is useful.
Lets say in a application we have 1000 value objects.We want to serialize only 100 specific objects . Now JDK has said that programmer role is just to mark the object as special with marker interface in this case its serializable interface.Now JDK will take care of that which object to serialize or not?
Yes we could achieve this kind of behaviour with some kind of boolean flag . but that would be a bad approach.
Similarly we can say in case of user defined marker interface , we can distinguish special objects with help of marker interface.Like we can use instance of operator to determine if it is a instance of that particular interface . If yes proceed in case of No throw some exception.
Java Marker Interface Examples
  • java.lang.Cloneable
  • java.io.Serializable
  • java.util.EventListener

Difference between Struts 1.x and Struts 2.x :

FeatureStruts 1Struts 2
Action classesStruts1 extends the abstract base class by its action class. The problem with struts1 is that it uses the abstract classes rather than interfaces.While in Struts 2, an Action class implements an Action interface, along with other interfaces use optional and custom services. Struts 2 provides a base ActionSupport class that implements commonly used interfaces. Although an Action interface is not necessary, any POJO object along with an execute signature can be used as an Struts 2 Action object.
Threading ModelStruts 1 Actions are singletons therefore they must be thread-safe because only one instance of a class handles all the requests for that Action. The singleton strategy restricts to Struts 1 Actions and requires extra care to make the action resources thread safe or synchronized while developing an application.Struts 2 doesn't have thread-safety issues as Action objects are instantiated for each request. A servlet container generates many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.
Servlet DependencyActions are dependent on the servlet API because HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked therefore Struts1.Container does not treat the Struts 2 Actions as a couple. Servlet contexts are typically represented as simple Maps that allow Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required. While other architectural elements directly reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse.
TestabilityStruts1 application has a major problem while testing the application because the execute method exposes the Servlet API. Struts TestCase provides a set of mock object for Struts 1.To test the Struts 2 Actions instantiate the Action, set the properties, and invoking methods. Dependency Injection also makes testing easier.
Harvesting InputStruts 1 recieves an input by creating an ActionForm object. Like the action classes, all ActionForms class must extend a ActionForm base class. Other JavaBeans classes cannot be used as ActionForms, while developers create redundant classes to receive the input. DynaBeans is the best alternative to create the conventional ActionForm classes.Struts 2 requires Action properties as input properties that eliminates the need of a second input object. These Input properties may be rich object types, since they may have their own properties. Developer can access the Action properties from the web page using the taglibs. Struts 2 also supports the ActionForm pattern, POJO form objects and POJO Actions as well.
Expression LanguageStruts1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support.Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).
Binding values into viewsStruts 1 binds objects into the page context by using the standard JSP mechanism.Struts 2 uses a ValueStack technology to make the values accessible to the taglibs without coupling the view to the object to which it is rendering. The ValueStack strategy enables us to reuse views across a range of types, having same property name but different property types.
Type ConversionStruts 1 ActionForm properties are almost in the form of Strings. Commons-Beanutils are used by used by Struts 1 for type conversion. Converters are per-class, which are not configurable per instance.Struts 2 uses OGNL for type conversion and converters to convert Basic and common object types and primitives as well.
ValidationStruts 1 uses manual validation that is done via a validate method on the ActionForm, or by using an extension to the Commons Validator. Classes can have different validation contexts for the same class, while chaining to validations on sub-objects is not allowed.Struts 2 allows manual validation that is done by using the validate method and the XWork Validation framework. The Xwork Validation Framework allows chaining of validations into sub-properties using the validations defined for the properties class type and the validation context.
Control Of Action ExecutionEach module in Struts 1 has a separate Request Processors (lifecycles), while all the Actions in the module must share the same lifecycle.In Struts 2 different lifecycles are created on a per Action basis via Interceptor Stacks. Custom stacks are created and used with different Actions








1 comment:

  1. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in Product prototyping during this lockdown period everyone can use it wisely.
    icp-cat training

    ReplyDelete

Java 9 and Java11 and Java17, Java 21 Features

 Java 9 and Java11 and Java17 features along with explanation and examples in realtime scenarios Here's a detailed breakdown of Java 9, ...