Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, September 24, 2014

Java JPA & Hibernate interview questions and answers

1. What is ORM?

Keyword:
Object-Relational Mapping.
converting data between relational databases and OOP languages.

Answer:
ORM is Object-Relational Mapping. It is a programming technique for converting data between incompatible type systems in relational databases and object-oriented programming languages. You can use an ORM framework to persist model objects to a relational database and retrieve them, and the ORM framework will take care of converting the data between the two otherwise incompatible states.

2. Explain first-level cache, second-level cache and query cache in Hibernate.

Keyword:
First level cache: associated with session.  enabled by default per transaction.
Second level cache: associated with session factory. disabled by default. Example: EHCache, OSCache, JBoss Cache.
Query cache: cache actual query results. disabled by default.

Answer:
First-level cache is associated with the Session object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications.

Second-level cache is associated with the Session Factory object. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided. EHCache, OSCache, JBoss Cache are examples of second-level cache provider.
By default, second-level cache is not enabled, you need to configure it as follows:
<property key="hibernate.cache.use_second_level_cache">true</property>
<property name="hibernate.cache.region.factory_class">net.sf.ehcache.hibernate.EhCacheRegionFactory</property>

Query cache is used to cache actual query results, rather than just persistent objects. Query cache should always be used in conjunction with the second-level cache.
By default, query cache is not enabled. To enable query cache, the following property should be used:
<property key="hibernate.cache.use_query_cache">true</property>

3. What is lazy loading in Hibernate?

Keyword:
parent-children, doesn’t load the children when loading the parent,
lazy=true/false,
parent.getChildren().size()

Answer:
In a one-to-many relationship, lazy setting decides whether to load child objects while loading the Parent Object.
lazy=true means Hibernate doesn’t load the children when loading the parent. This is the default behavior.
lazy=false makes Hibernate load the children when parent is loaded from the database.

Example:
public class Parent {
    private Set<Child> children;

    public Set<Child> getChildren() {
        return children;
    }
}

public void process() {
    //children contains nothing because of lazy loading.
    Set<Child> children = parent.getChildren();

    // When call one of the following methods,
    // Hibernate will start to actually load and fill the set.
    children.size();
    children.iterator();
}

4. What are the different Cascade: DELETE and DELETE-ORPHAN?

Keyword:
DELETE: delete referenced children when parent entity is deleted.
DELETE-ORPHAN: delete referenced children marked as removed (orphans) when parent entity is saved or updated.

Answer:
Cascade DELETE means if one parent entity is deleted, its referenced children will be deleted automatically.
Example:
Query query = session.create("from Parent where id = :id");
query.setParameter("id", 123);
Parent parent = (Parent)query.list().get(0);
session.delete(parent); //parent’s children will be deleted as well

Cascade DELETE-ORPHAN means when save or update one parent entity, only those children that have been marked removed will be deleted automatically. DELETE-ORPHAN allows parent table to delete few records (orphans) in child table.
Example:
Child c1 = (Child)session.get(Child.class, new Integer(10));
Child c2 = (Child)session.get(Child.class, new Integer(20));
Set<Child> children = parent.getChildren();
children.remove(c1); //c1 mark as removed
children.remove(c2); //c2 mark as removed
session.saveOrUpdate(parent);  //c1 and c2 will be deleted from table as well.

5. What is the difference between JPA and Hibernate?

Answer:
JPA is a specification for implementing ORM. It provides a set of guidelines that JPA implementation vendors should follow to create an ORM implementation.

Hibernate is an popular provider of JPA specification.

6. How to define a JPA entity class?

Answer:
The following is an example to define a typical JPA entity class

@Entity  //annotate entity class
@Table(name = "user")  //table mapping
public class User implements Serializable {
    //property declaration
    private Integer id;
    private String firstName;

    public User() {
       //default constructor
    }

    //primary key
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "user_id")
    public Integer getId() {
        return this.id;
    }
   
    public void setId(Integer id) {
        this.id = id;
    }

    //column mapping
    @Column(name = "first_name")
    public String getFirstName() {
        return this.firstName;
    }
   
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
}

7. Describe JPA Annotations for relationship definition.

Keyword:
@OneToOne, @OneToMany, @ManyToOne, @ManyToMany

Answer:
JPA use the following annotations to specify the relationships between entity classes:

@OneToOne defines a single-valued association to another entity that has one-to-one multiplicity.
Example:
    // On Customer class:
    @OneToOne
    @JoinColumn(name="custom_information_id")
    public CustomerInformation getCustomerInformation() { return customerInformation; }

    // On CustomerInformation class:
    @OneToOne(mappedBy="customerInformation")
    public Customer getCustomer() { return customer; }

@OneToMany defines a many-valued association with one-to-many multiplicity.
Example:
    // In Customer class:
    @OneToMany(cascade=ALL, mappedBy="customer")
    public Set<Order> getOrders() { return orders; }

    // In Order class:
    @ManyToOne
    @JoinColumn(name="customer_id", nullable=false)
    public Customer getCustomer() { return customer; }

@ManyToOne defines a single-valued association to another entity class that has many-to-one multiplicity.
Example:
    @ManyToOne(optional=false)
    @JoinColumn(name="customer_id", nullable=false, updatable=false)
    public Customer getCustomer() { return customer; }

@ManyToMany defines a many-valued association with many-to-many multiplicity.
Example:
    // In Customer class:
    @ManyToMany
    @JoinTable(name="customer_product")
    public Set<Product> getProducts() { return products; }

    // In Product class:
    @ManyToMany(mappedBy="products")
    public Set<Customer> getCustomers() { return customers; }

8. What is the difference between @JoinColumn and mappedBy attribute?

Answer:
@JoinColumn annotation indicates that this entity is the owner of the relationship, the corresponding table has a column with a foreign key to the referenced table.
mappedBy attribute indicates that the entity in this side is the inverse of the relationship, and the owner resides in the "other" entity.

An example:
@Entity
public class Company {
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "company")
    private Set<Department> departments;
}

@Entity
public class Department {
    @ManyToOne
    @JoinColumn(name = "companyId")
    private Company company;
}

9. What is @Temporal in JPA?

Answer:
@Temporal annotation is used to convert the date and time values between Java object and compatible database type. @Temporal must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar. It may only be specified for fields or properties of these types.

@Temporal has three type of values:
TemporalType.DATE
TemporalType.TIME
TemporalType.TIMESTAMP

An example:
@Temporal(TemporalType.DATE)
@Column(name = "register_date")
private java.util.Date registerDate;

10. What is the difference between JPQL and Criteria API?

Answer:
JPQL queries are defined as strings, similarly to SQL. JPA criteria queries, on the other hand, are defined by instantiation of Java objects that represent query elements.

A major advantage of using the criteria API is that errors can be detected earlier, during compilation rather than at runtime. On the other hand, for many developers string based JPQL queries, which are very similar to SQL queries, are easier to use and understand.

For simple static queries - string based JPQL queries may be preferred. For dynamic queries that are built at runtime - the criteria API may be preferred.

More Java JPA & Hibernate interview questions and answers: Java Interview Notes

  • What is SessionFactory in Hibernate?
  • Explain Hibernate object states.
  • What is the difference between merge method and update method in Hibernate?
  • What is Transaction in Hibernate?
  • What are the advantages of using JPA?
  • What is Entity in JPA?
  • What is Persistence Unit?
  • What is Entity Manager
  • What is FetchType in JPA?
  • What is the difference between JPQL and HQL?
  • ......

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.



JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

 SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play


Tuesday, September 23, 2014

Java Spring Framework interview questions and answers

1. What is Spring Framework? What are the advantages of using Spring?

Keyword:
application framework, IOC container.
Non-invasive development with POJO,
Loose coupling through dependency injection and interface orientation,
Spring AOP provides declarative common services, security, transaction, logging,
Reduce boilerplate code through aspects and templates. JdbcTemplate.

Answer:
The Spring Framework is an open source application framework and inversion of control (IOC) container for developing Java applications. Spring enables you to build applications from "plain old Java objects" (POJOs) and to apply enterprise services non-invasively to POJOs.

The main advantages of using Spring Framework are:
a. Lightweight and minimally invasive development with Plain Old Java Objects (POJOs). A Spring component can be any type of POJO. You don't need to implemented Spring specific interfaces or extend Spring specific classes.
b. Loose coupling through dependency injection and interface orientation. Spring IoC container manages java objects – from instantiation to destruction – through its BeanFactory, leaving them loosely coupled and allowing you to code to abstractions and to write testable code. For example, injecting mock implementation during testing.
c. Spring AOP provides declarative common services, like security, transaction, logging, leaving the application components to focus on their specific business logic;
d. Boilerplate reduction through aspects and templates. For example, Spring JdbcTemplate encapsulates JDBC checked exceptions to meaningful runtime exceptions.


2. What is IOC?

Keyword:
Inversion of Control, Dependency Injection.
Object coupling is bound at run time by an assembler object.

Answer:
Inversion of Control (IOC) is an object-oriented programming technique, in which object coupling is bound at run time by an assembler object and is typically not known at compile time using static analysis. IOC is also known as Dependency Injection (DI). In traditional programming, the flow of the business logic is determined by objects that are statically assigned to one another. With inversion of control, the flow depends on the object graph that is instantiated by the assembler and is made possible by object interactions being defined through abstractions. The binding process is achieved through dependency injection.

Example code:
Service: UserService interface and its implementations DbUserService, MockUserService
Client: UserManager
//User Service interface with a checkUser method
public interface UserService {
     boolean checkUser(String userName, String password);
}

//User Service implementation: check user via database
public class DbUserService implements UserService{
     public boolean checkUser(String userName, String password);
          //connect to database and check user
     }
}

//User Service mock implementation: check user via test data
public class MockUserService implements UserService{
     //define and init test user data.
     private Map<String, String> testUsers = ......;

     public boolean checkUser(String userName, String password);
          //check user using test data
          if(testUsers.get(userName)) {
              ......
          }
     }
}

//Traditional implementation without IOC:
//UserManager and UserService are tightly coupled,
//Cannot change another implementation at runtime, hard to test.
public class UserManager {
    private UserService userService;

    public UserManager() {
          this.userService = new DbUserService();
     }
}

//Implementation with IOC:
//UserManager and UserService are loosely coupled,
//The dependency is injected at runtime, can be either DbUserService or MockUserService,
//It is easy to test by injecting a mock implementation.
public class UserManager {
     private UserService userService;

     public UserManager(UserService userService) {
          this.userService = userService;
     }
}

3. What is Spring Container?

Keyword:
IOC container, manage components lifecycle.
Bean Factory, Application Context.

Answer:
Spring Container is at the core of the Spring Framework. It uses dependency injection (DI) to manage the components. In a Spring-based application, your application objects will live within the Spring container. The container will create the objects, wire them together, configure them, and manage their complete lifecycle from cradle to grave.

There are two types of Spring Container:
a. Bean factories (defined by the org.springframework.beans.factory.BeanFactory interface) are the simplest of
containers, providing basic support for DI.
b. Application contexts (defined by the org.springframework.context.ApplicationContext interface) build on the notion
of a bean factory by providing application framework services, such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners.


4. Explain Spring Bean lifecycle.

Answer:
a. Spring instantiates the bean.
b. Spring injects values and bean references into the bean’s properties.
c. If the bean implements BeanNameAware, Spring passes the bean’s ID to the setBeanName() method.
d. If the bean implements BeanFactoryAware, Spring calls the setBeanFactory() method.
e. If the bean implements ApplicationContextAware, Spring will call the setApplicationContext() method.
f. If the bean implements the BeanPostProcessor interface, Spring calls the postProcessBeforeInitialization() method.
g. If the bean implements the InitializingBean interface, Spring calls the afterPropertiesSet() method. Similarly, if the bean was declared with an init-method, then the specified initialization method will be called.
h. If the bean implements BeanPostProcessor, Spring will call the postProcessAfterInitialization() method.
i. At this point, the bean is ready to be used by the application and will remain in the application context until the application context is destroyed.
j. When container is shut down, if the bean implements the DisposableBean interface, then Spring will call the destroy() method. Likewise, if the bean was declared with a destroy-method, then the specified method will be called.


5. How to customize bean init and destroy process?

Keyword:
init-method, destroy-method.
default-init-method, default-destroy-method.
Implement InitializingBean and DisposableBean interfaces.

Answer:
There are several ways to customize bean init and destroy process:
a. Declare the <bean> with init-method and destroy-method parameters. For example:
public class MyBean {
    public void doInit() { //customized init code}
    public void doDestroy() { //customized destroy code}
}
<bean id="mybean" class="MyBean" init-method="doInit" destroy-method="doDestroy"/>

b. Set default-init-method and default-destroy-method in context definition file:
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
default-init-method="doInit"
default-destroy-method="doDestroy"> ...
</beans>
This setting will apply to all beans. You don’t have to declare init-method or destroy-method on each individual bean.

c. Implement InitializingBean and DisposableBean interfaces.
InitializingBean declares an afterPropertiesSet() method that serves as the init method.
DisposableBean declares a destroy() method that gets called when a bean is removed from the application context.


6. What is the difference between <context:annotation-config> and <context:component-scan>?

Answer:
<context:annotation-config> is used to activate annotations in beans already registered in the application context (no matter if they were defined with XML or by package scanning).

<context:component-scan> can also do what <context:annotation-config> does but also scans packages to detect and register Spring stereotyped classes within the ApplicationContext, for example: @Controller, @Service, @Repository, @Component.

7. Explain Spring stereotype annotations: @Component, @Service, @Repository, @Controller.

Answer:
@Component is a generic stereotype for any Spring-managed component. Classes marked with @Component are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.

@Repository, @Service, and @Controller are special kinds of @Component:
@Repository annotate DAO classes.
@Service annotate business logic (or called Business Service Facade) classes.
@Controller annotate Spring web controllers.

8. Describe the workflow of Spring Web MVC.

Keyword:
DispatcherServlet -> handler mapping -> controller -> ModelAndView -> ViewResolver -> view

Answer:
a. The DispatcherServlet configured in web.xml file receives the request.
b. DispatcherServlet consults one or more handler mappings to figure out the controller that is responsible for processing the request.
c. DispatcherServlet sends the request to the chosen controller. The controller handles the request by invoking service objects and business logic.
d. Controller packages up the model data as a map and identify the name of a view that should render the output. It sends the request, model and view name (a ModelAndView instance) back to the DispatcherServlet.
e. DispatcherServlet consults the ViewResolver to map the view name to a specific view implementation.
f. DispatcherServlet sends the model data to the view implementation. The view uses the model data to render the output.
g. DispatcherServlet sends the output to servlet container and finally servlet sends the response back to the user.

9. Can we configure a Spring Web MVC application without using web.xml?

Keyword:
Servlet 3.0, WebApplicationInitializer

Answer:
Yes. In a Servlet 3.0+ environment, we can configure the Servlet container programmatically as an alternative or in combination with a web.xml file. To do it, we just need to implement WebApplicationInitializer interface. WebApplicationInitializer is an interface provided by Spring MVC that ensures your implementation is detected and automatically used to initialize any Servlet 3 container.

For example:
public class SampleApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container) {
        XmlWebApplicationContext appContext = new XmlWebApplicationContext();
        appContext.setConfigLocation("/WEB-INF/spring/iraylab-sample.xml");
        ServletRegistration.Dynamic registration = container.addServlet("iraylab-sample", new DispatcherServlet(appContext));
        registration.setLoadOnStartup(1);
        registration.addMapping("/");
    }

}

10. How to handle static resources in Spring Web MVC?

Answer:
Use <mvc:resources> element in context definition file.
<mvc:resources> sets up a handler for serving static content.
<beans xmlns="http://www.springframework.org/schema/beans" ......>
     <mvc:resources mapping="/resources/**" location="/resources/"/>
</beans>

More Java Spring Framework interview questions and answers: Java Interview Notes

  • What are the different types of IOC (dependency injection)?
  • What is the difference between BeanFactory and ApplicationContext?
  • How to configure a singleton class as a bean in Spring container?
  • How to configure lazy-initialized bean in Spring?
  • How to configure bean automatic detection?
  • Explain AOP concepts: Aspect, Joint Point, Advice, Pointcut, Weaving.
  • Explain DAO support in Spring.
  • What is @Controller in Spring Web MVC?
  • What is @RequestMapping in Spring Web MVC?
  • How to validate @Controller inputs in Spring Web MVC?
  • ......

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.



JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

 SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play


Monday, September 22, 2014

Java EE interview questions and answers

1. Explain the multi-tiered architecture in Java EE.

Keyword:
Web tier: Servlet, JSP, JSF, Spring MVC, Struts,
Business tier: Spring IOC, EJB, REST, Web services,
Data tier: JDBC, JPA, Hibernate.

Answer:
In a multi-tiered application, the functionality is separated into isolated functional areas, called tiers. In a typical Java EE architecture, there are the following tiers:

The client tier
The client tier consists of application clients that access a Java EE server and that are usually located on a different machine from the server. Clients can be a web browser, a standalone application, or other servers, and they run on a different machine from the Java EE server.

The Web Tier
The web tier consists of components that handle the interaction between clients and the business tier.
Its primary tasks are:
Dynamically generate content in various formats for the client.
Collect input from users of the client interface and return appropriate results from the components in the business tier.
Control the flow of screens or pages on the client.
Maintain the state of data for a user's session.
Perform some basic logic and hold some data temporarily in JavaBeans components.
Technologies used in the Web Tier:
Servlets, JSP, JSF, JSTL, EL, JavaBeans, Spring MVC, Struts, etc.

The Business Tier
The business tier consists of components that provide the business logic for an application. In a properly designed enterprise application, the core functionality exists in the business tier components.
Technologies Used in the Business Tier:
EJB, Spring IOC, POJO, JAX-RS RESTful web services, JAX-WS web services.

The Data Tier or EIS Tier
The data tier (often called the enterprise information systems tier, or EIS tier) consists of database servers, enterprise resource planning systems, and other legacy data sources, like mainframes. These resources typically are located on a separate machine than the Java EE server, and are accessed by components on the business tier.
Technologies Used in the Data Tier:
JDBC, JPA, Hibernate, Java EE Connector Architecture (JCA), Java Transaction API (JTA).


2. Explain the life cycle of Servlet.

Keyword:
Servlet container load servlet class,
init() create servlet instance,
service(), doGet(), doPost() handle request,
destroy() remove servlet.

Answer:
The life cycle of a servlet is controlled by the servlet container. When a request is mapped to a servlet, the container performs the following steps:
If an instance of the servlet does not exist, the servlet container loads the servlet class;
The servlet container creates an instance of the servlet class by calling the servlet’s init() method;
The servlet container invokes the service method of the servlet, passing request and response objects. The service() method checks the HTTP requests type (GET, POST) and calls the doGet() or doPost method;
If the container needs to remove the servlet, it finalizes the servlet by calling the servlet’s destroy() method.

3. What is the difference between ServletConfig and ServletContext?

Keyword:
ServletConfig, servlet level, access within servlet.
ServletContext, web application level, available for all servlet within the application.
web.xml:  <init-param>, <context-param>.

Answer:
ServletConfig is specific to a particular servlet. It is used to pass information to a servlet during initialization. The parameters configured in a ServletConfig object can only be accessed within the servlet.

ServletContext defines a set of methods that a servlet uses to communicate with its servlet container. There is one ServletContext instance per web application per JVM. The parameters configured at the ServletContext level are available to all servlets within the application.

In web.xml, you can define ServletContext parameters under <web-app> tag, you can define ServletConfig parameters under <servlet> tag. For example:
<web-app>
    <context-param>
        <param-name>servlectContextParam1</param-name>
        <param-value>servlectContextValue1</param-value>
    </context-param>
    ......
    <servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>com.xxx.MyServlet</servlet-class>
        <init-param>
            <param-name>myServletConfigParam1</param-name>
            <param-value>myServletConfigValue1</param-value>
        </init-param>
    </servlet>
    ......
</web-app>


4. Are Servlets thread Safe? How to make a servlet thread safe?

Keyword:
Only one instance for every servlet.
Avoid access/reassign member variable,
Avoid synchronize the service (doGet, doPost) methods,
Implement SingleThreadModel interface, deprecated.

Answer:
No, servlets are not thread safe. In servlet container, there is only one instance for every servlet. Servlet container may send concurrent requests through the service method of the servlet.

To make sure that a servlet is thread safe:
a. The service method of servlet should not access any member variables, unless these member variables are thread safe themselves.
b. The service method of servlet should not reassign member variables, as this may affect other threads executing inside the service() method. If it is really necessary to reassign a member variable, make sure this is done inside a synchronized block.
c. Avoid to synchronize the service (or doPost, doGet) method directly, use synchronized block instead.
d. Implement SingleThreadModel interface to create a single-threaded servlet. But SingleThreadModel interface is deprecated, it is not recommended to use it.


5. What is Java EE Container?

Answer:
Java EE containers are the interface between Java EE components and the lower-level functionality provided by Java EE platform. The functionality of the container is defined by the platform, and is different for each component type. Java EE server allows the different component types to work together to provide functionality in an enterprise application.

Java EE Containers provide configurable services such as security, transaction management, JNDI lookups, and remote connectivity. Java EE containers also manage nonconfigurable services, such as enterprise bean and servlet lifecycles, database connection resource pooling, data persistence, and access to the Java EE platform APIs.


6. What is Java EE Component?

Answer:
A Java EE component is a self-contained functional software unit that is assembled into a Java EE application with its related classes and files and that communicates with other components. Java EE applications are made up of components.

The Java EE specification defines the following Java EE components:
Application clients and applets are components that run on the client.
Java Servlet, JavaServer Faces, and JavaServer Pages (JSP) technology components are web components that run on the server.
EJB components (enterprise beans) are business components that run on the server.

7. Explain the basic steps of using JDBC.

Answer:
Basically a Java program implementing JDBC performs the following steps:
1). Load a JDBC driver.
2). Establish a database connection through a connection URL.
3). Create a statement object.
4). Execute a query or update on the statement object.
5). Process the result.
6). Close the connection.

Example:
   Connection conn = null;
   Statement stmt = null;
   try{
      //STEP 1:
      Class.forName("com.mysql.jdbc.Driver");
      //STEP 2:
      conn = DriverManager.getConnection("jdbc:mysql://hostname:port/mydb","user", "pwd")
      //STEP 3:
      stmt = conn.createStatement();
      //STEP 4:
      String sql = "SELECT id, name FROM Users";
      ResultSet rs = stmt.executeQuery(sql);
      //STEP 5:
      while(rs.next()){
         int id  = rs.getInt("id");
         ......
      }
      //STEP 6:
      rs.close();
      stmt.close();
      conn.close();
   }catch(SQLException e1){
      ......
   }catch(Exception e2){
      ......
   }finally{
      try{
         if(stmt!=null)
            stmt.close();
      }catch(SQLException e3){}
      try{
         if(conn!=null)
            conn.close();
      }catch(SQLException se){}
   }

8. What is the difference between Point-to-Point Messaging and Publish/Subscribe Messaging?

Keyword:
Point-to-Point Messaging: queue, sender, receiver.
Publish/Subscribe Messaging: topic, publisher, subscriber.

Answer:
A point-to-point (PTP) application is built on the concept of message queues, senders, and receivers. Each message is addressed to a specific queue, and receiving clients extract messages from the queues established to hold their messages. Queues retain all messages sent to them until the messages are consumed or expire.

PTP messaging has the following characteristics:
a. Each message has only one consumer.
b. A sender and a receiver of a message have no timing dependencies. The receiver can fetch the message whether or not it was running when the client sent the message.
c. The receiver acknowledges the successful processing of a message.

In a publish/subscribe (pub/sub) application, clients address messages to a topic. Publishers and subscribers can dynamically publish or subscribe to the content hierarchy. The system takes care of distributing the messages arriving from a topic’s multiple publishers to its multiple subscribers. Topics retain messages only as long as it takes to distribute them to current subscribers.

Pub/sub messaging has the following characteristics.
Each message can have multiple consumers.
Publishers and subscribers have a timing dependency. A client that subscribes to a topic can consume only messages published after the client has created a subscription, and the subscriber must continue to be active in order for it to consume messages.

9. What are RESTful Web Services?

Keyword:
REST, resources, URI.
JAX-RS

Answer:
RESTful web services are loosely coupled, lightweight web services that are particularly well suited for creating APIs for clients spread out across the internet.

Representational State Transfer (REST) is an architectural style of client-server application centered around the transfer of representations of resources through requests and responses.

In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web. The resources are represented by documents and are acted upon by using a set of simple, well-defined operations.

In Java EE, we can use Java API for RESTful Web Services (JAX-RS) to build RESTful web services.

10. What are the differences between SOAP-based Web Services and RESTful Web Services?

Answer:
SOAP-based web services is a heavyweight solution. It has the following advantages:
a. Language, platform, and transport independent (HTTP or SMTP), while REST is based on HTTP;
b. Works well in distributed enterprise environments, while REST assumes direct point-to-point communication;
c. Reliable. SOAP provides reliable messaging (WS-ReliableMessaging) and end to end reliability through soap intermediaries.
d. Security. support different standards for security. WS-Security provides end-to-end security covering message integrity and authentication.

REST is a lightweight solution. It is easier to use and is more flexible. It has the following advantages:
a. No expensive tools require to interact with the Web service;
b. Smaller learning curve;
c. Flexible data representation: SOAP uses XML for all messages, REST can use XML, JSON or other format;
d. Performance: RESTful Web services are completely stateless. Restful services provide a good caching infrastructure over HTTP GET method.

More Java EE interview questions and answers: Java Interview Notes

  • What is the difference between Java EE and Java SE?
  • Explain MVC architecture relating to Java EE.
  • What is the difference between doGet and doPost method?
  • What is the difference between sendRedirect and forward methods?
  • What is the difference between Java EE component and standard Java class?
  • What is the difference between Statement, PreparedStatement and CallableStatement?
  • What is the difference between Topic and Queue?
  • What is CDI in Java EE?
  • Explain the main principles of RESTful Web Services.
  • What is JAX-RS API?
  • ......

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.



JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

 SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play


Sunday, September 21, 2014

Java Design Pattern interview questions and answers

1. What is design pattern?

Answer:
A design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into source or machine code. It is a description or template for how to solve a problem that can be used in many different situations.

2. What is Singleton design pattern? When do you use it?

Keyword:
only one instance, a global point of access.
logging, cache, service registry, thread pool, configuration settings, database connection manager.

Answer:
Singleton design pattern ensures a class has only one instance, and provide a global point of access to it.

Use the Singleton pattern when
· there must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
· when the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.

In practice, Singleton pattern is used in logging, cache, service registry, thread pool, configuration settings, database connection manager.

3. How to implement a thread-safe singleton in Java?

Keyword:
Eager initialization
Lazy initialization
On demand holder
Enum

Answer:
a. Eager initialization:
public class Singleton {
    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCE;
    }
}

b. Lazy initialization:
public class Singleton {
  private static Singleton INSTANCE;

  private Singleton() {}

  public static synchronized Singleton getInstance() {
    if (INSTANCE == null) {
      INSTANCE = new Singleton();
    }
    return INSTANCE;
  }
}

c. Initialization On Demand Holder Idiom:
public class Singleton {
private Singleton() { }

private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}

public static Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}

d. Using Enum:
public enum Singleton {
INSTANCE;
}

4. What is Factory Method pattern? When do you use it?

Keyword:
define a creation interface, subclasses implement concrete creation logic.
Class.newInstance()

Answer:
Factory Method pattern defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.

Use the Factory Method pattern when
· a class can't anticipate the class of objects it must create.
· a class wants its subclasses to specify the objects it creates.
· classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.

Examples in Java API:
java.lang.Class#newInstance()
java.lang.reflect.Constructor#newInstance()
java.lang.Boolean#valueOf(String)

5. What is Abstract Factory pattern? When do you use it?

Keyword:
define an interface of creating families of products without specifying concrete classes.
DriverManager#getConnection()
DocumentBuilderFactory#newInstance()

Answer:
Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes.

Use the Abstract Factory pattern when
· a system should be independent of how its products are created, composed, and represented.
· a system should be configured with one of multiple families of products.
· a family of related product objects is designed to be used together, and you need to enforce this constraint.
· you want to provide a class library of products, and you want to reveal just their interfaces, not their implementations.

Examples in Java API:
java.util.Calendar#getInstance()
java.sql.DriverManager#getConnection()
javax.xml.parsers.DocumentBuilderFactory#newInstance()

6. Explain the SOLID principles in Object-Oriented Design.

Keyword:
Single responsibility principle
Open/closed principle
Liskov substitution principle
Interface segregation principle
Dependency inversion principle

Answer:
S (SRP): Single responsibility principle. It means a class should have only a single responsibility.

O (OCP): Open/closed principle. It means software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

L (LSP): Liskov substitution principle. It means objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

I (ISP): Interface segregation principle. It means clients should not be forced to depend upon interfaces that they don't use.

D (DIP): Dependency inversion principle. It means: high-level modules should not depend on low-level modules. Both should depend on abstractions; Abstractions should not depend on details. Details should depend on abstractions.

More Java Design Pattern interview questions and answers: Java Interview Notes

  • What is the difference between Factory Method and Abstract Factory?
  • What is Builder pattern? When do you use it?
  • What is Adapter pattern? When do you use it?
  • What is Chain of Responsibility pattern? When do you use it?
  • What is Observer pattern? When do you use it?
  • What is Template Method pattern? When do you use it?
  • ......

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.



JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

 SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play


Friday, September 19, 2014

Java Generics, Reflection and Annotation interview questions and answers

1. What are the benefits of using Generics?

Keyword:
Compile time type check
Elimination of casts
Easy to implement generic algorithms

Answer:
a. Stronger type checks at compile time. Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.

b. Elimination of casts. An example:
List list = new ArrayList();
list.add("abc");
String s = (String) list.get(0); // need cast

List<String> list = new ArrayList<String>();
list.add("abc");
String s = list.get(0);   // no cast

c. Enabling programmers to implement generic algorithms. By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.

2. Can you pass List<String> to a method which accepts List<Object>?

Answer:
No, it will cause a compile error.

Different instantiations of the same generic type for different concrete type arguments have no type relationship.
Example:
public void printList(List<Object> list){
    for(Object o : list)
        System.out.println(o);
}
List<String> strList =new ArrayList<String>();
strList.add("abc");
printList(strList); // compiler error!!

3. What is unchecked warning? How to eliminate it?

Keyword:
Compile warning, assign raw type to parameterized type.
Eliminate: use parameterized type,  @SuppressWarnings("unchecked”).

Answer:
Unchecked warning occurs when you assign a raw type to a parameterized type.
Example:
List<String> list = new ArrayList(); //compile warning
The term "unchecked" means that the compiler does not have enough type information to perform all type checks necessary to ensure type safety.

To eliminate the unchecked warning, fix it as follows:
List<String> list = new ArrayList<String>();

If you can’t eliminate a warning, you can suppress the warning by using annotation:
@SuppressWarnings("unchecked")

4. What is type erasure?

Answer:
Java generics is implemented using type erasure mechanism. To implement generics, the compiler applies type erasure to:
a. Replace all type parameters in generic types with their bounds or Object if the type parameters are unbounded, while makes the produced bytecode contain only ordinary classes, interfaces, and methods.
b. Insert type casts if necessary to preserve type safety.
c. Generate bridge methods to preserve polymorphism in extended generic types.

Type erasure ensures that no new classes are created for parameterized types; consequently, generics incur no runtime overhead.

5. How to create an object of given class using reflection?

Answer:
First, load the class using Class.forName() method, then call newInstance() method to create instance.

Example:
try{
    Class userClass = Class.forName("com.abc.User");
    User user = userClass.newInstance();
}
catch(ClassNotFoundException e) { ... }
catch(InstantiationException e) { ... }
catch(IllegalAccessException e) { ... }

6. How to invoke a Java method using Reflection?

Answer:
The following example shows how to invoke a Java method using Reflection:

package com.iraylab.sample;
import java.lang.reflect.Method;
public class Hello {

    public void sayHello() {
        System.out.println("Hello");
    }
   
    public void sayHelloTo(String name) {
        System.out.println("Hello " + name);
    }
   
    public static void main(String[] args) {
        try{
            //Get Class and create instance
            Class clazz = Class.forName("com.iraylab.sample.Hello");
            Object hello = clazz.newInstance();
           
            //Create and invoke a method that has no parameter
            Method method1 = clazz.getDeclaredMethod("sayHello");
            method1.invoke(hello);
           
            //Greate and invoke a method that has parameters
            Method method2 = clazz.getDeclaredMethod("sayHelloTo", String.class);
            method2.invoke(hello, "Java");
        } catch(Exception e){
            //...
        }
    }
}

7. How to get annotations at runtime using reflection?

Answer:
Use the getAnnotation method of java.lang.Class to get annotations applied to a class.
Use the getAnnotation method of java.lang.reflect.Method to get annotations applied to a method.
Example:
Define an annotation:
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation { }

Apply it to a class:
@MyAnnotation
public class User { }

Get annotation via reflection:
User user = new User();
Class userClass =  user.getClass();
for (Annotation annotation : userClass.getDeclaredAnnotations()) {
    //...
}

8. Describe annotation @Deprecated, @Override and @SuppressWarnings.

Answer:
@Deprecated - this annotation indicates that the marked element is deprecated and should no longer be used. The compiler generates a warning whenever a program uses a method, class, or field with the @Deprecated annotation.

@Override - this annotation informs the compiler that the element is meant to override an element declared in a superclass. While it is not required to use this annotation when overriding a method, it helps to prevent errors. If a method marked with @Override fails to correctly override a method in one of its superclasses, the compiler generates an error.

@SuppressWarnings - this annotation tells the compiler to suppress specific warnings that it would otherwise generate. For example, a deprecated method is used, the compiler usually generates a warning. By using this annotation, the warning will be suppressed.

More Java Generics, Reflection and Annotation interview questions and answers: Java Interview Notes

  • What is generic type and parameterized type?
  • What is bounded type parameter?
  • What is autoboxing and unboxing in Java?
  • What is Reflection in Java?
  • What is the difference between getMethods() and getDeclaredMethods() of Class?
  • What are the different types of annotation?
  • How to create a custom annotation?
  • ......

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.



JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

 SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play


Thursday, September 18, 2014

Java Multithreading interview questions and answers

1. Explain different ways of creating a thread.

Keyword:
Thread class
Runnable interface

Answer:
a. extends Thread class:
public class MyThread extends Thread {
    public void run(){
       //thread execution logic
    }
}

b. implements Runnable interface:
public class MyThread implements Runnable {
    public void run(){
       //thread execution logic
    }
}

2. Explain the life cycle of thread.

Keyword:
New, Runnable, Running, Blocked, Waiting, Dead

Answer:
There are the following states in the life cycle of thread:
New - This is the state when the thread instance has been created, but the start() method has not been invoked.
Runnable - This is the state when the thread is eligible to run, but the scheduler has not selected it to be the running thread. A thread enters the runnable state when the start() method is invoked. A thread can also return to the runnable state from a blocked, waiting, or sleeping state.
Running - This is the state when the thread scheduler selects it from the runnable pool to be the currently executing thread.
Blocked - This is the state when the thread is waiting for a monitor lock to enter a synchronized block/method or reenter a synchronized block/method after calling the wait() method.
Waiting - This is the state when the thread is waiting for another thread to perform a particular action. For example, a thread that has called Object.wait() on an object is waiting for another thread to call Object.notify() or Object.notifyAll() on that object. A thread that has called Thread.join() is waiting for a specified thread to terminate.
Dead - This is the state when the thread has completed execution.

3. What is the difference between sleep(), yield() and stop() methods?

Keyword:
sleep: cause thread to stop executing, keep monitor.
yield: cause thread pause and allow other threads to execute, behavior not guaranteed.
stop: force thread to stop executing, unlock all monitors. deprecated.

Answer:
The sleep() method causes the current thread to stop executing for a given amount of time; if no other thread or process needs to be run, the CPU will be idle. The thread does not lose ownership of any monitors.

The yield() method hints the scheduler that the current thread is not doing anything particularly important and is willing to yield its current use of a processor. This method doesn’t guarantee that the current thread will pause. If there is no waiting thread or all the waiting threads have a lower priority, the current thread will continue its execution.

The stop() method forces the current thread to stop executing. Stopping a thread causes it to unlock all of the monitors that it has locked. This method is unsafe and has been deprecated.

4. What is the difference between start() and run() method?

Answer:
The start() method causes the thread to begin execution and make the thread enter the runnable state. When the scheduler pickup the thread from the runnable pool, the run() method get executed.
The run() method is the thread's execution logic. Subclasses of Thread should override this method.

5. How to ensure that a thread runs after another thread?

Keyword:
use join() method

Answer:
Use the join() method. This method wait for the thread on which it’s called to be dead or wait for a certain amount of time. It has three forms:
join() - waits for this thread to die.
join(long millis) - waits at most millis milliseconds for this thread to die. A timeout of 0 means to wait forever.
join(long millis, int nanos) - waits at most millis milliseconds plus nanos nanoseconds for this thread to die.

For the following example, t2 will start only when t1 is dead.
Thread t1 = new Thread();
Thread t2 = new Thread();
try {
    t1.join();
} catch (InterruptedException e) {}    
t2.start();

6. What is ThreadLocal? What is the difference with synchronized?

Keyword:
thread-local variable, independent copy for each thread.
Servlet may use ThreadLocal to store local data.
ThreadLocal for data isolation, Synchronized for data share.

Answer:
ThreadLocal class provides thread-local variables. These variables differ from their normal counterparts in that each thread can access an independent copy of the variable. ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread.
Example: a servlet may use ThreadLocal to store local data for each thread.

Main methods of ThreadLocal class:
get() - Returns the value in the current thread's copy of this thread-local variable.
set() - Sets the current thread's copy of this thread-local variable to the specified value.
initialValue() - Returns the current thread's "initial value" for this thread-local variable.

The difference with synchronized:
Synchronized is used to share data among threads, ThreadLocal is used to isolate data among threads.

7. What are DeadLock, LiveLock, and Starvation?

Answer:
Deadlock describes a situation where two or more threads are blocked forever, waiting for each other to release lock.

LiveLook describes a situation where a thread acts in response to the action of another thread. If the other thread's action is also a response to the action of another thread, then livelock may result. The threads are not blocked, but they are too busy responding to each other to resume work.

Starvation describes a situation where a thread is unable to gain regular access to shared resources and is unable to make progress. This happens when shared resources are made unavailable for long periods by greedy threads.

8. How to solve the Producer-Consumer problem?

Keyword:
a. Use wait(), notify()/notifyAll() methods.
b. Use BlockingQueue, put(), take().

Answer:
There are two typical ways to solve the Producer-Consumer problem:
a. Use wait and notify/notifyAll methods of Object to communicate between Producer thread and Consumer thread.
Sample code:
List<Element> queue = new LinkedList<Element>();
……
Producer thread:
while(true) {
    synchronized(queue) {
        while(queue.size() == MAX_SIZE) { //full
            queue.wait();
        }
        queue.add(new Element(…)) //produce
    }
}
……
Consumer thread:
while(true) {
    synchronized(queue) {
        while(queue.isEmpty()) { //empty
            queue.wait();
        }
        Element e = queue.remove(0);
        processElement(e); //consume
    }
}
……

b. Use BlockingQueue and its blocking methods: put() and take()
Sample code:
BlockingQueue<Element> queue = new ArrayBlockingQueue<Element>();
……
Producer thread:
while(true) {
     queue.put(new Element(…)) //produce
}
……
Consumer thread:
while(true) {
    processElement(queue.take());
}
……

More Java Multithreading interview questions and answers: Java Interview Notes

  • What is the difference between process and thread?
  • What are the ways in which a thread can enter the waiting state?
  • What is the difference between synchronized method and synchronized block?
  • What is the difference between synchronized and volatile?
  • Explain wait(), notify() and notifyAll() methods of Object class.
  • What is the difference between Mutex and Semaphore?
  • What is Lock in Java Concurrency API?
  • What is ReentrantLock in Java Concurrency API?
  • ......

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.



JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

 SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play



Tuesday, September 16, 2014

Java IO, JVM & GC interview questions and answers

1. What is the difference between unbuffered I/O stream and buffered I/O stream?

Keyword:
Unbuffered: read and write is handled directly by OS. InputStream, OutputStream.
Buffered: read and write on buffer. BufferedInputStream, BufferedOutputStream.
Unbuffered is less efficient than buffered.

Answer:
Unbuffered I/O means each read or write request is handled directly by the underlying OS. This can make a program much less efficient, since each such request often triggers disk access, network activity, or some other operation that is relatively expensive. Examples: InputStream, OutputStream, FileInputStream, FileOutputStream, Reader, Writer, FileReader, FileWriter.

To reduce this kind of overhead, the Java platform implements buffered I/O streams. Buffered input streams read data from a memory area known as a buffer; the native input API is called only when the buffer is empty. Similarly, buffered output streams write data to a buffer, and the native output API is called only when the buffer is full. To flush a stream manually, invoke its flush method.
Examples: BufferedInputStream, BufferedOutputStream, BufferedReader, BufferedWriter.

2. How to read and write text files using Java I/O?

Keyword:
BufferedReader, readLine()
PrintWriter, println()

Answer:
Typically, we use buffered I/O streams to read/write text files.
Example:
import java.io.*;
public class TextFileRW {
     public static void main(String[] args) {
          BufferedReader br = null;
          PrintWriter pw = null;
          try {
               br = new BufferedReader(new FileReader("a.txt"));
               pw = new PrintWriter(new FileWriter("b.txt"));
               String line;
               while((line=br.readLine())!=null) {
                    pw.println(line);
               }
          }
          catch(IOException e) {
               e.printStackTrace();
          }
          finally {
               if(br!=null) {
                    try{
                         br.close();
                    } catch(IOException e2) {
                         e2.printStackTrace();
                    }
               }
               if(pw!=null) pw.close();
          }
     }
}

3. How to read command line input in Java?

Keyword:
a. InputStreamReader and system.in
b. Console class
c. Scanner class

Answer:
Java supports several ways to read command line input:
a. Access standard input through system.in, along with the InputStreamReader and BufferedReader classes.
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = null;
try {
    input = br.readLine();
} catch (IOException e) { ... }

b. Using Console class.
Console console = System.console();
String input = console.readLine();
The Console is particularly useful for secure password entry:
char[] password = console.readPassword("Enter your password: ");

c. Using Scanner class.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
String s = sc.next();

4. What is the difference between Stack and Heap memory in Java?

Keyword:
stack: each thread has a private JVM stack, holds local variable, method invocation and return.

heap: shared among all thread, all class instances and arrays are allocated here.

Answer:
a. Each thread has a private JVM stack, created at the same time as the thread. A stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return.
JVM has a heap that is shared among all threads. The heap is created on virtual machine start-up. The heap is the runtime data area from which memory for all class instances and arrays is allocated.

For example:
public class User {
    int id;      // instance variable
    String name; // instance variable
    public User(int id, String name) {
         this.id = id;
         this.name = name;
    }
}
......
public static void main(String[] args) {
    User user;  // local variable - reference
    user = new User(1, "Jerry");
    int n = 2;  // local variable - primitive
}
The reference variable "user" is stored on the stack, it refer to a User instance. The primitive variable "n" is stored on the stack.
The User instance itself (including instance variables "id" and "name") is stored on the heap.

b. Variables stored in stacks are only visible to the owner Thread, while objects created in heap are visible to all thread.

c. If there is no memory left in stack, JVM will throw java.lang.StackOverFlowError. If there is no more heap space for creating object, JVM will throw java.lang.OutOfMemoryError: Java Heap Space.

5. What is OutofMemoryError in Java? How to avoid it?

Answer:
java.lang.OutOfMemoryError is a runtime error thrown when JVM cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

Usually, there two types of java.lang.OutOfMemoryError:
OutOfMemoryError: Java heap space
OutOfMemoryError: PermGen space

If OutOfMemoryError: Java heap space occurs, you can solve it by increasing JVM heap size using JVM option: -Xmx

If OutOfMemoryError: PermGen space occurs, it means that you have exceeded Java's fixed 64MB block for loading class files, you can increase PermGen size using JVM option:
-XX:MaxPermSize=…

6. What is Garbage Collection?

Answer:
Garbage collection (GC) is a form of automatic memory management. The garbage collector attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program.

In Java, GC is the process of looking at heap memory, identifying which objects are in use and which are not, and deleting the unused objects.

An in use object, or a referenced object, means that some part of your program still maintains a pointer to that object.

An unused object, or unreferenced object, is no longer referenced by any part of your program. So the memory used by an unreferenced object can be reclaimed.

7. Explain JVM options related to Garbage Collection.

Answer:
-Xms256m or -XX:InitialHeapSize=256m
    Set initial size of JVM heap (young + old).

-Xmx2g or -XX:MaxHeapSize=2g
    Set max size of JVM heap (young + old).

-XX:NewSize=64m -XX:MaxNewSize=64m
    Set absolute initial and max size of young generation (Eden + 2 Survivors).

-XX:NewRatio=2
    Set ration of young vs old generation. NewRatio=3 means old generation will be twice the size of young generation.

-XX:SurvivorRatio=15
    Set size of single survivor space relative to Eden space size.

-XX:PermSize=256m -XX:MaxPermSize=1g
    Set initial and max size of permanent space.

8. What is the difference between Serializable and Externalizable interface?

Answer:
Serializable interface is a marker interface, it does not contain any method.
Externalizable interface extends Serializable interface, adds two methods writeExternal() and readExternal() which are automatically called during serialization and deserialization.

Serializable interface provides a inbuilt serialization mechanism. Externalizable enables you to define custom serialization mechanism.

9. Describe different types of ClassLoader.

Keyword:
Bootstrap ClassLoader
Extension ClassLoader
System ClassLoader

Answer:
There are three types of ClassLoader:

Bootstrap ClassLoader: load standard JDK class files from rt.jar and it is parent of all class loaders. Bootstrap class loader don't have any parents, if you call String.class.getClassLoader() it will return null.

Extension ClassLoader: load class form jre/lib/ext directory or any other directory pointed by java.ext.dirs system property.

System ClassLoader: load application specific classes from CLASSPATH environment variable, -classpath or -cp command line option, Class-Path attribute of Manifest file inside JAR.

10. How to create a custom ClassLoader?

Answer:
First, extends java.lang.ClassLader or its subclass,
Then, set the parent class loader in the constructor,
Last, override the findClass() method to implement the custom load logic.

Example:
public class MyClassLoader extends ClassLoader {
    public MyClassLoader() {
        super(MyClassLoader.class.getClassLoader());
    }

    public Class findClass(String className) {
        //custom load logic
        //……
    }
}

More Java IO, JVM & GC interview questions and answers: Java Interview Notes

  • What is InputStream/OutputStream, Reader/Writer and InputStreamReader/OutputStreamWriter?
  • How to copy files using Java I/O?
  • What are transient variables? What role do they play in Serialization process?
  • Explain the structure of Java heap.
  • What is StackOverflowError? How to avoid it?
  • When an object becomes eligible for garbage collection?
  • What are WeakReference, SoftReference and PhantomReference?
  • Explain Class Loader delegation model.
  • How to explicitly load a class?
  • ......

Java Interview Notes

300+ frequently asked Java interview questions with concise summaries and detailed answers. Topics include: Java & OOP, Strings & Collections, IO JVM & GC, Multithreading, Generics Reflection & Annotations, Design Patterns, Java EE, Spring, JPA & Hibernate.



JavaScript Interview Notes

100+ frequently asked JavaScript interview questions with concise summaries and detailed answers. Topics include: JavaScript Basics, DOM, BOM, Object-Oriented JavaScript, Function, Scope, Closure, JSON, XML, Ajax, jQuery. 
Download on the AppStore    Get it On Google Play

 SQL Interview Notes

100+ frequently asked SQL and Database interview questions with concise summaries and detailed answers.  
Topics include: SQL Basic Concepts, SQL DDL & DML, Advanced SQL, Database Design and Performance Tuning.  
Download on the AppStore    Get it On Google Play