Final Technical Notes
Final Technical Notes
Final Technical Notes
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:
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
3 {
5 Node previousNode=null;
6 Node nextNode;
7 while(currentNode!=null)
8 {
9 nextNode=currentNode.next;
11 currentNode.next=previousNode;
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
4 return node;
5 }
6
8 node.next.next = node;
9 node.next = null;
10 return remaining;
11 }
12
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;
synchronized(str1){
synchronized(str2){
System.out.println(str1 + str2);
};
while(true){
synchronized(str2){
synchronized(str1){
System.out.println(str2 + str1);
};
mdl.trd1.start();
mdl.trd2.start();
}
}
properties.load(stream);
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(){}
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.
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
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.
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.
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
<protocol>://<service-name>/<ResourceType>/<ResourceID>
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
POST : Should create new resource. Ideally return JSON with link to newly created resource. Same
return codes as get possible. In
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.
Useful methods:
XX:+UseParallelGC
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"));)
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.
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
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;
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.
There are around 20 modules which are generalized into Core Container, Data
Access/Integration, Web, AOP (Aspect Oriented Programming), Instrumentation and
Test.
a. Spring Core
b. Spring Bean
c. SpEL (Spring Expression Language)
d. Spring Context
a. Web
b. Web – MVC
c. Web – Socket
d. Web – Portlet
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.
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 4.0: This version was released in 2013. This was the first
version to provide full support to Java 8.
Spring Framework can be used in various ways. They are listed as follows:
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.
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.
Constructor Injection
Setter Injection
Interface Injection
It will create a new instance if any It will not create new instance if any
modification is done. modification is done.
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.
1 <beans>
2 <context:annotation-config/>
3 <!-- bean definitions go here -->
4 </beans>
4 @Bean
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.
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.
Student.java
1 public class Student
2
3 {
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">
</bean>
7
</property>
8
</bean>
9
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?
Following are some of the limitations you might face with auto wiring:
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
25. How annotation wiring can be turned on in Spring?
3 xmlns:context="http://www.springframework.org/schema/context">
4 <context:annotation-config/>
</beans>
6
26. What’s the difference between @Component, @Controller,
@Repository & @Service annotations in Spring?
For example:
1
public class Employee
2 {
3 private String name;
4 @Required
6 {this.name=name; }
6 {this.name=name; }
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
6 { this.name=name; }
EmpAccount.java
1 public class EmpAccount
2 {
3
private Employee emp;
4 @Autowired
5 @Qualifier(emp1)
7 {
}
9
}
10
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.
See the below diagram, it depicts all the Spring DAO classes in the hierarchical
order.
33. Which classes are present in spring JDBC API?
a. JdbcTemplate
b. SimpleJdbcTemplate
c. NamedParameterJdbcTemplate
d. SimpleJdbcInsert
e. SimpleJdbcCall
34. What are the ways by which Hibernate can be accessed using
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.
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?
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:
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.
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.
</div>
Java 8
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:
Stream API
Finally block if executed and then try block -----if return inside try
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.
WRONG WAY –HERE ONLY 1 INSTANCE OF PROTOTYPE CREATED FOR ALL REQUESTS
@Autowired
private MyPrototypeBean prototypeBean;
@Autowired
private ApplicationContext applicationContext;
@Component
@Lookup
return null;
@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();
}
}
}
}
}
}
}
@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
Object lock;
PrintNumbers(Object lock) {
this.lock = lock;
}
@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();
}
}
}
}
}
}