Java Skills Flashcards

1
Q

What are the important features of Java 8 release?

A

The important features of Java 8 release are:
1. Interface can have default and static methods
2. Functional interfaces(Predicate, Consumer, Supplier, Function) and Lambda Expressions
3. Java Stream API for collection classes
4. Java Date Time API

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are Collection related features in Java 8?

A

Java 8 has brought major changes in the Collection API. Some of the changes are:
1. Java Stream API for collection classes for supporting sequential as well as parallel processing
2. Iterable interface is extended with forEach() default method that we can use to iterate over a collection. It is very helpful when used with lambda expressions because it’s argument Consumer is a function interface.
3. Miscellaneous Collection API improvements such as forEachRemaining(Consumer action) method in Iterator interface, Map replaceAll(), compute(), merge() methods.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is overloading and overriding in java?

A

When we have more than one method with same name in a single class but the arguments are different, then it is called as method overloading.
Overriding concept comes in picture with inheritance when we have two methods with same signature, one in parent class and another in child class. We can use @Override annotation in the child class overridden method to make sure if parent class method is changed, so as child class

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is an interface?

A

Interfaces provide a way to achieve abstraction in java and used to define the contract for the subclasses to implement.
A java class can implement multiple interfaces.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is an abstract class?

A

Abstract classes are used in java to create a class with some default method implementation for subclasses. An abstract class can have abstract method without body and it can have methods with implementation also.
Abstract classes can’t be instantiated and mostly used to provide base for sub-classes to extend and implement the abstract methods and override or use the implemented methods in abstract class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the difference between abstract class and interface?

A

abstract keyword is used to create abstract class whereas interface is the keyword for interfaces.
Abstract classes can have method implementations whereas interfaces can’t.
A class can extend only one abstract class but it can implement multiple interfaces.
We can run abstract class if it has main() method whereas we can’t run an interface.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is static keyword?

A

The static keyword can be used with class level variables to make it global so all the objects will share the same variable.
The static keyword can be used with methods also. A static method can access only static variables of the class and invoke only static methods of the class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is static block?

A

Java static block is the group of statements that gets executed when the class is loaded into memory by Java ClassLoader. It is used to initialize static variables of the class and is executed before main method at the time of classloading. Mostly it’s used to create static resources when class is loaded.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is try-with-resources in java?

A

One of the Java 7 features is try-with-resources statement for automatic resource management. Before Java 7, there was no auto resource management and we should explicitly close the resource. Usually, it was done in the finally block of a try-catch statement. This approach used to cause memory leaks when we forgot to close the resource. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.
From Java 7, we can create resources inside try block and use it. Java takes care of closing it as soon as try-catch block gets finished.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is multi-catch block in java?

A

Java 7 one of the improvement was multi-catch block where we can catch multiple exceptions in a single catch block. This makes are code shorter and cleaner when every catch block has similar code.
If a catch block handles multiple exception, you can separate them using a pipe (|) and in this case exception parameter (ex) is final, so you can’t change it.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is Enum in Java?

A

Enum is a type in Java. Its fields consists of fixed set of constants. For example, in Java we can create Direction as enum with fixed fields as EAST, WEST, NORTH, SOUTH.
enum is the keyword to create an enum type and similar to class. Enum constants are implicitly static and final.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What is composition in java?

A

Composition is the design technique to implement has-a relationship in classes. We can use Object composition for code reuse.
Java composition is achieved by using instance variables that refers to other objects. Benefit of using composition is that we can control the visibility of other object to client classes and reuse only what we need.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is ternary operator in java?

A

Java ternary operator is the only conditional operator that takes three operands. It’s a one liner replacement for if-then-else statement and used a lot in java programming. We can use ternary operator if-else conditions or even switch conditions using nested ternary operators.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is Garbage Collection?

A

Garbage Collection is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects. In Java, process of deallocating memory is handled automatically by the garbage collector.
We can run the garbage collector with code Runtime.getRuntime().gc() or use utility method System.gc().
Types : Serial, Parallel, CMS(Concurrent Mark Sweep), G1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is difference between Heap and Stack Memory?

A

Major difference between Heap and Stack memory are as follows:
* Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
* Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space.
* Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is an Iterator?

A

Iterator interface provides methods to iterate over any Collection. We can get iterator instance from a Collection using iterator() method. Iterator takes the place of Enumeration in the Java Collections Framework. Iterators allow the caller to remove elements from the underlying collection during the iteration. Java Collection iterator provides a generic way for traversal through the elements of a collection and implements Iterator Design Pattern.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What is the importance of hashCode() and equals() methods?

A

HashMap uses Key object hashCode() and equals() method to determine the index to put the key-value pair. These methods are also used when we try to get value from HashMap. If these methods are not implemented correctly, two different Key’s might produce same hashCode() and equals() output and in that case rather than storing it at different location, HashMap will consider them same and overwrite them.
Similarly all the collection classes that doesn’t store duplicate data use hashCode() and equals() to find duplicates, so it’s very important to implement them correctly. The implementation of equals() and hashCode() should follow these rules.
* If o1.equals(o2), then o1.hashCode() == o2.hashCode()should always be true.
* If o1.hashCode() == o2.hashCode is true, it doesn’t mean that o1.equals(o2) will be true.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What is Comparable and Comparator interface?

A

Java provides Comparable interface which should be implemented by any custom class if we want to use Arrays or Collections sorting methods. Comparable interface has compareTo(T obj) method which is used by sorting methods. We should override this method in such a way that it returns a negative integer, zero, or a positive integer if “this” object is less than, equal to, or greater than the object passed as argument.
But, in most real life scenarios, we want sorting based on different parameters. For example, as a CEO, I would like to sort the employees based on Salary, an HR would like to sort them based on the age. This is the situation where we need to use Comparator interface because Comparable.compareTo(Object o) method implementation can sort based on one field only and we can’t chose the field on which we want to sort the Object.
Comparator interface compare(Object o1, Object o2) method need to be implemented that takes two Object argument, it should be implemented in such a way that it returns negative int if first argument is less than the second one and returns zero if they are equal and positive int if first argument is greater than second one.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What is Java PriorityQueue?

A

PriorityQueue is an unbounded queue based on a priority heap and the elements are ordered in their natural order or we can provide Comparator for ordering at the time of creation. PriorityQueue doesn’t allow null values and we can’t add any object that doesn’t provide natural ordering or we don’t have any comparator for them for ordering. Java PriorityQueue is not thread-safe and provided O(log(n)) time for enqueuing and dequeuing operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

SOLID Class Design Principles

A
  • Single Responsibility Principles(SRP) : One class should have one and only one reasonability.
    ex) If we have to implement customers logic, we can make Customer and Account class. Both have single responsibility to store their specific information. If we want to change state of Person then we do not need to modify the class Account and vice-versa.
  • Open Closed Principle(OCP) : Software components should be open for extension, but closed modification.
    ex) Spring framework has class DispatcherServlet. This class acts as front controller for String based web applications. To use this class, we are not required to modify this class. All we need is to pass initialization parameters and we can extend it’s functionality the way we want. Decorator pattern.
  • Liskov’s Substitution Principle(LSP) : Derived types must be completely substitutable for their base types.
    Interface Segregation Principle(ISP) : Clients should not be forced to implement unnecessary methods which they will not use.
  • Dependency Inversion Principle(DIP) : Depend on abstraction, not on concretions.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Singleton

A

Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.
* The singleton class must provide a global access point to get the instance of the class.
* Singleton pattern is used for logging, drivers objects, caching and thread pool.
* Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc.
* Singleton design pattern is used in core java classes also, for example java.lang.Runtime, java.awt.Desktop.

Implementation of Singleton Pattern.
* Private constructor to restrict instantiation of the class from other classes.
* Private static variable of the same class that is the only instance of the class.
* Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.

To avoid this extra overhead every time, double checked locking principle is used. In this approach, the synchronized block is used inside the if condition with an additional check to ensure that only one instance of a singleton class is created.

Below code snippet provides the double-checked locking implementation.

package net.glenn.singleton;

public class ThreadSafeSingleton {

    private static ThreadSafeSingleton instance;    
    private ThreadSafeSingleton(){}
        
    public static ThreadSafeSingleton getInstanceUsingDoubleLocking() {
        if(instance == null){
            synchronized (ThreadSafeSingleton.class) {
                if(instance == null){
                    instance = new ThreadSafeSingleton();
                }
             }
        }
        return instance;
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Strategy Pattern

A

Strategy pattern in quite useful for implementing set of related algorithms e.g. compression algorithms, filtering strategies etc. Strategy design pattern allows you to create Context classes, which uses Strategy implementation classes for applying business rules. This pattern follows open closed design principle and quite useful in Java.
One of a good example of Strategy pattern from JDK itself is a Collections.sort() method and Comparator interface, which is a strategy interface and defines a strategy for comparing objects. Because of this pattern, we don’t need to modify sort() method (closed for modification) to compare any object, at the same time we can implement Comparator interface to define new comparing strategy (open for extension).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Observer Pattern

A

Observer pattern is based upon notification, there are two kinds of object Subject and Observer. Whenever there is change on subject’s state observer will receive notification.
For example, The ApplicationEvent class and ApplicationListener interface of Spring enables event handling in Spring ApplicationContext. When you deploy a bean that implements the ApplicationListener interface, it will receive an ApplicationEvent every time the ApplicationEvent is published by an event publisher. Here, the event publisher is the subject and the bean that implements ApplicationListener is the observer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Factory Pattern

A

Factory Method - Defines an interface for creating objects, but let subclasses to decide which class to instantiate and Refers to the newly created object through a common interface.
ex) java.util.Calendar, ResourceBundle and NumberFormat :: getInstance(), valueOf() method in wrapper classes like Boolean, Integer etc.
Abstract Factory - Offers the interface for creating a family of related objects, without explicitly specifying their classes.
ex) java.sql.Connection::createStatement()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

JOIN

A

INNER JOIN (a.k.a. “simple join”): Returns all rows for which there is at least one match in BOTH tables. This is the default type of join if no specific JOIN type is specified.
LEFT(RIGHT) JOIN (or LEFT(RIGHT) OUTER JOIN): Returns all rows from the left(right) table, and the matched rows from the right(left) table; i.e., the results will contain all records from the left(right) table, even if the JOIN condition doesn’t find any matching records in the right(left) table. This means that if the ON clause doesn’t match any records in the right(left) table, the JOIN will still return a row in the result for that record in the left(right) table, but with NULL in each column from the right(left) table.

26
Q

What are different Clauses used in SQL?

A

Clauses used in SQL
WHERE Clause: This clause is used to define the condition, extract and display only those records which fulfill the given condition
GROUP BY Clause: It is used with SELECT statement to group the result of the executed query using the value specified in it. It matches the value with the column name in tables and groups the end result accordingly.
HAVING Clause: This clause is used in association with GROUP BY clause. It is applied to the each group of result or the entire result as single group and much similar as WHERE clause, the only difference is you cannot use it without GROUP BY clause
ORDER BY Clause: This clause is to define the order of the query output either in ascending (ASC) or in descending (DESC) order. Ascending (ASC) is the default one but descending (DESC) is set explicitly.
USING Clause: USING clause comes in use while working with SQL Joins. It is used to check equality based on columns when tables are joined. It can be used instead ON clause in Joins.

27
Q

What is Normalization? How many Normalization forms are there?

A

Normalization is used to organize the data in such manner that data redundancy will never occur in the database and avoid insert, update and delete anomalies.
There are 5 forms of Normalization
First Normal Form (1NF): It removes all duplicate columns from the table. Creates table for related data and identifies unique column values
Second Normal Form (2NF): Follows 1NF and creates and places data subsets in an individual table and defines relationship between tables using primary key
Third Normal Form (3NF): Follows 2NF and removes those columns which are not related through primary key
Fourth Normal Form (4NF): Follows 3NF and do not define multi-valued dependencies. 4NF also known as BCNF

28
Q

What is SQL injection?

A

SQL injection is an attack by malicious users in which malicious code can be inserted into strings that can be passed to an instance of SQL server for parsing and execution. All statements have to checked for vulnerabilities as it executes all syntactically valid queries that it receives. Even parameters can be manipulated by the skilled and experienced attackers.

29
Q

What are the methods used to protect against SQL injection attack?

A

Following are the methods used to protect against SQL injection attack:
* Use Parameters for Stored Procedures
* Filtering input parameters
* Use Parameter collection with Dynamic SQL
* In like clause, user escape characters

30
Q

What are the important benefits of using Hibernate Framework?

A

Some of the important benefits of using hibernate framework are:
* Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
* Hibernate framework provides support for XML as well as JPA annotations, that makes our code implementation independent.
* Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism and association.
* Hibernate is an open source project from Red Hat Community and used worldwide. This makes it a better choice than others because learning curve is small and there are tons of online documentations and help is easily available in forums.
* Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating hibernate with Spring applications.
* Hibernate supports lazy initialization using proxy objects and perform actual database queries only when it’s required.
* Hibernate cache helps us in getting better performance.
* For database vendor specific feature, hibernate is suitable because we can also execute native sql queries.
* Overall hibernate is the best choice in current market for ORM tool, it contains all the features that you will ever need in an ORM tool.

31
Q

Name some important interfaces of Hibernate framework?

A

Some of the important interfaces of Hibernate framework are:
* SessionFactory (org.hibernate.SessionFactory): SessionFactory is an immutable thread-safe cache of compiled mappings for a single database. We need to initialize SessionFactory once and then we can cache and reuse it. SessionFactory instance is used to get the Session objects for database operations.
* Session (org.hibernate.Session): Session is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It wraps JDBC java.sql.Connection and works as a factory for org.hibernate.Transaction. We should open session only when it’s required and close it as soon as we are done using it. Session object is the interface between java application code and hibernate framework and provide methods for CRUD operations.
* Transaction (org.hibernate.Transaction): Transaction is a single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC or JTA transaction. A org.hibernate.Session might span multiple org.hibernate.Transaction in some cases.

32
Q

What is difference between Hibernate Session get() and load() method?

A

Hibernate session comes with different methods to load data from database.
get and load are most used methods, at first look they seems similar but there are some differences between them.
get() loads the data as soon as it’s called whereas load() returns a proxy object and loads data only when it’s actually required, so load() is better because it support lazy loading.
Since load() throws exception when data is not found, we should use it only when we know data exists.
We should use get() when we want to make sure data exists in the database.

33
Q

What is hibernate caching? Explain Hibernate first level cache?

A

As the name suggests, hibernate caches query data to make our application faster. Hibernate Cache can be very useful in gaining fast application performance if used correctly. The idea behind cache is to reduce the number of database queries, hence reducing the throughput time of the application.

Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it. However hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely. ( evict(), clear() ).
Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.

34
Q

What are different states of an entity bean?

A

An entity bean instance can exist is one of the three states.
* Transient: When an object is never persisted or associated with any session, it’s in transient state. Transient instances may be made persistent by calling save(), persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete().
* Persistent: When an object is associated with a unique session, it’s in persistent state. Any instance returned by a get() or load() method is persistent.
* Detached: When an object is previously persistent but not associated with any session, it’s in detached state. Detached instances may be made persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().

35
Q

What is difference between Hibernate save(), saveOrUpdate() and persist() methods?

A
  • save() : Hibernate save can be used to save entity to database. Problem with save() is that it can be invoked without a transaction and if we have mapping entities, then only the primary object gets saved causing data inconsistencies. Also save returns the generated id immediately.
  • persist() : Hibernate persist is similar to save with transaction. I feel it’s better than save because we can’t use it outside the boundary of transaction, so all the object mappings are preserved. Also persist doesn’t return the generated id immediately, so data persistence happens when needed.
  • saveOrUpdate() : Hibernate saveOrUpdate results into insert or update queries based on the provided data. If the data is present in the database, update query is executed. We can use saveOrUpdate() without transaction also, but again you will face the issues with mapped objects not getting saved if session is not flushed.
36
Q

HTTP methods used in REST based architecture?

A

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. Idempotent.
* DELETE − Used to remove a resource. Idempotent.
* POST − Used to update a existing resource or create a new resource.
* OPTIONS − Used to get the supported operations on a resource.

37
Q

What do you mean by idempotent operation?

A

Idempotent operations means their result will always same no matter how many times these operations are invoked.
Some examples of idempotent HTTP methods are GET, PUT, and PATCH. No matter how many times you call them, they will produce the same result with the same URI.

38
Q

What are webservices?

A

A webservice is a collection of open protocols and standards (XML, SOAP, HTTP, RESTful etc.) used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer.

39
Q

What is the purpose of HTTP Status Code?

A

HTTP Status code are standard codes and refers to predefined status of task done at server.
* 200 – OK, shows success
* 201 – CREATED, when a resource is successful created using POST or PUT request. Return link to newly created resource using location header.
* 204 – NO CONTENT, when response body is empty for example, a DELETE request.
* 304 – NOT MODIFIED, used to reduce network bandwidth usage in case of conditional GET requests. Response body should be empty. Headers should have date, location etc.
* 400 – BAD REQUEST, states that invalid input is provided e.g. validation error, missing data.
* 401 – FORBIDDEN, states that user is not having access to method being used for example, delete access without admin rights.
* 404 – NOT FOUND, states that method is not available.
* 409 - CONFLICT, states conflict situation while executing the method for example, adding duplicate entry.
* 500 – INTERNAL SERVER ERROR, states that server has thrown some exception while executing the method.

40
Q

What do you understand by Dependency Injection?

A

Dependency Injection design pattern allows us to remove the hard-coded dependencies and make our application loosely coupled, extendable and maintainable. We can implement dependency injection pattern to move the dependency resolution from compile-time to runtime.
Some of the benefits of using Dependency Injection are: Separation of Concerns, Boilerplate Code reduction, Configurable components and easy unit testing.

41
Q

What do you understand by Aspect Oriented Programming?

A

Enterprise applications have some common cross-cutting concerns that is applicable for different types of Objects and application modules, such as logging, transaction management, data validation, authentication etc. In Object Oriented Programming, modularity of application is achieved by Classes whereas in AOP application modularity is achieved by Aspects and they are configured to cut across different classes methods.
AOP takes out the direct dependency of cross-cutting tasks from classes that is not possible in normal object oriented programming. For example, we can have a separate class for logging but again the classes will have to call these methods for logging the data.

42
Q

What is Aspect, Advice, Pointcut and JointPoint in AOP?

A
  • Aspect: Aspect is a class that implements cross-cutting concerns, such as transaction management. Aspects can be a normal class configured and then configured in Spring Bean configuration file or we can use Spring AspectJ support to declare a class as Aspect using @Aspect annotation.
  • Advice: Advice is the action taken for a particular join point. In terms of programming, they are methods that gets executed when a specific join point with matching pointcut is reached in the application. You can think of Advices as Spring interceptors or Servlet Filters.
  • Pointcut: Pointcut are regular expressions that is matched with join points to determine whether advice needs to be executed or not. Pointcut uses different kinds of expressions that are matched with the join points. Spring framework uses the AspectJ pointcut expression language for determining the join points where advice methods will be applied.
  • Join Point: A join point is the specific point in the application such as method execution, exception handling, changing object variable values etc. In Spring AOP a join points is always the execution of a method.
43
Q

What is Spring IoC Container?

A

Inversion of Control (IoC) is the mechanism to achieve loose-coupling between Objects dependencies. To achieve loose coupling and dynamic binding of the objects at runtime, the objects define their dependencies that are being injected by other assembler objects. Spring IoC container is the program that injects dependencies into an object and make it ready for our use.
Spring Framework IoC container classes are part of org.springframework.beans and org.springframework.context packages and provides us different ways to decouple the object dependencies.
Some of the useful ApplicationContext implementations that we use are;
* AnnotationConfigApplicationContext: For standalone java applications using annotations based configuration.
* ClassPathXmlApplicationContext: For standalone java applications using XML based configuration.
* FileSystemXmlApplicationContext: Similar to ClassPathXmlApplicationContext except that the xml configuration file can be loaded from anywhere in the file system.
* AnnotationConfigWebApplicationContext and XmlWebApplicationContext for web applications.

44
Q

What are different scopes of Spring Bean?

A

There are five scopes defined for Spring Beans.
* singleton: Only one instance of the bean will be created for each container. This is the default scope for the spring beans. While using this scope, make sure spring bean doesn’t have shared instance variables otherwise it might lead to data inconsistency issues because it’s not thread-safe.
* prototype: A new instance will be created every time the bean is requested.
* request: This is same as prototype scope, however it’s meant to be used for web applications. A new instance of the bean will be created for each HTTP request.
* session: A new bean will be created for each HTTP session by the container.
* global-session: This is used to create global session beans for Portlet applications.

45
Q

What is a Controller in Spring MVC?

A

Controller is the class that takes care of all the client requests and send them to the configured resources to handle it. In Spring MVC, org.springframework.web.servlet.DispatcherServlet is the front controller class that initializes the context based on the spring beans configurations.
A Controller class is responsible to handle different kind of client requests based on the request mappings. We can create a controller class by using @Controller annotation. Usually it’s used with @RequestMapping annotation to define handler methods for specific URI mapping.

46
Q

What is DispatcherServlet and ContextLoaderListener?

A

DispatcherServlet is the front controller in the Spring MVC application and it loads the spring bean configuration file and initialize all the beans that are configured. If annotations are enabled, it also scans the packages and configure any bean annotated with @Component, @Controller, @Repository or @Service annotations.

ContextLoaderListener is the listener to start up and shut down Spring’s root WebApplicationContext. It’s important functions are to tie up the lifecycle of ApplicationContext to the lifecycle of the ServletContext and to automate the creation of ApplicationContext. We can use it to define shared beans that can be used across different spring contexts.

47
Q

How to handle exceptions in Spring MVC Framework?

A

Spring MVC Framework provides following ways to help us achieving robust exception handling.
* Controller Based – We can define exception handler methods in our controller classes. All we need is to annotate these methods with @ExceptionHandler annotation.
* Global Exception Handler – Exception Handling is a cross-cutting concern and Spring provides @ControllerAdvice annotation that we can use with any class to define our global exception handler.
* HandlerExceptionResolver implementation – For generic exceptions, most of the times we serve static pages. Spring Framework provides HandlerExceptionResolver interface that we can implement to create global exception handler. The reason behind this additional way to define global exception handler is that Spring framework also provides default implementation classes that we can define in our spring bean configuration file to get spring framework exception handling benefits.

48
Q

What is Spring MVC Interceptor and how to use it?

A

Spring MVC Interceptors are like Servlet Filters and allow us to intercept client request and process it. We can intercept client request at three places – preHandle, postHandleand afterCompletion.
We can create spring interceptor by implementing HandlerInterceptor interface or by extending abstract class HandlerInterceptorAdapter.
We need to configure interceptors in the spring bean configuration file. We can define an interceptor to intercept all the client requests or we can configure it for specific URI mapping too.

49
Q

What is the benefits of using Spring Boot?

A
  • Auto-configure applications based on the artifacts it finds on the classpath
  • Provide non-functional features common to applications in production, such as security or health checks
50
Q

What is the transaction propagation and isolation in Spring Framework ?

A

Propagation
Defines how transactions relate to each other. Common options
* PROPAGATION_REQUIRED: This is the default propagation level. If a transaction already exists when the method is called, that transaction will be used. Otherwise, a new transaction will be started.
* PROPAGATION_REQUIRES_NEW: This propagation level always starts a new transaction, regardless of whether a transaction already exists. The existing transaction, if any, will be suspended until the new transaction is completed.
* PROPAGATION_SUPPORTS: This propagation level will use an existing transaction if one exists, but it will not start a new transaction if none exists.
* PROPAGATION_NOT_SUPPORTED: This propagation level will never start a new transaction and will run the method without a transaction. If a transaction already exists, it will be suspended until the method has been completed.
* PROPAGATION_NEVER: This propagation level will never start a new transaction and throw an exception if a transaction already exists. You can specify the propagation level you want to use by setting the propagation attribute of the @Transactional annotation when you declare your transactional method.

Outer bean
~~~
@Autowired
private TestDAO testDAO;

@Autowired
private InnerBean innerBean;

@Override
@Transactional(propagation=Propagation.REQUIRED)
public void testRequired(User user) {
testDAO.insertUser(user);
try{
innerBean.testRequired();
} catch(RuntimeException e){
// handle exception
}
}
~~~

Inner bean
~~~
@Override
@Transactional(propagation=Propagation.REQUIRED)
public void testRequired() {
throw new RuntimeException(“Rollback this!”);
}
~~~

Isolation
Defines the data contract between transactions.
* Read Uncommitted: Allows dirty reads
* Read Committed: Does not allow dirty reads. Default Isolation in Spring Framework. (ISOLATION_DEFAULT or ISOLATION_READ_COMMIT)
* Repeatable Read: If a row is read twice in the same transaciton, result will always be the same
* Serializable: Performs all transactions in a sequence

Isolation level in a transactional method
~~~
@Autowired
private TestDAO testDAO;

@Transactional(isolation=Isolation.READ_COMMITTED)
public void someTransactionalMethod(User user) {

// Interact with testDAO

}
~~~

51
Q

Explain about the Scrum lifecycle.

A

The following diagram details the Scrum lifecycle. Scrum is iterative. The entire lifecycle is completed in fixed time-period called a Sprint. A Sprint is typically 2-4 weeks long.

52
Q

Explain about the Scrum Roles

A

Scrum prescribes three specific roles…
* Product Owner : Responsible for what the team is building, and why they’re building it. The product owner is responsible for keeping the backlog up-to-date and in priority order.
* Scrum Master : Responsible to ensure the scrum process is followed by the team. Scrum masters are continually on the lookout for how the team can improve, while also resolving impediments (blocking issues) that arise during the sprint. Scrum masters are part coach, part team member, and part cheerleader.
* Scrum Team : These are the individuals that actually build the product. The team owns the engineering of the product, and the quality that goes with it.

53
Q

How can you create a repository in Git?

A

In Git, to create a repository, create a directory for the project if it does not exist, and then run command “git init”. By running this command .git directory will be created in the project directory, the directory does not need to be empty.

54
Q

What is the difference between git pull and git fetch?

A
  • Git pull command pulls new changes or commits from a particular branch from your central repository and updates your target branch in your local repository.
  • Git fetch is also used for the same purpose but it works in a slightly different way. When you perform a git fetch, it pulls all new commits from the desired branch and stores it in a new branch in your local repository. If you want to reflect these changes in your target branch, git fetch must be followed with a git merge. Your target branch will only be updated after merging the target branch and fetched branch.

Just to make it easy for you, remember the equation below:
Git pull = git fetch + git merge

55
Q

What is ‘staging area’ or ‘index’ in Git?

A

That before completing the commits, it can be formatted and reviewed in an intermediate area known as ‘Staging Area’ or ‘Index’. From the diagram it is evident that every change is first verified in the staging area I have termed it as “stage file” and then that change is committed to the repository.

56
Q

What is Git stash?

A

GIT stash takes the current state of the working directory and index and puts in on the stack for later and gives you back a clean working directory. So in case if you are in the middle of something and need to jump over to the other job, and at the same time you don’t want to lose your current edits then you can use GIT stash.

57
Q

How can you create a repository in Git?

A

This is probably the most frequently asked questions and answer to this is really simple.
To create a repository, create a directory for the project if it does not exist, then run command “git init”. By running this command .git directory will be created in the project directory.

58
Q

What is the function of git clone?

A

The git clone command creates a copy of an existing Git repository. To get the copy of a central repository, ‘cloning’ is the most common way used by programmers.

59
Q

How can conflict in git resolved?

A

To resolve the conflict in git, edit the files to fix the conflicting changes and then add the resolved files by running “git add” after that to commit the repaired merge, run “git commit”. Git remembers that you are in the middle of a merger, so it sets the parents of the commit correctly.

60
Q

What is git rebase and how can it be used to resolve conflicts in a feature branch before merge?

A

In simple words, git rebase allows one to move the first commit of a branch to a new starting location. For example, if a feature branch was created from master, and since then the master branch has received new commits, git rebase can be used to move the feature branch to the tip of master. The command effectively will replay the changes made in the feature branch at the tip of master, allowing conflicts to be resolved in the process. When done with care, this will allow the feature branch to be merged into master with relative ease and sometimes as a simple fast-forward operation.

61
Q

What is git cherry-pick?

A

Cherry picking in git means to choose a commit from one branch and apply it onto another.
This is in contrast with other ways such as merge and rebase which normally applies many commits onto a another branch.
Make sure you are on the branch you want apply the commit to. git checkout master Execute the following:
git cherry-pick <commit-hash></commit-hash>