Final Technical Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 46

Nth highest salary in Oracle using ROW_NUMBER() function

SELECT * FROM (
SELECT e.*,
ROW_NUMBER() OVER (ORDER BY salary DESC) rn
FROM Employee e
)
WHERE rn = N; /*N is the nth highest salary*/

SQL Query:

SELECT name, salary


FROM #Employee e1
WHERE N-1 = (SELECT COUNT(DISTINCT salary) FROM #Employee e2
WHERE e2.salary > e1.salary)

To reverse a singly linked list you should have three nodes, top, beforeTop and AfterTop.
Top is the header of singly linked list, hence beforeTop would be null and afterTop would
be next element of top and with each iteration move forward beforeTop is assigned top and
top is assigned afterTop(i.e. top.next)

Iterative:
Logic for this would be:
 Have three nodes i.e previousNode,currentNode and nextNode
 When currentNode is starting node, then previousNode will be null
 Assign currentNode.next to previousNode to reverse the link.
 In each iteration move currentNode and previousNode by  1 node.

1  

2 public static Node reverseLinkedList(Node currentNode)

3 {

4 // For first node, previousNode will be null

5 Node previousNode=null;
6   Node nextNode;

7   while(currentNode!=null)

8   {

9    nextNode=currentNode.next;

10   // reversing the link

11    currentNode.next=previousNode;

12   // moving currentNode and previousNode by 1 node

13    previousNode=currentNode;

14    currentNode=nextNode;

15   }

16   return previousNode;

17 }

18  

Recursive:
Base case: Base case for this would be either node is null or node.next is null
For recursive solution, replace reverseLinkedList of above program to below
function

1  

2 public static Node reverseLinkedList(Node node) {

3 if (node == null || node.next == null) {

4 return node;

5 }

6  

7 Node remaining = reverseLinkedList(node.next);

8 node.next.next = node;

9 node.next = null;

10 return remaining;

11 }

12  

Program: Write a program to create deadlock between two threads.


Description:

Deadlock describes a situation where two or more threads are blocked forever, waiting for each
other. Deadlocks can occur in Java when the synchronized keyword causes the executing thread to
block while waiting to get the lock, associated with the specified object. Since the thread might
already hold locks associated with other objects, two threads could each be waiting for the other to
release a lock. In such case, they will end up waiting forever.

Code:

10

11

12

13

14

15

16

17

18

19
20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

package com.java2novice.algos;

public class MyDeadlock {

String str1 = "Java";

String str2 = "UNIX";

Thread trd1 = new Thread("My Thread 1"){

public void run(){


while(true){

synchronized(str1){

synchronized(str2){

System.out.println(str1 + str2);

};

Thread trd2 = new Thread("My Thread 2"){

public void run(){

while(true){

synchronized(str2){

synchronized(str1){

System.out.println(str2 + str1);

};

public static void main(String a[]){

MyDeadlock mdl = new MyDeadlock();

mdl.trd1.start();

mdl.trd2.start();

}
}

Hashmap overrites the old value if key is duplicate

Class clazz = Class.forName ("com.Car"); 

Car myCar = (Car) clazz.newInstance ( );

ClassLoader classLoader = MyClass.class.getClassLoader();  


forName("com.SomeClass", true, currentClassLoader)

Loading property file from classapth


final Properties properties = new Properties();
try (final InputStream stream = this.getClass().getResourceAsStream("myapp.properties")) {
    properties.load(stream);
    /* or properties.loadFromXML(...) */
}

Loading it from outside the classpath is NOT portable

final Properties properties = new Properties();

final String dir = System.getProperty("user.dir");

try (final InputStream stream = new FileInputStream(dir + "/myapp/myapp.properties")) {

properties.load(stream);

Default specifier: accessible to all classes in same package only

Overloading – compile time(static polymorphism)

Overriding – run time(dynamic polymorphism)

Serialization ignores static fields

Class A{

int x;

Func() {}

Class b extends A{

int x;
Func() {}

If you create object of subclass with reference of super class like ( A a = new B();) then subclass
method(a.Func()) and super class variable(a.x) will be executed.

Class A{

Static { }

{ }

Pvsm(){}

First execute static block, then statement block then constructor.


An object is eligible for garbage collection when its reference is set to null.its automatic and done
by JVM by calling finalize() on such eligible objects

public class Test { public static void main(String[] args){ String value = "abc"; changeValue(value);
System.out.println(value); } public static void changeValue(String a){ a = "xyz"; } } Options are A.abc
B.xyz C.Compilation fails D.Compilation clean but no output Answer : A is the correct answer. Java
pass reference as value. passing the object reference, and not the actual object itself. Simply
reassigning to the parameter used to pass the value into the method will do nothing, because the
parameter is essentially a local variable.

If a superclass throws exception then overrridden method in subclass must throw exception

both method (one static and other no-static) can run simultaneously. A static synchronized method
and a non static synchronized method will not block each other. If one synchronized method of an
instance is executing then other synchronized method of the same instance should wait.

Thread t = new Thread(a,"A"); Thread t1 = new Thread(a,"B"); t.start(); t.join(); t1.start();

t.join(); means Threat t must finish before Thread t1 start.ie., run() will be called by t and after it
finished then same run() called by t1.

class Rextester

{
public static void main(String... args) throws Exception {

B b = new B();

OR

A a = new B(); }

class A{

A() {

System.out.println("A"); } }

class B extends A {

B() {

System.out.println("B"); } }

OUTPUT:
A
B

First constructor of super class is called and then sub class.

Override only equals
If only equals is overriden, then when you call myMap.put(first,someValue) first will hash
to some bucket and when you call myMap.put(second,someOtherValue) it will hash to
some other bucket (as they have a different hashCode). So, although they are equal, as
they don't hash to the same bucket, the map can't realize it and both of them stay in the
map.

Although it is not necessary to override equals() if we override hashCode(), let's see what


would happen in this particular case where we know that two objects of MyClass are
equal if their importantField is equal but we do not override equals().
Override only hashCode
Imagine you have this

MyClass first = new MyClass("a","first");


MyClass second = new MyClass("a","second");
If you only override hashCode then when you call myMap.put(first,someValue) it takes
first, calculates its hashCode and stores it in a given bucket. Then when you
call myMap.put(second,someOtherValue) it should replace first with second as per the Map
Documentation because they are equal (according to the business requirement).
But the problem is that equals was not redefined, so when the map hashes second and
iterates through the bucket looking if there is an object k such that second.equals(k) is
true it won't find any as second.equals(first) will be false.

1. If two objects are equal, then they must have the same hash code.
2. If two objects have the same hash code, they may or may not be equal.

1. Duplicate objects are added in Hashmap as a key (Because we have not


overided the hashcode and equals method)
2. We are not able to get back object from map (Because hashcode is not
implemented)

Object.equals() method consider two object references as equal if they point to the same
object. Classes override equals method to specify the object equality. For example - We
may like two objects to be treated equal if all of its elements of one object are equal to all
elements of the other object or we may just want equality on the basis of one of the
element only. So we define this rule for equality in the overridden equal method. 
equals() :
If you only override equal method, a.equals(b) is true it means the hashCode of a and b
must be same but not happen. Because you did not override hashCode method.
Note : hashCode() method of Object class always return new hashCode for each object.

Following well known HTTP methods are commonly used in REST based architecture ? GET ?
Provides a read only access to a resource. PUT ? Used to create a new resource. DELETE ? Ued to
remove a resource. POST ? Used to update a existing resource or create a new resource. OPTIONS ?
Used to get the supported operations on a resource.

Status/Response Code ? Indicate Server status for the requested resource. For example 404 means
resource not found and 200 means response is ok.401 forbidden and 500 internal server error

A URI is of following format ?

<protocol>://<service-name>/<ResourceType>/<ResourceID>

RESTful—client must pass session id to the server

<Cache-Control> header of HTTP response provides control over caching?

What are the best practices to be followed while designing a secure RESTful web service? As RESTful
web services work with HTTP URLs Paths so it is very important to safeguard a RESTful web service in
the same manner as a website is be secured. Following are the best practices to be followed while
designing a RESTful web service ? Validation ? Validate all inputs on the server. Protect your server
against SQL or NoSQL injection attacks. Session based authentication ? Use session based
authentication to authenticate a user whenever a request is made to a Web Service method. No
sensitive data in URL ? Never use username, password or session token in URL , these values should
be passed to Web Service via POST method. Restriction on Method execution ? Allow restricted use
of methods like GET, POST, DELETE. GET method should not be able to delete data. Validate
Malformed XML/JSON ? Check for well formed input passed to a web service method. Throw generic
Error Messages ? A web service method should use HTTP error messages like 403 to show access
forbidden etc.

What is the difference between REST and SOAP Based Services? First of all, REST is a set of
architectural principles defining how a RESTful service should look look like. SOAP is a message
exchange format. SOAP defines the structure of message to exchanged. How should the header be?
How should the request content be? So, there is no real comparison between REST and SOAP.
Restful Sample Implementation : JSON over HTTP SOAP Sample Implementation : XML over SOAP
over HTTP All comparison is between the Sample Restful and SOAP implementations described
above. REST is built over simple HTTP protocol. SOAP services are more complex to implement and
more complex to consume. REST has better performance and scalability. REST reads can be cached,
SOAP based reads cannot be cached. REST permits many different data formats (JSON is the most
popular choice) where as SOAP only permits XML. SOAP services have well defined structure and
interface (WSDL). SOAP is based on well defined standards (WS-Security, WS-AtomicTransaction and
WS-ReliableMessaging).

HTTP/1.1 200 OK
Content-Type: application/json
Cache-Control: private, max-age=86400
Last-Modified: Thu, 07 Feb 2013 11:56 EST
@Path("/book/{id}")
@PUT
@Consumes("application/json")
public Response getBook(@PathParam("id") long id)

What are the best practices in using HTTP methods with Restful Web Services?

GET : Should not update anything. Should be idempotent (same result in multiple calls). Possible
Return Codes 200 (OK) + 404

(NOT FOUND) +400 (BAD REQUEST)

POST : Should create new resource. Ideally return JSON with link to newly created resource. Same
return codes as get possible. In

addition : Return code 201 (CREATED)

Can you explain a little bit about JAX-RS?

JAX-RS is the JEE Specification for Restful web services implemented by all JEE compliant web servers
(and application servers).

Important Annotations:

@ApplicationPath("/"). @Path("users") : used on class and methods to define the url path.
@GET @POST : Used to define the HTTP method that invokes the method.

@Produces(MediaType.APPLICATION_JSON) : Defines the output format of Restful service.

@Path("/{id}") on method (and) @PathParam("id") on method parameter : This helps in defining a


dynamic parameter in Rest URL.

@Path("{user_id}/followers/{follower_id}") is a more complicated example.

@QueryParam("page") : To define a method parameter ex: /users?page=10.

Useful methods:

Response.OK(jsonBuilder.build()).build() returns json response with status code.

Json.createObjectBuilder(). add("id",user.getId()); creates a user object.

XX:+UseParallelGC

//disable reflection in singleton

private static final JavaSingleton singleton = new


JavaSingleton();
private Singleton() {
if( Singleton.singleton != null ) {
throw new InstantiationError( "Creating of this object is not allowed." );
}
}

Java.util.Concurrent.CyclicBarrier is a synchronisation aid that allows a set of threads to


wait for each other to reach a common barrier point before continuing execution
CountDownLatch in Java is a kind of synchronizer which allows one Thread  to wait for one or more
Threads before starts processing.

Collections.synchronizedList(<List> t)
Collections.sort(<List> t)

a weak reference. Objects referenced by them may be garbage collected -- if the JVM runs short
of memory -- even when they are being used. (WeakReference<String> wr
= new WeakReference<String>(new String("abc"));)

grep -R "your word" .


finding a word in all files in current directory/folder

Swapping column values in MySQL


UPDATE swap_test SET x=(@temp:=x), x = y, y = @temp;

UPDATE swap_test s1, swap_test s2 SET s1.x=s1.y, s1.y=s2.x WHERE s1.id=s2.id;

SOAP envelope which is in XML format, on the other hand, RESTful web services allow you
to send a request in various formats(JSON,XML). RESTful web service takes full advantage
of the web caching but not SOAP
SOAP messages can be sent over to any transport mechanism e.g. TCP, FTP, SMTP or any
other protocol. On the other hand, RESTful Web services are heavily dependent upon
HTTP protocol.

Inde SQL NoSQL


x

1) Databases are categorized as NoSQL databases are categorized as


Relational Database Non-relational or distributed database system.
Management System
(RDBMS).

2) SQL databases have fixed or NoSQL databases have dynamic


static or predefined schema. schema.

3) SQL databases display data in NoSQL databases display data as


form of tables so it is known collection of key-value pair,
as table-based database. documents, graph databases or
wide-column stores.

4) SQL databases are vertically NoSQL databases are horizontally


scalable. scalable.

5) SQL databases use a powerful In NoSQL databases, collection of documents are used
language "Structured Query also called unstructured query language.
Language" to define and It varies from database to database.
manipulate the data.

6) SQL databases are best suited NoSQL databases are not so good for
for complex queries. complex queries because these
are not as powerful as SQL queries.

7) SQL databases are not best NoSQL databases are best suited
suited for hierarchical data for hierarchical data storage.
storage.

First-level cache --- Session --default. Mainly it reduces the number of SQL queries it needs to
generate within a given transaction. That is instead of updating after every modification done in
the transaction, it updates the transaction only at the end of the transaction.
Second-level cache(ex. EH cache ) ----- Session Factory ---objects will be available to the entire
application, not bound to single user.

The fundamental difference is wait() is from Object and sleep() is static method of Thread .
The major difference is that wait() releases the lock while sleep() doesn't release any lock
while waiting. The wait() is used for inter-thread communication while sleep() is used to
introduce pause on execution, generally.sleep(1000) – pauses for exactly 1 seond
wait(1000) – pauses for <=1 second depending on when notify() is called

if a block of code or method is using a shared resource/object always synchronize that block
or method.If one thread modifies a synchronized/locked object ,its value is updated in heap
so that other threads get latest information.
BlockingQueue, you can easily share data between threads without being bothered about
thread safety 

In Java, memory leak can occur due to

1) Long living objects having reference to short living objects, causing the
memory to slowly grow. For example, singleton classes referring to short
lived objects. This prevents short-lived objects being garbage collected.
2) Improper use of thread-local variables. The thread-local variables will not
be removed by the garbage collector as long as the thread itself is alive.
So, when threads are pooled and kept alive forever, the object might
never be removed by the garbage collector.
3) Using mutable static fields to hold data caches, and not explicitly clearing
them. The mutable static fields and collections need to be explicitly
cleared.
4) Objects with circular references from a thread. GC uses “reference
counting“. Whenever a reference to an object is added its reference count
is increased by 1. Whenever a reference to an object is removed, the
reference count is decreased by 1. If “A” references object B and B
references object A, then both of their reference counts can never be less
than 1, which means they will never get collected.

A sorted collection(using Compatator/Collections.sort) is more suited for small dataset but for a
large dataset, it's better to use ordered collection(orderby SQL) to avoid OutOfMemoryError in
Java application.

@Component
@Scope(value="prototype")
public class PrototypeBean {
// ...
}
@Component
public class SingletonBean{

@Autowired
private PrototypeBean prototypeBean;

Here only 1 instance of prototype bean is created for all requests

General Questions – Spring Interview Questions


1. What is a Spring Framework?

Spring is a powerful open source, application framework


created to reduce the complexity of enterprise application development. It is
light-weighted and loosely coupled. It has layered architecture, which allows you
to select the components to use, while also providing a cohesive framework for
J2EE application development. Spring framework is also called framework of
frameworks as it provides support to various other frameworks such as Struts,
Hibernate, Tapestry, EJB, JSF etc.
2. List the advantages of Spring Framework.

 Because of Spring Frameworks layered architecture, you can use what you
need and leave which you don’t.
 Spring Framework enables POJO (Plain Old Java Object) Programming which
in turn enables continuous integration and testability.
 JDBC is simplified due to Dependency Injection and Inversion of Control.
 It is open-source and has no vendor lock-in.

3. What are the different features of Spring Framework?

Following are some of the major features of Spring Framework :

 Lightweight: Spring is lightweight when it comes to size and transparency. 


 Inversion of control (IOC): The objects give their dependencies instead of
creating or looking for dependent objects. This is called Inversion Of Control.
 Aspect oriented Programming (AOP): Aspect oriented programming in
Spring supports cohesive development by separating application business
logic from system services.
 Container: Spring Framework creates and manages the life cycle and
configuration of the application objects.
 MVC Framework: Spring Framework’s MVC web application framework is
highly configurable. Other frameworks can also be used easily instead of
Spring MVC Framework.
 Transaction Management: Generic abstraction layer for transaction
management is provided by the Spring Framework. Spring’s transaction
support can be also used in container less environments.
 JDBC Exception Handling: The JDBC abstraction layer of the Spring offers
an exception hierarchy, which simplifies the error handling strategy.

4. How many modules are there in Spring Framework and what


are they?

There are around 20 modules which are generalized into Core Container, Data
Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation and
Test.

 Spring Core Container – This layer is basically the core of Spring


Framework. It contains the following modules :

a. Spring Core
b. Spring Bean
c. SpEL (Spring Expression Language)
d. Spring Context 

 Data Access/Integration – This layer provides support to interact with the


database. It contains the following modules :

a. JDBC (Java DataBase Connectivity)


b. ORM (Object Relational Mapping)
c. OXM (Object XML Mappers)
d. JMS (Java Messaging Service)
e. Transaction
 Web – This layer provides support to create web application. It contains the
following modules :

a. Web
b. Web – MVC
c. Web – Socket
d. Web – Portlet

 Aspect Oriented Programming (AOP) – In this layer you can use


Advices, Pointcuts etc., to decouplethe code.
 Instrumentation – This layer provides support to class instrumentation and
classloader implementations.
 Test – This layer provides support to testing with JUnit and TestNG.

Few Miscellaneous modules are given below:

 Messaging – This module provides support for STOMP. It also supports an


annotation programming model that is used for routing and processing
STOMP messages from WebSocket clients.
 Aspects – This module provides support to integration with AspectJ.

5. What is a Spring configuration file?

A Spring configuration file is an XML file. This file mainly contains the classes
information. It describes how those classes are configured as well as introduced to
each other. The XML configuration files, however, are verbose and more clean. If it’s
not planned and written correctly, it becomes very difficult to manage in big
projects.

6. What are the different components of a Spring application?

A Spring application, generally consists of following components:

 Interface: It defines the functions.


 Bean class: It contains properties, its setter and getter methods, functions
etc.
 Spring Aspect Oriented Programming (AOP): Provides the functionality of
cross-cutting concerns.
 Bean Configuration File: Contains the information of classes and how to
configure them.
 User program: It uses the function. 
7. What are the major features in different versions of Spring?

Since the release of Spring Framework back in the 2004, many Spring versions
came out in the market. But few of them had some major additions like:

Spring 2.5: This version was released in 2007. It was the first version 
which supported annotations.

Spring 3.0: This version was released in 2009. It made full fledged use of


improvements in Java5 and also provided support to JEE6.

Spring 4.0: This version was released in 2013. This was the first
version to provide full support to Java 8.

8. What are the various ways of using Spring Framework?

Spring Framework can be used in various ways. They are listed as follows:

1.  As a Full-fledged Spring web application.


2. As a third-party web framework, using Spring Frameworks middle-tier.
3.  For remote usage. 
4. As Enterprise Java Bean which can wrap existing POJOs (Plain Old Java
Objects).

The next section of Spring Interview Questions is on Dependency Injection and IoC
container.
Dependency Injection/ IoC Container – Spring Interview
Questions
9. What is Spring IOC Container?

At the core of the Spring Framework, lies the Spring container. The
container creates the object, wires them together, configures them and manages
their complete life cycle. The Spring container makes use of Dependency Injection to
manage the components that make up an application. The container receives
instructions for which objects to instantiate, configure, and assemble by reading the
configuration metadata provided. This metadata can be provided either by XML, Java
annotations or Java code.

10. What do you mean by Dependency Injection? 

In Dependency Injection, you do not have to create your objects but have to
describe how they should be created. You don’t connect your components and
services together in the code directly, but describe which services are needed by
which components in the configuration file. The IoC container will wire them up
together.

11. In how many ways can Dependency Injection be done?

In general, dependency injection can be done in three ways, namely :

 Constructor Injection
 Setter Injection
 Interface Injection

In Spring Framework, only constructor and setter injections are used.


12. Differentiate between constructor injection and setter
injection.

Constructor Injection Setter Injection

There is no partial injection. There can be partial injection.

It doesn’t override the setter property. It overrides the constructor property.

It will create a new instance if any It will not create new instance if any
modification is done. modification is done.

It works better for many properties. It works better for few properties.

13. How many types of IOC containers are there in spring?

a. BeanFactory: BeanFactory is like a factory class that contains a collection of


beans. It instantiates the bean whenever asked for by clients.
b. ApplicationContext: The ApplicationContext interface is built on top of the
BeanFactory interface. It provides some extra  functionality on
top BeanFactory.

14. Differentiate between BeanFactory and ApplicationContext.


BeanFactory ApplicationContext

It is an interface defined in It is an interface defined in


org.springframework.beans.factory.Bea org.springframework.context.Applicatio
nFactory nContext

It uses Lazy initialization It uses Eager/ Aggressive initialization

It explicitly provides a resource object It creates and manages resource


using the syntax objects on its own

It doesn’t supports internationalization It supports internationalization 

It doesn’t supports annotation based


It supports annotation based dependency
dependency    

15.  List some of the benefits of IoC.

Some of the benefits of IoC are:

 It will minimize the amount of code in your application.


 It will make your application easy to test because it doesn’t require any
singletons or JNDI lookup mechanisms in your unit test cases.
 It promotes loose coupling with minimal effort and least intrusive mechanism.
 It supports eager instantiation and lazy loading of the services.
Let’s move on to the next section of Spring Interview Questions, that is Spring
Beans Interview Questions.

Spring Beans – Spring Interview Questions


16. Explain Spring Beans?

 They are the objects that form the backbone of the  user’s application.
 Beans are managed by the Spring IoC container.
 They are instantiated, configured, wired and managed by a Spring IoC
container
 Beans are created with the configuration metadata that the users supply to

the container.

17. How configuration metadata is provided to the Spring


container?

Configuration metadata can be provided to Spring container in following ways:

 XML-Based configuration: In Spring Framework, the dependencies and the


services needed by beans are specified in configuration files which are in XML
format. These configuration files usually contain a lot of bean definitions and
application specific configuration options. They generally start with a bean
tag. For example:

1 <bean id="studentbean" class="org.edureka.firstSpring.StudentBean">


2  <property name="name" value="Edureka"></property>
3 </bean>

 Annotation-Based configuration: Instead of using XML to describe a bean


wiring, you can configure the bean into the component class itself by using
annotations on the relevant class, method, or field declaration. By default,
annotation wiring is not turned on in the Spring container. So, you need to
enable it in your Spring configuration file before using it. For example:

1 <beans>
2 <context:annotation-config/>
3 <!-- bean definitions go here -->

4 </beans>

 Java-based configuration: The key features in Spring Framework’s new


Java-configuration support are @Configuration annotated classes and @Bean
annotated methods. 

1. @Bean annotation plays the same role as the <bean/> element. 


2.@Configuration classes allows to define inter-bean dependencies by simply calling
other @Bean methods in the same class.
For example:
1 @Configuration
2 public class StudentConfig
3 {

4 @Bean

5 public StudentBean myStudent()

{ return new StudentBean(); }


6
}
7

18. How many bean scopes are supported by Spring?

The Spring Framework supports five scopes. They are:

 Singleton: This provides scope for the bean definition to single instance per
Spring IoC container.
 Prototype: This provides scope for a single bean definition to have any
number of object instances.
 Request: This provides scope for a bean definition to an HTTP-request. 
 Session: This provides scope for a bean definition to an HTTP-session. 
 Global-session: This provides scope for a bean definition to an Global HTTP-
session. 

The last three are available only if the users use a web-aware ApplicationContext.

19. What is the Bean life cycle in Spring Bean Factory Container?

Bean life cycle in Spring Bean Factory Container is as follows:

1. The Spring container instantiates the bean from the bean’s definition in the
XML file.
2. Spring populates all of the properties using the dependency injection, as
specified in the bean definition.
3. The factory calls setBeanName() by passing the bean’s ID, if the bean
implements the BeanNameAware interface.
4. The factory calls setBeanFactory() by passing an instance of itself, if the bean
implements the BeanFactoryAware interface.
5. preProcessBeforeInitialization() methods are called if there are any
BeanPostProcessors associated with the bean.
6. If an init-method is specified for the bean, then it will be called.
7. Finally, postProcessAfterInitialization() methods will be called if there are any
BeanPostProcessors associated with the bean.

To understand it in better way check the below diagram:


20. Explain inner beans in Spring.

A bean can be declared as an inner bean only when it is used as a property of


another bean. For defining a bean, the Spring’s XML based configuration metadata
provides the use of <bean> element inside the <property> or <constructor-
arg>. Inner beans are always anonymous and they are always scoped as
prototypes. For example, let’s say we have one Student class having reference
of Person class. Here we will be creating only one instance of Person class and use it
inside Student.

Here’s a Student class followed by bean configuration file:

Student.java
1 public class Student
2

3 {

private Person person;


4
//Setters and Getters
5
}
6
public class Person
7
{
8
private String name;
9 private String address;
10 //Setters and Getters

11 }

studentbean.xml
1
<bean id=“StudentBean" class="com.edureka.Student">
2 <property name="person">
3 <!--This is inner bean -->
4 <bean class="com.edureka.Person">

5 <property name="name" value=“Scott"></property>

6 <property name="address" value=“Bangalore"></property>

</bean>
7
</property>
8
</bean>
9

21. Define Bean Wiring.

When beans are combined together within the Spring container, it’s called wiring or
bean wiring. The Spring container needs to know what beans are needed and how
the container should use dependency injection to tie the beans together, while
wiring beans.
22. What do you understand by auto wiring and name the
different modes of it?

The Spring container is able to autowire relationships between the collaborating


beans. That is, it is possible to let Spring resolve collaborators for your bean
automatically by inspecting the contents of the BeanFactory.
Different modes of bean auto-wiring are:

a. no: This is default setting which means no autowiring. Explicit bean reference


should be used for wiring.
b. byName: It injects the object dependency according to name of the bean. It
matches and wires its properties with the beans defined by the same names
in the XML file.
c. byType: It injects the object dependency according to type. It matches and
wires a property if its type matches with exactly one of the beans name in
XML file.
d. constructor: It injects the dependency by calling the constructor of the
class. It has a large number of parameters.
e. autodetect: First the container tries to wire using autowire by constructor, if
it can’t then it tries to autowire by byType.

23. What are the limitations with auto wiring?

Following are some of the limitations you might face with auto wiring:

 Overriding possibility: You can always specify dependencies using


<constructor-arg> and <property> settings which will override autowiring.
  Primitive data type: Simple properties such as primitives, Strings and
Classes can’t be autowired.
 Confusing nature: Always prefer using explicit wiring because autowiring is
less precise.

In the next section, we will discuss on Spring Annotations Interview Questions.


Spring Annotations – Spring Interview Questions
24. What do you mean by  Annotation-based container
configuration?

Instead of using XML to describe a bean wiring, the developer moves the
configuration into the component class itself by using annotations on the relevant
class, method, or field declaration. It acts as an alternative to XML setups. For
example:
1 @Configuration
2 public class AnnotationConfig
3 {

4 @Bean

5 public MyDemo myDemo()

 { return new MyDemoImpll(); }


6
}
7

 
25. How annotation wiring can be turned on in Spring?

By default, Annotation wiring is not turned on in the Spring container. Thus, to use


annotation based wiring we must enable it in our Spring configuration file by
configuring <context:annotation-config/> element. For example:
1 <beans xmlns="http://www.springframework.org/schema/beans"
2 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

3 xmlns:context="http://www.springframework.org/schema/context">

4 <context:annotation-config/>

5 <beans ………… />

</beans>
6
26. What’s the difference between @Component, @Controller,
@Repository & @Service annotations in Spring?

@Component: This marks a java class as a bean. It is a generic stereotype for any


Spring-managed component. The component-scanning mechanism of spring now
can pick it up and pull it into the application context.
@Controller: This marks a class as a Spring Web MVC controller. Beans marked
with it are automatically imported into the Dependency Injection container.

@Service: This annotation is a specialization of the component annotation. It


doesn’t provide any additional behavior over the @Component annotation. You
can use @Service over @Component in service-layer classes as it specifies intent in
a better way.

@Repository: This annotation is a specialization of the @Component annotation


with similar use and functionality. It provides additional benefits specifically for
DAOs. It imports the DAOs into the DI container and makes the unchecked
exceptions eligible for translation into Spring DataAccessException.

27. What do you understand by @Required annotation?

@Required is applied to bean property setter methods. This annotation simply


indicates that the affected bean property must be populated at the configuration
time with the help of an explicit property value in a bean definition or with
autowiring. If the affected bean property has not been populated, the container will
throw BeanInitializationException.

For example:
1
public class Employee
2 {
3 private String name;
4 @Required

5 public void setName(String name)

6 {this.name=name; }

public string getName()


7
{ return name; }
8
}
9

28. What do you understand by @Autowired annotation?

The @Autowired annotation provides more accurate control over where and how


autowiring should be done. This annotation is used to autowire bean on the setter
methods, constructor, a property or methods with arbitrary names or multiple
arguments. By default, it is a type driven injection.
For Example:
1
public class Employee
2 {
3 private String name;
4 @Autowired

5 public void setName(String name)

6 {this.name=name; }

public string getName()


7
{ return name; }
8
}
9

29. What do you understand by @Qualifier annotation?

When you create more than one bean of the same type and want to wire only one of
them with a property  you can use the @Qualifier annotation along
with @Autowired to remove the ambiguity by specifying which exact bean should
be wired.

For example, here we have two classes, Employee and EmpAccount respectively. In
EmpAccount, using @Qualifier its specified that bean with id emp1 must be wired.

Employee.java
1
public class Employee
2 {
3 private String name;
4 @Autowired

5 public void setName(String name)

6 { this.name=name; }

public string getName()


7
{ return name; }
8
}
9

EmpAccount.java
1 public class EmpAccount

2 {
3
private Employee emp;
4 @Autowired
5 @Qualifier(emp1)

6 public void showName()

7 {

8 System.out.println(“Employee name : ”+emp.getName);

}
9
}
10

30.  What do you understand by @RequestMapping annotation?

@RequestMapping annotation is used for mapping a particular HTTP request method


to a specific class/ method in controller that will be handling the respective
request. This annotation can be applied at both levels:

 Class level : Maps the URL of the request


 Method level: Maps the URL as well as HTTP request method

Next section of Spring Interview Questions is on Data Access.

Data Access – Spring Interview Questions


31. Describe Spring DAO support?

The Data Access Object (DAO) support in Spring makes it easy to work with data
access technologies like JDBC, Hibernate or JDO in a consistent way. This allows one
to switch between the persistence technologies easily. It also allows you to code
without worrying about catching exceptions that are specific to each of these
technology.

32. Name the exceptions thrown by the Spring DAO classes.

See the below diagram, it depicts all the Spring DAO classes in the hierarchical
order.
33.  Which classes are present in spring JDBC API?

Classes present in JDBC API are as follows:

a. JdbcTemplate
b. SimpleJdbcTemplate
c. NamedParameterJdbcTemplate
d. SimpleJdbcInsert
e. SimpleJdbcCall

34. What are the ways by which Hibernate can be accessed using
Spring?

There are two ways by which we can access Hibernate using Spring:

a. Inversion of Control with a Hibernate Template and Callback


b. Extending HibernateDAOSupport and Applying an AOP Interceptor node
35. Name the types of transaction management that Spring
supports.

Two types of transaction management are supported by Spring. They are:

a. Programmatic transaction management: In this, the transaction is


managed with the help of programming. It provides you extreme flexibility,
but it is very difficult to maintain.
b. Declarative transaction management: In this, the transaction
management is separated from the business code. Only annotations or XML
based configurations are used to manage the transactions.

36. What are the different ORM’s supported by Spring?

Different ORM’s supported by Spring are depicted via the below diagram:

The next section of Spring interview questions discusses on Spring AOP Interview
Questions.

Aspect Oriented Programming (AOP) – Spring Interview


Questions
37. Describe AOP.

Aspect-oriented programming or AOP is a programming technique which allows


programmers to modularize crosscutting concerns or behavior that cuts across the
typical divisions of responsibility. Examples of cross-cutting concerns can be logging
and transaction management. The core of AOP is an aspect. It encapsulates
behaviors that can affect multiple classes into reusable modules.
38. What do you mean by Aspect?

Aspect is a modularization of concern which cuts across multiple objects. Transaction


management is a good example of a crosscutting concern in J2EE applications.
Aspects are implemented using regular classes or regular classes annotated with the
@Aspect annotation in Spring Framework.

39. Explain JoinPoint.

A point during the execution of a program is called JoinPoint, such as the execution
of a method or the handling of an exception. In Spring AOP, a joinpoint always
represents a method execution.

40. What is an Advice?

An Action taken by an aspect at a particular joinpoint is known as an Advice.


Spring AOP uses an advice as an interceptor, maintaining a chain of interceptors
“around” the join point.
41. What are the different types of Advices?

a. Before: These types of advices execute before the joinpoint methods and are


configured using @Before annotation mark.
b. After returning: These types of advices execute after the joinpoint methods
completes executing normally and are configured using
@AfterReturning annotation mark.
c. After throwing:  These types of advices execute only if joinpoint method
exits by throwing an exception and are configured using
@AfterThrowing annotation mark.
d. After (finally): These types of advices execute after a joinpoint method,
regardless of the method’s exit whether normally or exceptional return and
are configured using @After annotation mark.
e. Around: These types of advices execute before and after a joinpoint and are
configured using @Around annotation mark.

42. Point out the difference between concern and cross-cutting


concern in Spring AOP?

The concern is the behavior we want to have in a particular module of an


application. It can be defined as a functionality we want to implement. 

The cross-cutting concern is a concern which is applicable throughout the


application. This affects the entire application. For example, logging, security and
data transfer are the concerns needed in almost every module of an application,
thus they are the cross-cutting concerns.
43. What are the different AOP implementations?

Different AOP implementations are depicted by the below diagram:


44. What are the difference between Spring AOP and AspectJ
AOP?

Spring AOP AspectJ AOP

Compile time weaving through AspectJ


Runtime weaving through proxy is done
Java tools is done 

It supports only method level PointCut It suports field level Pointcuts

It is schema based and Annotation


It is DTD based 
configuration

45. What do you mean by Proxy in Spring Framework?

An object which is created after applying advice to a target object is known as a


Proxy. In case of client objects the target object and the proxy object are the same.
46. In Spring, what is Weaving?

The process of linking an aspect with other application types or objects to create an
advised object is called Weaving. In Spring AOP, weaving is performed at runtime.
Refer the below diagram:

The last section of Spring


interview questions is on Spring MVC Interview Questions.
MVC (Model-View-Controller) – Spring Interview Questions

47. What do you mean by Spring MVC framework?

The Spring web MVC framework provides model-view-controller architecture and


ready to use components that are used to develop flexible and loosely coupled web
applications. The MVC pattern helps in separating the different aspects of the
application like input logic, business logic and UI logic, while providing a loose
coupling between all these elements.

48. Describe DispatcherServlet.

The DispatcherServlet is the core of Spring Web MVC framework. It handles all the
HTTP requests and responses. The DispatcherServlet receives the entry of handler
mapping from the configuration file and forwards the request to the controller. The
controller then returns an object of Model And View. The DispatcherServlet checks
the entry of view resolver in the configuration file and calls the specified view
component.

49. Explain WebApplicationContext.

The WebApplicationContext is an extension of the plain ApplicationContext. It has


some extra features that are necessary for web applications. It differs from a
normal ApplicationContext in terms of its capability of resolving themes and in
deciding which servlet it is associated with.
50. In Spring MVC framework, what is controller?

Controllers provide access to the application behavior. These behaviors are generally
defined through a service interface. Controllers interpret the user input and transform it
into a model which is represented to the user by the view. In Spring, controller is
implemented in a very abstract way. It also enables you to create a wide variety of
controllers.

  

ng-app - To initialize the Angular Application.


ng-init - To initialize the Angular Application data.
ng-model - To bind the html tags (input, select, textarea) to Angular
Application Data.
<div data-ng-app="" data-ng-
init="names=['Web','Technology','Experts','Notes']">
<b>Loop Example:</b>
<br />
<ul>
<li data-ng-repeat="x in names">
{{ x }}
</li>
</ul>

String 1: <input ng-model="str1" type="text" /><br />


String 2: <input ng-model="str2" type="text" /><br />
Full String <b> {{fullString()}}</b>
</div>
<script>
function StrControllerExample($scope) {
$scope.str1 = "Web",
$scope.str2 = "Technology",
$scope.fullString = function() {
return $scope.str1+ " " + $scope.str2;
}
}
</script>

</div>

Java 8

Lambda Exp example

func ( x-> x%2 ) ===== func(int x){ int y = x%2; return y;}

How will you sort a list of string using Java 8 lambda expression?
Following code sorts a list of string using Java 8 lambda expression:

//sort using java 8


private void sortUsingJava8(List<String> names){
Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
}

Stream API

Following code will print the highest number present in a list.

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);


IntSummaryStatistics stats = integers.stream().mapToInt((x) −>
x).summaryStatistics();
System.out.println("Lowest number in List : " + stats.getMin());

Finally block if executed and then try block -----if return inside try

If return statement in finally block then return part of try and

catch is skipped
Algorithm to find if linked list contains loops or cycles
Two pointers, fast and slow is used while iterating over linked list. Fast pointer moves two nodes in each
iteration, while slow pointer moves to one node. If linked list contains loop or cycle than both fast and slow pointer
will meet at some point during iteration. If they don't meet and fast or slow will point to null, then linked list is not
cyclic and it doesn't contain any loop.

public class MySingletonBean {


@Component – Indicates a auto scan component.
@Repository – Indicates DAO component in the persistence layer.
@Service – Indicates a Service component in the business layer.
@Controller – Indicates a controller component in the presentation layer.

INJECTING PROTOTYPE TO SIGLETON

WRONG WAY –HERE ONLY 1 INSTANCE OF PROTOTYPE CREATED FOR ALL REQUESTS
@Autowired
private MyPrototypeBean prototypeBean;

public void showMessage(){


System.out.println("Hi, the time is "+prototypeBean.getDateTime());
}
}

RIGHT WAY—A NEW INSTANCE OF PROTOTYPE WILL


BE RETURNED FOR EACH REQUES TO SINGLETON BEAN
public class MySingletonBean {

@Autowired
private ApplicationContext applicationContext;

public void showMessage(){


MyPrototypeBean bean =
applicationContext.getBean(MyPrototypeBean.class);
System.out.println("Hi, the time is "+bean.getDateTime());
}
}

RIGHT Way—using lookup method injection

@Component

public class MySingletonBean {


public void showMessage(){

MyPrototypeBean bean = getPrototypeBean();

//each time getPrototypeBean() call

//will return new instance

Printing Even and Odd using two Threads in Java

@Lookup

public MyPrototypeBean getPrototypeBean(){

//spring will override this method

return null;

public class ThreadEvenOdd {


static int cnt=0;
public static void main(String[] args) {

Thread t1 = new Thread(new Runnable() {

@Override
public void run() {
synchronized(this) {
while(cnt<101) {
if(cnt%2==0) {
System.out.print(cnt+" ");
cnt++;
}
notifyAll();
}
}
}

});
Thread t2 = new Thread(new Runnable() {

@Override
public void run() {
synchronized(this) {
while(cnt<101) {
if(cnt%2==1) {
System.out.print(cnt+" ");
cnt++;
}
notifyAll();
}
}
}
});

t1.start();
t2.start();
}
}

public class OddAndEvenThreadProblems {


private static Integer i = 0;

public static void main(String[] args) {


new EvenClass().start();
new OddClass().start();

public static class EvenClass extends Thread {

public void run() {


while (i < 10) {
synchronized (i) {
if (i % 2 == 0 ) {
try {
Thread.sleep(1000);
System.out.println(" EvenClass " + i);
i = i + 1;
} catch (Exception e) {
e.printStackTrace();
}

}
}
}
}
}

public static class OddClass extends Thread {

@Override
public void run() {
while (i < 10) {
synchronized (i) {
if (i % 2 == 1) {
try {
Thread.sleep(1000);
System.out.println(" OddClass " + i);
i = i + 1;
} catch (Exception e) {
e.printStackTrace();
}

}
}
}
}
}
}

OUTPUT will be :-

EvenClass 0
OddClass 1
EvenClass 2
OddClass 3
EvenClass 4
OddClass 5
EvenClass 6
OddClass 7
EvenClass 8
OddClass 9

public class PrintNumbers extends Thread {

Object lock;

PrintNumbers(Object lock) {
this.lock = lock;
}

public static void main(String ar[]) {


Object obj = new Object();
// This constructor is required for the identification of wait/notify
// communication
PrintNumbers odd = new PrintNumbers(obj);
PrintNumbers even = new PrintNumbers(obj);
odd.setName("Odd");
even.setName("Even");
even.start();
odd.start();

@Override
public void run() {
for(int i=0;i<=100;i++) {

synchronized (lock) {

if (Thread.currentThread().getName().equals("Even")) {

if(i % 2 == 0 ){
System.out.println(Thread.currentThread().getName() + " - "+ i);
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (i % 2 != 0 ) {
lock.notify();
}
}

if (Thread.currentThread().getName().equals("Odd")) {

if(i % 2 == 1 ){
System.out.println(Thread.currentThread().getName() + " - "+ i);
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
else if (i % 2 != 1 ) {
lock.notify();
}
}

}
}
}
}

You might also like